clang 20.0.0git
SemaExpr.cpp
Go to the documentation of this file.
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"
18#include "clang/AST/ASTLambda.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/DeclObjC.h"
26#include "clang/AST/Expr.h"
27#include "clang/AST/ExprCXX.h"
28#include "clang/AST/ExprObjC.h"
31#include "clang/AST/Type.h"
32#include "clang/AST/TypeLoc.h"
43#include "clang/Sema/DeclSpec.h"
48#include "clang/Sema/Lookup.h"
49#include "clang/Sema/Overload.h"
51#include "clang/Sema/Scope.h"
53#include "clang/Sema/SemaCUDA.h"
55#include "clang/Sema/SemaHLSL.h"
57#include "clang/Sema/SemaObjC.h"
60#include "clang/Sema/Template.h"
61#include "llvm/ADT/STLExtras.h"
62#include "llvm/ADT/STLForwardCompat.h"
63#include "llvm/ADT/StringExtras.h"
64#include "llvm/Support/ConvertUTF.h"
65#include "llvm/Support/SaveAndRestore.h"
66#include "llvm/Support/TimeProfiler.h"
67#include "llvm/Support/TypeSize.h"
68#include <optional>
69
70using namespace clang;
71using namespace sema;
72
73bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
74 // See if this is an auto-typed variable whose initializer we are parsing.
75 if (ParsingInitForAutoVars.count(D))
76 return false;
77
78 // See if this is a deleted function.
79 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
80 if (FD->isDeleted())
81 return false;
82
83 // If the function has a deduced return type, and we can't deduce it,
84 // then we can't use it either.
85 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
86 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
87 return false;
88
89 // See if this is an aligned allocation/deallocation function that is
90 // unavailable.
91 if (TreatUnavailableAsInvalid &&
93 return false;
94 }
95
96 // See if this function is unavailable.
97 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
98 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
99 return false;
100
101 if (isa<UnresolvedUsingIfExistsDecl>(D))
102 return false;
103
104 return true;
105}
106
108 // Warn if this is used but marked unused.
109 if (const auto *A = D->getAttr<UnusedAttr>()) {
110 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
111 // should diagnose them.
112 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
113 A->getSemanticSpelling() != UnusedAttr::C23_maybe_unused) {
114 const Decl *DC = cast_or_null<Decl>(S.ObjC().getCurObjCLexicalContext());
115 if (DC && !DC->hasAttr<UnusedAttr>())
116 S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
117 }
118 }
119}
120
122 assert(Decl && Decl->isDeleted());
123
124 if (Decl->isDefaulted()) {
125 // If the method was explicitly defaulted, point at that declaration.
126 if (!Decl->isImplicit())
127 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
128
129 // Try to diagnose why this special member function was implicitly
130 // deleted. This might fail, if that reason no longer applies.
132 return;
133 }
134
135 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
136 if (Ctor && Ctor->isInheritingConstructor())
138
139 Diag(Decl->getLocation(), diag::note_availability_specified_here)
140 << Decl << 1;
141}
142
143/// Determine whether a FunctionDecl was ever declared with an
144/// explicit storage class.
146 for (auto *I : D->redecls()) {
147 if (I->getStorageClass() != SC_None)
148 return true;
149 }
150 return false;
151}
152
153/// Check whether we're in an extern inline function and referring to a
154/// variable or function with internal linkage (C11 6.7.4p3).
155///
156/// This is only a warning because we used to silently accept this code, but
157/// in many cases it will not behave correctly. This is not enabled in C++ mode
158/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
159/// and so while there may still be user mistakes, most of the time we can't
160/// prove that there are errors.
162 const NamedDecl *D,
164 // This is disabled under C++; there are too many ways for this to fire in
165 // contexts where the warning is a false positive, or where it is technically
166 // correct but benign.
167 if (S.getLangOpts().CPlusPlus)
168 return;
169
170 // Check if this is an inlined function or method.
171 FunctionDecl *Current = S.getCurFunctionDecl();
172 if (!Current)
173 return;
174 if (!Current->isInlined())
175 return;
176 if (!Current->isExternallyVisible())
177 return;
178
179 // Check if the decl has internal linkage.
180 if (D->getFormalLinkage() != Linkage::Internal)
181 return;
182
183 // Downgrade from ExtWarn to Extension if
184 // (1) the supposedly external inline function is in the main file,
185 // and probably won't be included anywhere else.
186 // (2) the thing we're referencing is a pure function.
187 // (3) the thing we're referencing is another inline function.
188 // This last can give us false negatives, but it's better than warning on
189 // wrappers for simple C library functions.
190 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
191 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
192 if (!DowngradeWarning && UsedFn)
193 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
194
195 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
196 : diag::ext_internal_in_extern_inline)
197 << /*IsVar=*/!UsedFn << D;
198
200
201 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
202 << D;
203}
204
206 const FunctionDecl *First = Cur->getFirstDecl();
207
208 // Suggest "static" on the function, if possible.
210 SourceLocation DeclBegin = First->getSourceRange().getBegin();
211 Diag(DeclBegin, diag::note_convert_inline_to_static)
212 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
213 }
214}
215
217 const ObjCInterfaceDecl *UnknownObjCClass,
218 bool ObjCPropertyAccess,
219 bool AvoidPartialAvailabilityChecks,
220 ObjCInterfaceDecl *ClassReceiver,
221 bool SkipTrailingRequiresClause) {
222 SourceLocation Loc = Locs.front();
223 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
224 // If there were any diagnostics suppressed by template argument deduction,
225 // emit them now.
226 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
227 if (Pos != SuppressedDiagnostics.end()) {
228 for (const PartialDiagnosticAt &Suppressed : Pos->second)
229 Diag(Suppressed.first, Suppressed.second);
230
231 // Clear out the list of suppressed diagnostics, so that we don't emit
232 // them again for this specialization. However, we don't obsolete this
233 // entry from the table, because we want to avoid ever emitting these
234 // diagnostics again.
235 Pos->second.clear();
236 }
237
238 // C++ [basic.start.main]p3:
239 // The function 'main' shall not be used within a program.
240 if (cast<FunctionDecl>(D)->isMain())
241 Diag(Loc, diag::ext_main_used);
242
243 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
244 }
245
246 // See if this is an auto-typed variable whose initializer we are parsing.
247 if (ParsingInitForAutoVars.count(D)) {
248 if (isa<BindingDecl>(D)) {
249 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
250 << D->getDeclName();
251 } else {
252 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
253 << D->getDeclName() << cast<VarDecl>(D)->getType();
254 }
255 return true;
256 }
257
258 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
259 // See if this is a deleted function.
260 if (FD->isDeleted()) {
261 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
262 if (Ctor && Ctor->isInheritingConstructor())
263 Diag(Loc, diag::err_deleted_inherited_ctor_use)
264 << Ctor->getParent()
265 << Ctor->getInheritedConstructor().getConstructor()->getParent();
266 else {
267 StringLiteral *Msg = FD->getDeletedMessage();
268 Diag(Loc, diag::err_deleted_function_use)
269 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef());
270 }
272 return true;
273 }
274
275 // [expr.prim.id]p4
276 // A program that refers explicitly or implicitly to a function with a
277 // trailing requires-clause whose constraint-expression is not satisfied,
278 // other than to declare it, is ill-formed. [...]
279 //
280 // See if this is a function with constraints that need to be satisfied.
281 // Check this before deducing the return type, as it might instantiate the
282 // definition.
283 if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) {
284 ConstraintSatisfaction Satisfaction;
285 if (CheckFunctionConstraints(FD, Satisfaction, Loc,
286 /*ForOverloadResolution*/ true))
287 // A diagnostic will have already been generated (non-constant
288 // constraint expression, for example)
289 return true;
290 if (!Satisfaction.IsSatisfied) {
291 Diag(Loc,
292 diag::err_reference_to_function_with_unsatisfied_constraints)
293 << D;
294 DiagnoseUnsatisfiedConstraint(Satisfaction);
295 return true;
296 }
297 }
298
299 // If the function has a deduced return type, and we can't deduce it,
300 // then we can't use it either.
301 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
303 return true;
304
305 if (getLangOpts().CUDA && !CUDA().CheckCall(Loc, FD))
306 return true;
307
308 }
309
310 if (auto *Concept = dyn_cast<ConceptDecl>(D);
312 return true;
313
314 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
315 // Lambdas are only default-constructible or assignable in C++2a onwards.
316 if (MD->getParent()->isLambda() &&
317 ((isa<CXXConstructorDecl>(MD) &&
318 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
319 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
320 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
321 << !isa<CXXConstructorDecl>(MD);
322 }
323 }
324
325 auto getReferencedObjCProp = [](const NamedDecl *D) ->
326 const ObjCPropertyDecl * {
327 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
328 return MD->findPropertyDecl();
329 return nullptr;
330 };
331 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
333 return true;
335 return true;
336 }
337
338 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
339 // Only the variables omp_in and omp_out are allowed in the combiner.
340 // Only the variables omp_priv and omp_orig are allowed in the
341 // initializer-clause.
342 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
343 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
344 isa<VarDecl>(D)) {
345 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
347 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
348 return true;
349 }
350
351 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
352 // List-items in map clauses on this construct may only refer to the declared
353 // variable var and entities that could be referenced by a procedure defined
354 // at the same location.
355 // [OpenMP 5.2] Also allow iterator declared variables.
356 if (LangOpts.OpenMP && isa<VarDecl>(D) &&
357 !OpenMP().isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
358 Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
360 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
361 return true;
362 }
363
364 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
365 Diag(Loc, diag::err_use_of_empty_using_if_exists);
366 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
367 return true;
368 }
369
370 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
371 AvoidPartialAvailabilityChecks, ClassReceiver);
372
373 DiagnoseUnusedOfDecl(*this, D, Loc);
374
376
377 if (D->hasAttr<AvailableOnlyInDefaultEvalMethodAttr>()) {
378 if (getLangOpts().getFPEvalMethod() !=
381 PP.getCurrentFPEvalMethod() != getLangOpts().getFPEvalMethod())
382 Diag(D->getLocation(),
383 diag::err_type_available_only_in_default_eval_method)
384 << D->getName();
385 }
386
387 if (auto *VD = dyn_cast<ValueDecl>(D))
388 checkTypeSupport(VD->getType(), Loc, VD);
389
390 if (LangOpts.SYCLIsDevice ||
391 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)) {
393 if (const auto *VD = dyn_cast<VarDecl>(D))
394 if (VD->getTLSKind() != VarDecl::TLS_None)
395 targetDiag(*Locs.begin(), diag::err_thread_unsupported);
396 }
397
398 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
400 // C++ [expr.prim.req.nested] p3
401 // A local parameter shall only appear as an unevaluated operand
402 // (Clause 8) within the constraint-expression.
403 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
404 << D;
405 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
406 return true;
407 }
408
409 return false;
410}
411
413 ArrayRef<Expr *> Args) {
414 const SentinelAttr *Attr = D->getAttr<SentinelAttr>();
415 if (!Attr)
416 return;
417
418 // The number of formal parameters of the declaration.
419 unsigned NumFormalParams;
420
421 // The kind of declaration. This is also an index into a %select in
422 // the diagnostic.
423 enum { CK_Function, CK_Method, CK_Block } CalleeKind;
424
425 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
426 NumFormalParams = MD->param_size();
427 CalleeKind = CK_Method;
428 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
429 NumFormalParams = FD->param_size();
430 CalleeKind = CK_Function;
431 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
432 QualType Ty = VD->getType();
433 const FunctionType *Fn = nullptr;
434 if (const auto *PtrTy = Ty->getAs<PointerType>()) {
435 Fn = PtrTy->getPointeeType()->getAs<FunctionType>();
436 if (!Fn)
437 return;
438 CalleeKind = CK_Function;
439 } else if (const auto *PtrTy = Ty->getAs<BlockPointerType>()) {
440 Fn = PtrTy->getPointeeType()->castAs<FunctionType>();
441 CalleeKind = CK_Block;
442 } else {
443 return;
444 }
445
446 if (const auto *proto = dyn_cast<FunctionProtoType>(Fn))
447 NumFormalParams = proto->getNumParams();
448 else
449 NumFormalParams = 0;
450 } else {
451 return;
452 }
453
454 // "NullPos" is the number of formal parameters at the end which
455 // effectively count as part of the variadic arguments. This is
456 // useful if you would prefer to not have *any* formal parameters,
457 // but the language forces you to have at least one.
458 unsigned NullPos = Attr->getNullPos();
459 assert((NullPos == 0 || NullPos == 1) && "invalid null position on sentinel");
460 NumFormalParams = (NullPos > NumFormalParams ? 0 : NumFormalParams - NullPos);
461
462 // The number of arguments which should follow the sentinel.
463 unsigned NumArgsAfterSentinel = Attr->getSentinel();
464
465 // If there aren't enough arguments for all the formal parameters,
466 // the sentinel, and the args after the sentinel, complain.
467 if (Args.size() < NumFormalParams + NumArgsAfterSentinel + 1) {
468 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
469 Diag(D->getLocation(), diag::note_sentinel_here) << int(CalleeKind);
470 return;
471 }
472
473 // Otherwise, find the sentinel expression.
474 const Expr *SentinelExpr = Args[Args.size() - NumArgsAfterSentinel - 1];
475 if (!SentinelExpr)
476 return;
477 if (SentinelExpr->isValueDependent())
478 return;
479 if (Context.isSentinelNullExpr(SentinelExpr))
480 return;
481
482 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
483 // or 'NULL' if those are actually defined in the context. Only use
484 // 'nil' for ObjC methods, where it's much more likely that the
485 // variadic arguments form a list of object pointers.
486 SourceLocation MissingNilLoc = getLocForEndOfToken(SentinelExpr->getEndLoc());
487 std::string NullValue;
488 if (CalleeKind == CK_Method && PP.isMacroDefined("nil"))
489 NullValue = "nil";
490 else if (getLangOpts().CPlusPlus11)
491 NullValue = "nullptr";
492 else if (PP.isMacroDefined("NULL"))
493 NullValue = "NULL";
494 else
495 NullValue = "(void*) 0";
496
497 if (MissingNilLoc.isInvalid())
498 Diag(Loc, diag::warn_missing_sentinel) << int(CalleeKind);
499 else
500 Diag(MissingNilLoc, diag::warn_missing_sentinel)
501 << int(CalleeKind)
502 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
503 Diag(D->getLocation(), diag::note_sentinel_here)
504 << int(CalleeKind) << Attr->getRange();
505}
506
508 return E ? E->getSourceRange() : SourceRange();
509}
510
511//===----------------------------------------------------------------------===//
512// Standard Promotions and Conversions
513//===----------------------------------------------------------------------===//
514
515/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
517 // Handle any placeholder expressions which made it here.
518 if (E->hasPlaceholderType()) {
520 if (result.isInvalid()) return ExprError();
521 E = result.get();
522 }
523
524 QualType Ty = E->getType();
525 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
526
527 if (Ty->isFunctionType()) {
528 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
529 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
531 return ExprError();
532
534 CK_FunctionToPointerDecay).get();
535 } else if (Ty->isArrayType()) {
536 // In C90 mode, arrays only promote to pointers if the array expression is
537 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
538 // type 'array of type' is converted to an expression that has type 'pointer
539 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
540 // that has type 'array of type' ...". The relevant change is "an lvalue"
541 // (C90) to "an expression" (C99).
542 //
543 // C++ 4.2p1:
544 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
545 // T" can be converted to an rvalue of type "pointer to T".
546 //
547 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
549 CK_ArrayToPointerDecay);
550 if (Res.isInvalid())
551 return ExprError();
552 E = Res.get();
553 }
554 }
555 return E;
556}
557
559 // Check to see if we are dereferencing a null pointer. If so,
560 // and if not volatile-qualified, this is undefined behavior that the
561 // optimizer will delete, so warn about it. People sometimes try to use this
562 // to get a deterministic trap and are surprised by clang's behavior. This
563 // only handles the pattern "*null", which is a very syntactic check.
564 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
565 if (UO && UO->getOpcode() == UO_Deref &&
566 UO->getSubExpr()->getType()->isPointerType()) {
567 const LangAS AS =
568 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
569 if ((!isTargetAddressSpace(AS) ||
570 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
571 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
573 !UO->getType().isVolatileQualified()) {
574 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
575 S.PDiag(diag::warn_indirection_through_null)
576 << UO->getSubExpr()->getSourceRange());
577 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
578 S.PDiag(diag::note_indirection_through_null));
579 }
580 }
581}
582
583static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
584 SourceLocation AssignLoc,
585 const Expr* RHS) {
586 const ObjCIvarDecl *IV = OIRE->getDecl();
587 if (!IV)
588 return;
589
590 DeclarationName MemberName = IV->getDeclName();
592 if (!Member || !Member->isStr("isa"))
593 return;
594
595 const Expr *Base = OIRE->getBase();
596 QualType BaseType = Base->getType();
597 if (OIRE->isArrow())
598 BaseType = BaseType->getPointeeType();
599 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
600 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
601 ObjCInterfaceDecl *ClassDeclared = nullptr;
602 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
603 if (!ClassDeclared->getSuperClass()
604 && (*ClassDeclared->ivar_begin()) == IV) {
605 if (RHS) {
606 NamedDecl *ObjectSetClass =
608 &S.Context.Idents.get("object_setClass"),
610 if (ObjectSetClass) {
611 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
612 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
614 "object_setClass(")
616 SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
617 << FixItHint::CreateInsertion(RHSLocEnd, ")");
618 }
619 else
620 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
621 } else {
622 NamedDecl *ObjectGetClass =
624 &S.Context.Idents.get("object_getClass"),
626 if (ObjectGetClass)
627 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
629 "object_getClass(")
631 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
632 else
633 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
634 }
635 S.Diag(IV->getLocation(), diag::note_ivar_decl);
636 }
637 }
638}
639
641 // Handle any placeholder expressions which made it here.
642 if (E->hasPlaceholderType()) {
644 if (result.isInvalid()) return ExprError();
645 E = result.get();
646 }
647
648 // C++ [conv.lval]p1:
649 // A glvalue of a non-function, non-array type T can be
650 // converted to a prvalue.
651 if (!E->isGLValue()) return E;
652
653 QualType T = E->getType();
654 assert(!T.isNull() && "r-value conversion on typeless expression?");
655
656 // lvalue-to-rvalue conversion cannot be applied to types that decay to
657 // pointers (i.e. function or array types).
659 return E;
660
661 // We don't want to throw lvalue-to-rvalue casts on top of
662 // expressions of certain types in C++.
663 if (getLangOpts().CPlusPlus) {
664 if (T == Context.OverloadTy || T->isRecordType() ||
665 (T->isDependentType() && !T->isAnyPointerType() &&
667 return E;
668 }
669
670 // The C standard is actually really unclear on this point, and
671 // DR106 tells us what the result should be but not why. It's
672 // generally best to say that void types just doesn't undergo
673 // lvalue-to-rvalue at all. Note that expressions of unqualified
674 // 'void' type are never l-values, but qualified void can be.
675 if (T->isVoidType())
676 return E;
677
678 // OpenCL usually rejects direct accesses to values of 'half' type.
679 if (getLangOpts().OpenCL &&
680 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
681 T->isHalfType()) {
682 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
683 << 0 << T;
684 return ExprError();
685 }
686
688 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
689 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
690 &Context.Idents.get("object_getClass"),
692 if (ObjectGetClass)
693 Diag(E->getExprLoc(), diag::warn_objc_isa_use)
694 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
696 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
697 else
698 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
699 }
700 else if (const ObjCIvarRefExpr *OIRE =
701 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
702 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
703
704 // C++ [conv.lval]p1:
705 // [...] If T is a non-class type, the type of the prvalue is the
706 // cv-unqualified version of T. Otherwise, the type of the
707 // rvalue is T.
708 //
709 // C99 6.3.2.1p2:
710 // If the lvalue has qualified type, the value has the unqualified
711 // version of the type of the lvalue; otherwise, the value has the
712 // type of the lvalue.
713 if (T.hasQualifiers())
714 T = T.getUnqualifiedType();
715
716 // Under the MS ABI, lock down the inheritance model now.
717 if (T->isMemberPointerType() &&
719 (void)isCompleteType(E->getExprLoc(), T);
720
722 if (Res.isInvalid())
723 return Res;
724 E = Res.get();
725
726 // Loading a __weak object implicitly retains the value, so we need a cleanup to
727 // balance that.
730
733
734 // C++ [conv.lval]p3:
735 // If T is cv std::nullptr_t, the result is a null pointer constant.
736 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
737 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
739
740 // C11 6.3.2.1p2:
741 // ... if the lvalue has atomic type, the value has the non-atomic version
742 // of the type of the lvalue ...
743 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
744 T = Atomic->getValueType().getUnqualifiedType();
745 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
746 nullptr, VK_PRValue, FPOptionsOverride());
747 }
748
749 return Res;
750}
751
754 if (Res.isInvalid())
755 return ExprError();
756 Res = DefaultLvalueConversion(Res.get());
757 if (Res.isInvalid())
758 return ExprError();
759 return Res;
760}
761
763 QualType Ty = E->getType();
764 ExprResult Res = E;
765 // Only do implicit cast for a function type, but not for a pointer
766 // to function type.
767 if (Ty->isFunctionType()) {
769 CK_FunctionToPointerDecay);
770 if (Res.isInvalid())
771 return ExprError();
772 }
773 Res = DefaultLvalueConversion(Res.get());
774 if (Res.isInvalid())
775 return ExprError();
776 return Res.get();
777}
778
779/// UsualUnaryConversions - Performs various conversions that are common to most
780/// operators (C99 6.3). The conversions of array and function types are
781/// sometimes suppressed. For example, the array->pointer conversion doesn't
782/// apply if the array is an argument to the sizeof or address (&) operators.
783/// In these instances, this routine should *not* be called.
785 // First, convert to an r-value.
787 if (Res.isInvalid())
788 return ExprError();
789 E = Res.get();
790
791 QualType Ty = E->getType();
792 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
793
794 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
795 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
796 (getLangOpts().getFPEvalMethod() !=
799 switch (EvalMethod) {
800 default:
801 llvm_unreachable("Unrecognized float evaluation method");
802 break;
804 llvm_unreachable("Float evaluation method should be set by now");
805 break;
808 // Widen the expression to double.
809 return Ty->isComplexType()
812 CK_FloatingComplexCast)
813 : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);
814 break;
817 // Widen the expression to long double.
818 return Ty->isComplexType()
821 CK_FloatingComplexCast)
823 CK_FloatingCast);
824 break;
825 }
826 }
827
828 // Half FP have to be promoted to float unless it is natively supported
829 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
830 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
831
832 // Try to perform integral promotions if the object has a theoretically
833 // promotable type.
835 // C99 6.3.1.1p2:
836 //
837 // The following may be used in an expression wherever an int or
838 // unsigned int may be used:
839 // - an object or expression with an integer type whose integer
840 // conversion rank is less than or equal to the rank of int
841 // and unsigned int.
842 // - A bit-field of type _Bool, int, signed int, or unsigned int.
843 //
844 // If an int can represent all values of the original type, the
845 // value is converted to an int; otherwise, it is converted to an
846 // unsigned int. These are called the integer promotions. All
847 // other types are unchanged by the integer promotions.
848
850 if (!PTy.isNull()) {
851 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
852 return E;
853 }
856 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
857 return E;
858 }
859 }
860 return E;
861}
862
863/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
864/// do not have a prototype. Arguments that have type float or __fp16
865/// are promoted to double. All other argument types are converted by
866/// UsualUnaryConversions().
868 QualType Ty = E->getType();
869 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
870
872 if (Res.isInvalid())
873 return ExprError();
874 E = Res.get();
875
876 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
877 // promote to double.
878 // Note that default argument promotion applies only to float (and
879 // half/fp16); it does not apply to _Float16.
880 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
881 if (BTy && (BTy->getKind() == BuiltinType::Half ||
882 BTy->getKind() == BuiltinType::Float)) {
883 if (getLangOpts().OpenCL &&
884 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
885 if (BTy->getKind() == BuiltinType::Half) {
886 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
887 }
888 } else {
889 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
890 }
891 }
892 if (BTy &&
893 getLangOpts().getExtendIntArgs() ==
898 E = (Ty->isUnsignedIntegerType())
899 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
900 .get()
901 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
903 "Unexpected typesize for LongLongTy");
904 }
905
906 // C++ performs lvalue-to-rvalue conversion as a default argument
907 // promotion, even on class types, but note:
908 // C++11 [conv.lval]p2:
909 // When an lvalue-to-rvalue conversion occurs in an unevaluated
910 // operand or a subexpression thereof the value contained in the
911 // referenced object is not accessed. Otherwise, if the glvalue
912 // has a class type, the conversion copy-initializes a temporary
913 // of type T from the glvalue and the result of the conversion
914 // is a prvalue for the temporary.
915 // FIXME: add some way to gate this entire thing for correctness in
916 // potentially potentially evaluated contexts.
920 E->getExprLoc(), E);
921 if (Temp.isInvalid())
922 return ExprError();
923 E = Temp.get();
924 }
925
926 // C++ [expr.call]p7, per CWG722:
927 // An argument that has (possibly cv-qualified) type std::nullptr_t is
928 // converted to void* ([conv.ptr]).
929 // (This does not apply to C23 nullptr)
931 E = ImpCastExprToType(E, Context.VoidPtrTy, CK_NullToPointer).get();
932
933 return E;
934}
935
937 if (Ty->isIncompleteType()) {
938 // C++11 [expr.call]p7:
939 // After these conversions, if the argument does not have arithmetic,
940 // enumeration, pointer, pointer to member, or class type, the program
941 // is ill-formed.
942 //
943 // Since we've already performed null pointer conversion, array-to-pointer
944 // decay and function-to-pointer decay, the only such type in C++ is cv
945 // void. This also handles initializer lists as variadic arguments.
946 if (Ty->isVoidType())
947 return VAK_Invalid;
948
949 if (Ty->isObjCObjectType())
950 return VAK_Invalid;
951 return VAK_Valid;
952 }
953
955 return VAK_Invalid;
956
957 if (Context.getTargetInfo().getTriple().isWasm() &&
959 return VAK_Invalid;
960 }
961
962 if (Ty.isCXX98PODType(Context))
963 return VAK_Valid;
964
965 // C++11 [expr.call]p7:
966 // Passing a potentially-evaluated argument of class type (Clause 9)
967 // having a non-trivial copy constructor, a non-trivial move constructor,
968 // or a non-trivial destructor, with no corresponding parameter,
969 // is conditionally-supported with implementation-defined semantics.
972 if (!Record->hasNonTrivialCopyConstructor() &&
973 !Record->hasNonTrivialMoveConstructor() &&
974 !Record->hasNonTrivialDestructor())
975 return VAK_ValidInCXX11;
976
977 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
978 return VAK_Valid;
979
980 if (Ty->isObjCObjectType())
981 return VAK_Invalid;
982
984 return VAK_Valid;
985
986 if (getLangOpts().MSVCCompat)
987 return VAK_MSVCUndefined;
988
990 return VAK_Valid;
991
992 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
993 // permitted to reject them. We should consider doing so.
994 return VAK_Undefined;
995}
996
998 // Don't allow one to pass an Objective-C interface to a vararg.
999 const QualType &Ty = E->getType();
1000 VarArgKind VAK = isValidVarArgType(Ty);
1001
1002 // Complain about passing non-POD types through varargs.
1003 switch (VAK) {
1004 case VAK_ValidInCXX11:
1006 E->getBeginLoc(), nullptr,
1007 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
1008 [[fallthrough]];
1009 case VAK_Valid:
1010 if (Ty->isRecordType()) {
1011 // This is unlikely to be what the user intended. If the class has a
1012 // 'c_str' member function, the user probably meant to call that.
1013 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1014 PDiag(diag::warn_pass_class_arg_to_vararg)
1015 << Ty << CT << hasCStrMethod(E) << ".c_str()");
1016 }
1017 break;
1018
1019 case VAK_Undefined:
1020 case VAK_MSVCUndefined:
1021 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1022 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
1023 << getLangOpts().CPlusPlus11 << Ty << CT);
1024 break;
1025
1026 case VAK_Invalid:
1028 Diag(E->getBeginLoc(),
1029 diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1030 << Ty << CT;
1031 else if (Ty->isObjCObjectType())
1032 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1033 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
1034 << Ty << CT);
1035 else
1036 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
1037 << isa<InitListExpr>(E) << Ty << CT;
1038 break;
1039 }
1040}
1041
1043 FunctionDecl *FDecl) {
1044 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1045 // Strip the unbridged-cast placeholder expression off, if applicable.
1046 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1047 (CT == VariadicMethod ||
1048 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1050
1051 // Otherwise, do normal placeholder checking.
1052 } else {
1054 if (ExprRes.isInvalid())
1055 return ExprError();
1056 E = ExprRes.get();
1057 }
1058 }
1059
1061 if (ExprRes.isInvalid())
1062 return ExprError();
1063
1064 // Copy blocks to the heap.
1065 if (ExprRes.get()->getType()->isBlockPointerType())
1066 maybeExtendBlockObject(ExprRes);
1067
1068 E = ExprRes.get();
1069
1070 // Diagnostics regarding non-POD argument types are
1071 // emitted along with format string checking in Sema::CheckFunctionCall().
1073 // Turn this into a trap.
1074 CXXScopeSpec SS;
1075 SourceLocation TemplateKWLoc;
1076 UnqualifiedId Name;
1077 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1078 E->getBeginLoc());
1079 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1080 /*HasTrailingLParen=*/true,
1081 /*IsAddressOfOperand=*/false);
1082 if (TrapFn.isInvalid())
1083 return ExprError();
1084
1085 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), {},
1086 E->getEndLoc());
1087 if (Call.isInvalid())
1088 return ExprError();
1089
1090 ExprResult Comma =
1091 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1092 if (Comma.isInvalid())
1093 return ExprError();
1094 return Comma.get();
1095 }
1096
1097 if (!getLangOpts().CPlusPlus &&
1099 diag::err_call_incomplete_argument))
1100 return ExprError();
1101
1102 return E;
1103}
1104
1105/// Convert complex integers to complex floats and real integers to
1106/// real floats as required for complex arithmetic. Helper function of
1107/// UsualArithmeticConversions()
1108///
1109/// \return false if the integer expression is an integer type and is
1110/// successfully converted to the (complex) float type.
1112 ExprResult &ComplexExpr,
1113 QualType IntTy,
1114 QualType ComplexTy,
1115 bool SkipCast) {
1116 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1117 if (SkipCast) return false;
1118 if (IntTy->isIntegerType()) {
1119 QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();
1120 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1121 } else {
1122 assert(IntTy->isComplexIntegerType());
1123 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1124 CK_IntegralComplexToFloatingComplex);
1125 }
1126 return false;
1127}
1128
1129// This handles complex/complex, complex/float, or float/complex.
1130// When both operands are complex, the shorter operand is converted to the
1131// type of the longer, and that is the type of the result. This corresponds
1132// to what is done when combining two real floating-point operands.
1133// The fun begins when size promotion occur across type domains.
1134// From H&S 6.3.4: When one operand is complex and the other is a real
1135// floating-point type, the less precise type is converted, within it's
1136// real or complex domain, to the precision of the other type. For example,
1137// when combining a "long double" with a "double _Complex", the
1138// "double _Complex" is promoted to "long double _Complex".
1140 QualType ShorterType,
1141 QualType LongerType,
1142 bool PromotePrecision) {
1143 bool LongerIsComplex = isa<ComplexType>(LongerType.getCanonicalType());
1145 LongerIsComplex ? LongerType : S.Context.getComplexType(LongerType);
1146
1147 if (PromotePrecision) {
1148 if (isa<ComplexType>(ShorterType.getCanonicalType())) {
1149 Shorter =
1150 S.ImpCastExprToType(Shorter.get(), Result, CK_FloatingComplexCast);
1151 } else {
1152 if (LongerIsComplex)
1153 LongerType = LongerType->castAs<ComplexType>()->getElementType();
1154 Shorter = S.ImpCastExprToType(Shorter.get(), LongerType, CK_FloatingCast);
1155 }
1156 }
1157 return Result;
1158}
1159
1160/// Handle arithmetic conversion with complex types. Helper function of
1161/// UsualArithmeticConversions()
1163 ExprResult &RHS, QualType LHSType,
1164 QualType RHSType, bool IsCompAssign) {
1165 // Handle (complex) integer types.
1166 if (!handleComplexIntegerToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1167 /*SkipCast=*/false))
1168 return LHSType;
1169 if (!handleComplexIntegerToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1170 /*SkipCast=*/IsCompAssign))
1171 return RHSType;
1172
1173 // Compute the rank of the two types, regardless of whether they are complex.
1174 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1175 if (Order < 0)
1176 // Promote the precision of the LHS if not an assignment.
1177 return handleComplexFloatConversion(S, LHS, LHSType, RHSType,
1178 /*PromotePrecision=*/!IsCompAssign);
1179 // Promote the precision of the RHS unless it is already the same as the LHS.
1180 return handleComplexFloatConversion(S, RHS, RHSType, LHSType,
1181 /*PromotePrecision=*/Order > 0);
1182}
1183
1184/// Handle arithmetic conversion from integer to float. Helper function
1185/// of UsualArithmeticConversions()
1187 ExprResult &IntExpr,
1188 QualType FloatTy, QualType IntTy,
1189 bool ConvertFloat, bool ConvertInt) {
1190 if (IntTy->isIntegerType()) {
1191 if (ConvertInt)
1192 // Convert intExpr to the lhs floating point type.
1193 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1194 CK_IntegralToFloating);
1195 return FloatTy;
1196 }
1197
1198 // Convert both sides to the appropriate complex float.
1199 assert(IntTy->isComplexIntegerType());
1200 QualType result = S.Context.getComplexType(FloatTy);
1201
1202 // _Complex int -> _Complex float
1203 if (ConvertInt)
1204 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1205 CK_IntegralComplexToFloatingComplex);
1206
1207 // float -> _Complex float
1208 if (ConvertFloat)
1209 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1210 CK_FloatingRealToComplex);
1211
1212 return result;
1213}
1214
1215/// Handle arithmethic conversion with floating point types. Helper
1216/// function of UsualArithmeticConversions()
1218 ExprResult &RHS, QualType LHSType,
1219 QualType RHSType, bool IsCompAssign) {
1220 bool LHSFloat = LHSType->isRealFloatingType();
1221 bool RHSFloat = RHSType->isRealFloatingType();
1222
1223 // N1169 4.1.4: If one of the operands has a floating type and the other
1224 // operand has a fixed-point type, the fixed-point operand
1225 // is converted to the floating type [...]
1226 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1227 if (LHSFloat)
1228 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1229 else if (!IsCompAssign)
1230 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1231 return LHSFloat ? LHSType : RHSType;
1232 }
1233
1234 // If we have two real floating types, convert the smaller operand
1235 // to the bigger result.
1236 if (LHSFloat && RHSFloat) {
1237 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1238 if (order > 0) {
1239 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1240 return LHSType;
1241 }
1242
1243 assert(order < 0 && "illegal float comparison");
1244 if (!IsCompAssign)
1245 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1246 return RHSType;
1247 }
1248
1249 if (LHSFloat) {
1250 // Half FP has to be promoted to float unless it is natively supported
1251 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1252 LHSType = S.Context.FloatTy;
1253
1254 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1255 /*ConvertFloat=*/!IsCompAssign,
1256 /*ConvertInt=*/ true);
1257 }
1258 assert(RHSFloat);
1259 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1260 /*ConvertFloat=*/ true,
1261 /*ConvertInt=*/!IsCompAssign);
1262}
1263
1264/// Diagnose attempts to convert between __float128, __ibm128 and
1265/// long double if there is no support for such conversion.
1266/// Helper function of UsualArithmeticConversions().
1267static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1268 QualType RHSType) {
1269 // No issue if either is not a floating point type.
1270 if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1271 return false;
1272
1273 // No issue if both have the same 128-bit float semantics.
1274 auto *LHSComplex = LHSType->getAs<ComplexType>();
1275 auto *RHSComplex = RHSType->getAs<ComplexType>();
1276
1277 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1278 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1279
1280 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1281 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1282
1283 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1284 &RHSSem != &llvm::APFloat::IEEEquad()) &&
1285 (&LHSSem != &llvm::APFloat::IEEEquad() ||
1286 &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1287 return false;
1288
1289 return true;
1290}
1291
1292typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1293
1294namespace {
1295/// These helper callbacks are placed in an anonymous namespace to
1296/// permit their use as function template parameters.
1297ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1298 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1299}
1300
1301ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1302 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1303 CK_IntegralComplexCast);
1304}
1305}
1306
1307/// Handle integer arithmetic conversions. Helper function of
1308/// UsualArithmeticConversions()
1309template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1311 ExprResult &RHS, QualType LHSType,
1312 QualType RHSType, bool IsCompAssign) {
1313 // The rules for this case are in C99 6.3.1.8
1314 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1315 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1316 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1317 if (LHSSigned == RHSSigned) {
1318 // Same signedness; use the higher-ranked type
1319 if (order >= 0) {
1320 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1321 return LHSType;
1322 } else if (!IsCompAssign)
1323 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1324 return RHSType;
1325 } else if (order != (LHSSigned ? 1 : -1)) {
1326 // The unsigned type has greater than or equal rank to the
1327 // signed type, so use the unsigned type
1328 if (RHSSigned) {
1329 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1330 return LHSType;
1331 } else if (!IsCompAssign)
1332 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1333 return RHSType;
1334 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1335 // The two types are different widths; if we are here, that
1336 // means the signed type is larger than the unsigned type, so
1337 // use the signed type.
1338 if (LHSSigned) {
1339 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1340 return LHSType;
1341 } else if (!IsCompAssign)
1342 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1343 return RHSType;
1344 } else {
1345 // The signed type is higher-ranked than the unsigned type,
1346 // but isn't actually any bigger (like unsigned int and long
1347 // on most 32-bit systems). Use the unsigned type corresponding
1348 // to the signed type.
1349 QualType result =
1350 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1351 RHS = (*doRHSCast)(S, RHS.get(), result);
1352 if (!IsCompAssign)
1353 LHS = (*doLHSCast)(S, LHS.get(), result);
1354 return result;
1355 }
1356}
1357
1358/// Handle conversions with GCC complex int extension. Helper function
1359/// of UsualArithmeticConversions()
1361 ExprResult &RHS, QualType LHSType,
1362 QualType RHSType,
1363 bool IsCompAssign) {
1364 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1365 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1366
1367 if (LHSComplexInt && RHSComplexInt) {
1368 QualType LHSEltType = LHSComplexInt->getElementType();
1369 QualType RHSEltType = RHSComplexInt->getElementType();
1370 QualType ScalarType =
1371 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1372 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1373
1374 return S.Context.getComplexType(ScalarType);
1375 }
1376
1377 if (LHSComplexInt) {
1378 QualType LHSEltType = LHSComplexInt->getElementType();
1379 QualType ScalarType =
1380 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1381 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1383 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1384 CK_IntegralRealToComplex);
1385
1386 return ComplexType;
1387 }
1388
1389 assert(RHSComplexInt);
1390
1391 QualType RHSEltType = RHSComplexInt->getElementType();
1392 QualType ScalarType =
1393 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1394 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1396
1397 if (!IsCompAssign)
1398 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1399 CK_IntegralRealToComplex);
1400 return ComplexType;
1401}
1402
1403/// Return the rank of a given fixed point or integer type. The value itself
1404/// doesn't matter, but the values must be increasing with proper increasing
1405/// rank as described in N1169 4.1.1.
1406static unsigned GetFixedPointRank(QualType Ty) {
1407 const auto *BTy = Ty->getAs<BuiltinType>();
1408 assert(BTy && "Expected a builtin type.");
1409
1410 switch (BTy->getKind()) {
1411 case BuiltinType::ShortFract:
1412 case BuiltinType::UShortFract:
1413 case BuiltinType::SatShortFract:
1414 case BuiltinType::SatUShortFract:
1415 return 1;
1416 case BuiltinType::Fract:
1417 case BuiltinType::UFract:
1418 case BuiltinType::SatFract:
1419 case BuiltinType::SatUFract:
1420 return 2;
1421 case BuiltinType::LongFract:
1422 case BuiltinType::ULongFract:
1423 case BuiltinType::SatLongFract:
1424 case BuiltinType::SatULongFract:
1425 return 3;
1426 case BuiltinType::ShortAccum:
1427 case BuiltinType::UShortAccum:
1428 case BuiltinType::SatShortAccum:
1429 case BuiltinType::SatUShortAccum:
1430 return 4;
1431 case BuiltinType::Accum:
1432 case BuiltinType::UAccum:
1433 case BuiltinType::SatAccum:
1434 case BuiltinType::SatUAccum:
1435 return 5;
1436 case BuiltinType::LongAccum:
1437 case BuiltinType::ULongAccum:
1438 case BuiltinType::SatLongAccum:
1439 case BuiltinType::SatULongAccum:
1440 return 6;
1441 default:
1442 if (BTy->isInteger())
1443 return 0;
1444 llvm_unreachable("Unexpected fixed point or integer type");
1445 }
1446}
1447
1448/// handleFixedPointConversion - Fixed point operations between fixed
1449/// point types and integers or other fixed point types do not fall under
1450/// usual arithmetic conversion since these conversions could result in loss
1451/// of precsision (N1169 4.1.4). These operations should be calculated with
1452/// the full precision of their result type (N1169 4.1.6.2.1).
1454 QualType RHSTy) {
1455 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1456 "Expected at least one of the operands to be a fixed point type");
1457 assert((LHSTy->isFixedPointOrIntegerType() ||
1458 RHSTy->isFixedPointOrIntegerType()) &&
1459 "Special fixed point arithmetic operation conversions are only "
1460 "applied to ints or other fixed point types");
1461
1462 // If one operand has signed fixed-point type and the other operand has
1463 // unsigned fixed-point type, then the unsigned fixed-point operand is
1464 // converted to its corresponding signed fixed-point type and the resulting
1465 // type is the type of the converted operand.
1466 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1468 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1470
1471 // The result type is the type with the highest rank, whereby a fixed-point
1472 // conversion rank is always greater than an integer conversion rank; if the
1473 // type of either of the operands is a saturating fixedpoint type, the result
1474 // type shall be the saturating fixed-point type corresponding to the type
1475 // with the highest rank; the resulting value is converted (taking into
1476 // account rounding and overflow) to the precision of the resulting type.
1477 // Same ranks between signed and unsigned types are resolved earlier, so both
1478 // types are either signed or both unsigned at this point.
1479 unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1480 unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1481
1482 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1483
1485 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1486
1487 return ResultTy;
1488}
1489
1490/// Check that the usual arithmetic conversions can be performed on this pair of
1491/// expressions that might be of enumeration type.
1494 Sema::ArithConvKind ACK) {
1495 // C++2a [expr.arith.conv]p1:
1496 // If one operand is of enumeration type and the other operand is of a
1497 // different enumeration type or a floating-point type, this behavior is
1498 // deprecated ([depr.arith.conv.enum]).
1499 //
1500 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1501 // Eventually we will presumably reject these cases (in C++23 onwards?).
1503 R = RHS->getEnumCoercedType(S.Context);
1504 bool LEnum = L->isUnscopedEnumerationType(),
1505 REnum = R->isUnscopedEnumerationType();
1506 bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1507 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1508 (REnum && L->isFloatingType())) {
1509 S.Diag(Loc, S.getLangOpts().CPlusPlus26
1510 ? diag::err_arith_conv_enum_float_cxx26
1511 : S.getLangOpts().CPlusPlus20
1512 ? diag::warn_arith_conv_enum_float_cxx20
1513 : diag::warn_arith_conv_enum_float)
1514 << LHS->getSourceRange() << RHS->getSourceRange() << (int)ACK << LEnum
1515 << L << R;
1516 } else if (!IsCompAssign && LEnum && REnum &&
1518 unsigned DiagID;
1519 // In C++ 26, usual arithmetic conversions between 2 different enum types
1520 // are ill-formed.
1521 if (S.getLangOpts().CPlusPlus26)
1522 DiagID = diag::err_conv_mixed_enum_types_cxx26;
1523 else if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1524 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1525 // If either enumeration type is unnamed, it's less likely that the
1526 // user cares about this, but this situation is still deprecated in
1527 // C++2a. Use a different warning group.
1528 DiagID = S.getLangOpts().CPlusPlus20
1529 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1530 : diag::warn_arith_conv_mixed_anon_enum_types;
1531 } else if (ACK == Sema::ACK_Conditional) {
1532 // Conditional expressions are separated out because they have
1533 // historically had a different warning flag.
1534 DiagID = S.getLangOpts().CPlusPlus20
1535 ? diag::warn_conditional_mixed_enum_types_cxx20
1536 : diag::warn_conditional_mixed_enum_types;
1537 } else if (ACK == Sema::ACK_Comparison) {
1538 // Comparison expressions are separated out because they have
1539 // historically had a different warning flag.
1540 DiagID = S.getLangOpts().CPlusPlus20
1541 ? diag::warn_comparison_mixed_enum_types_cxx20
1542 : diag::warn_comparison_mixed_enum_types;
1543 } else {
1544 DiagID = S.getLangOpts().CPlusPlus20
1545 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1546 : diag::warn_arith_conv_mixed_enum_types;
1547 }
1548 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1549 << (int)ACK << L << R;
1550 }
1551}
1552
1553/// UsualArithmeticConversions - Performs various conversions that are common to
1554/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1555/// routine returns the first non-arithmetic type found. The client is
1556/// responsible for emitting appropriate error diagnostics.
1559 ArithConvKind ACK) {
1560 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1561
1562 if (ACK != ACK_CompAssign) {
1563 LHS = UsualUnaryConversions(LHS.get());
1564 if (LHS.isInvalid())
1565 return QualType();
1566 }
1567
1568 RHS = UsualUnaryConversions(RHS.get());
1569 if (RHS.isInvalid())
1570 return QualType();
1571
1572 // For conversion purposes, we ignore any qualifiers.
1573 // For example, "const float" and "float" are equivalent.
1574 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
1575 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
1576
1577 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1578 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1579 LHSType = AtomicLHS->getValueType();
1580
1581 // If both types are identical, no conversion is needed.
1582 if (Context.hasSameType(LHSType, RHSType))
1583 return Context.getCommonSugaredType(LHSType, RHSType);
1584
1585 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1586 // The caller can deal with this (e.g. pointer + int).
1587 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1588 return QualType();
1589
1590 // Apply unary and bitfield promotions to the LHS's type.
1591 QualType LHSUnpromotedType = LHSType;
1592 if (Context.isPromotableIntegerType(LHSType))
1593 LHSType = Context.getPromotedIntegerType(LHSType);
1594 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1595 if (!LHSBitfieldPromoteTy.isNull())
1596 LHSType = LHSBitfieldPromoteTy;
1597 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1598 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1599
1600 // If both types are identical, no conversion is needed.
1601 if (Context.hasSameType(LHSType, RHSType))
1602 return Context.getCommonSugaredType(LHSType, RHSType);
1603
1604 // At this point, we have two different arithmetic types.
1605
1606 // Diagnose attempts to convert between __ibm128, __float128 and long double
1607 // where such conversions currently can't be handled.
1608 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1609 return QualType();
1610
1611 // Handle complex types first (C99 6.3.1.8p1).
1612 if (LHSType->isComplexType() || RHSType->isComplexType())
1613 return handleComplexConversion(*this, LHS, RHS, LHSType, RHSType,
1614 ACK == ACK_CompAssign);
1615
1616 // Now handle "real" floating types (i.e. float, double, long double).
1617 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1618 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1619 ACK == ACK_CompAssign);
1620
1621 // Handle GCC complex int extension.
1622 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1623 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1624 ACK == ACK_CompAssign);
1625
1626 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1627 return handleFixedPointConversion(*this, LHSType, RHSType);
1628
1629 // Finally, we have two differing integer types.
1630 return handleIntegerConversion<doIntegralCast, doIntegralCast>
1631 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1632}
1633
1634//===----------------------------------------------------------------------===//
1635// Semantic Analysis for various Expression Types
1636//===----------------------------------------------------------------------===//
1637
1638
1640 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1641 bool PredicateIsExpr, void *ControllingExprOrType,
1642 ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs) {
1643 unsigned NumAssocs = ArgTypes.size();
1644 assert(NumAssocs == ArgExprs.size());
1645
1646 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1647 for (unsigned i = 0; i < NumAssocs; ++i) {
1648 if (ArgTypes[i])
1649 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1650 else
1651 Types[i] = nullptr;
1652 }
1653
1654 // If we have a controlling type, we need to convert it from a parsed type
1655 // into a semantic type and then pass that along.
1656 if (!PredicateIsExpr) {
1657 TypeSourceInfo *ControllingType;
1658 (void)GetTypeFromParser(ParsedType::getFromOpaquePtr(ControllingExprOrType),
1659 &ControllingType);
1660 assert(ControllingType && "couldn't get the type out of the parser");
1661 ControllingExprOrType = ControllingType;
1662 }
1663
1665 KeyLoc, DefaultLoc, RParenLoc, PredicateIsExpr, ControllingExprOrType,
1666 llvm::ArrayRef(Types, NumAssocs), ArgExprs);
1667 delete [] Types;
1668 return ER;
1669}
1670
1672 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1673 bool PredicateIsExpr, void *ControllingExprOrType,
1675 unsigned NumAssocs = Types.size();
1676 assert(NumAssocs == Exprs.size());
1677 assert(ControllingExprOrType &&
1678 "Must have either a controlling expression or a controlling type");
1679
1680 Expr *ControllingExpr = nullptr;
1681 TypeSourceInfo *ControllingType = nullptr;
1682 if (PredicateIsExpr) {
1683 // Decay and strip qualifiers for the controlling expression type, and
1684 // handle placeholder type replacement. See committee discussion from WG14
1685 // DR423.
1689 reinterpret_cast<Expr *>(ControllingExprOrType));
1690 if (R.isInvalid())
1691 return ExprError();
1692 ControllingExpr = R.get();
1693 } else {
1694 // The extension form uses the type directly rather than converting it.
1695 ControllingType = reinterpret_cast<TypeSourceInfo *>(ControllingExprOrType);
1696 if (!ControllingType)
1697 return ExprError();
1698 }
1699
1700 bool TypeErrorFound = false,
1701 IsResultDependent = ControllingExpr
1702 ? ControllingExpr->isTypeDependent()
1703 : ControllingType->getType()->isDependentType(),
1704 ContainsUnexpandedParameterPack =
1705 ControllingExpr
1706 ? ControllingExpr->containsUnexpandedParameterPack()
1707 : ControllingType->getType()->containsUnexpandedParameterPack();
1708
1709 // The controlling expression is an unevaluated operand, so side effects are
1710 // likely unintended.
1711 if (!inTemplateInstantiation() && !IsResultDependent && ControllingExpr &&
1712 ControllingExpr->HasSideEffects(Context, false))
1713 Diag(ControllingExpr->getExprLoc(),
1714 diag::warn_side_effects_unevaluated_context);
1715
1716 for (unsigned i = 0; i < NumAssocs; ++i) {
1717 if (Exprs[i]->containsUnexpandedParameterPack())
1718 ContainsUnexpandedParameterPack = true;
1719
1720 if (Types[i]) {
1721 if (Types[i]->getType()->containsUnexpandedParameterPack())
1722 ContainsUnexpandedParameterPack = true;
1723
1724 if (Types[i]->getType()->isDependentType()) {
1725 IsResultDependent = true;
1726 } else {
1727 // We relax the restriction on use of incomplete types and non-object
1728 // types with the type-based extension of _Generic. Allowing incomplete
1729 // objects means those can be used as "tags" for a type-safe way to map
1730 // to a value. Similarly, matching on function types rather than
1731 // function pointer types can be useful. However, the restriction on VM
1732 // types makes sense to retain as there are open questions about how
1733 // the selection can be made at compile time.
1734 //
1735 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1736 // complete object type other than a variably modified type."
1737 unsigned D = 0;
1738 if (ControllingExpr && Types[i]->getType()->isIncompleteType())
1739 D = diag::err_assoc_type_incomplete;
1740 else if (ControllingExpr && !Types[i]->getType()->isObjectType())
1741 D = diag::err_assoc_type_nonobject;
1742 else if (Types[i]->getType()->isVariablyModifiedType())
1743 D = diag::err_assoc_type_variably_modified;
1744 else if (ControllingExpr) {
1745 // Because the controlling expression undergoes lvalue conversion,
1746 // array conversion, and function conversion, an association which is
1747 // of array type, function type, or is qualified can never be
1748 // reached. We will warn about this so users are less surprised by
1749 // the unreachable association. However, we don't have to handle
1750 // function types; that's not an object type, so it's handled above.
1751 //
1752 // The logic is somewhat different for C++ because C++ has different
1753 // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1754 // If T is a non-class type, the type of the prvalue is the cv-
1755 // unqualified version of T. Otherwise, the type of the prvalue is T.
1756 // The result of these rules is that all qualified types in an
1757 // association in C are unreachable, and in C++, only qualified non-
1758 // class types are unreachable.
1759 //
1760 // NB: this does not apply when the first operand is a type rather
1761 // than an expression, because the type form does not undergo
1762 // conversion.
1763 unsigned Reason = 0;
1764 QualType QT = Types[i]->getType();
1765 if (QT->isArrayType())
1766 Reason = 1;
1767 else if (QT.hasQualifiers() &&
1768 (!LangOpts.CPlusPlus || !QT->isRecordType()))
1769 Reason = 2;
1770
1771 if (Reason)
1772 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1773 diag::warn_unreachable_association)
1774 << QT << (Reason - 1);
1775 }
1776
1777 if (D != 0) {
1778 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1779 << Types[i]->getTypeLoc().getSourceRange()
1780 << Types[i]->getType();
1781 TypeErrorFound = true;
1782 }
1783
1784 // C11 6.5.1.1p2 "No two generic associations in the same generic
1785 // selection shall specify compatible types."
1786 for (unsigned j = i+1; j < NumAssocs; ++j)
1787 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1788 Context.typesAreCompatible(Types[i]->getType(),
1789 Types[j]->getType())) {
1790 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1791 diag::err_assoc_compatible_types)
1792 << Types[j]->getTypeLoc().getSourceRange()
1793 << Types[j]->getType()
1794 << Types[i]->getType();
1795 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1796 diag::note_compat_assoc)
1797 << Types[i]->getTypeLoc().getSourceRange()
1798 << Types[i]->getType();
1799 TypeErrorFound = true;
1800 }
1801 }
1802 }
1803 }
1804 if (TypeErrorFound)
1805 return ExprError();
1806
1807 // If we determined that the generic selection is result-dependent, don't
1808 // try to compute the result expression.
1809 if (IsResultDependent) {
1810 if (ControllingExpr)
1811 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr,
1812 Types, Exprs, DefaultLoc, RParenLoc,
1813 ContainsUnexpandedParameterPack);
1814 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingType, Types,
1815 Exprs, DefaultLoc, RParenLoc,
1816 ContainsUnexpandedParameterPack);
1817 }
1818
1819 SmallVector<unsigned, 1> CompatIndices;
1820 unsigned DefaultIndex = -1U;
1821 // Look at the canonical type of the controlling expression in case it was a
1822 // deduced type like __auto_type. However, when issuing diagnostics, use the
1823 // type the user wrote in source rather than the canonical one.
1824 for (unsigned i = 0; i < NumAssocs; ++i) {
1825 if (!Types[i])
1826 DefaultIndex = i;
1827 else if (ControllingExpr &&
1829 ControllingExpr->getType().getCanonicalType(),
1830 Types[i]->getType()))
1831 CompatIndices.push_back(i);
1832 else if (ControllingType &&
1834 ControllingType->getType().getCanonicalType(),
1835 Types[i]->getType()))
1836 CompatIndices.push_back(i);
1837 }
1838
1839 auto GetControllingRangeAndType = [](Expr *ControllingExpr,
1840 TypeSourceInfo *ControllingType) {
1841 // We strip parens here because the controlling expression is typically
1842 // parenthesized in macro definitions.
1843 if (ControllingExpr)
1844 ControllingExpr = ControllingExpr->IgnoreParens();
1845
1846 SourceRange SR = ControllingExpr
1847 ? ControllingExpr->getSourceRange()
1848 : ControllingType->getTypeLoc().getSourceRange();
1849 QualType QT = ControllingExpr ? ControllingExpr->getType()
1850 : ControllingType->getType();
1851
1852 return std::make_pair(SR, QT);
1853 };
1854
1855 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1856 // type compatible with at most one of the types named in its generic
1857 // association list."
1858 if (CompatIndices.size() > 1) {
1859 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
1860 SourceRange SR = P.first;
1861 Diag(SR.getBegin(), diag::err_generic_sel_multi_match)
1862 << SR << P.second << (unsigned)CompatIndices.size();
1863 for (unsigned I : CompatIndices) {
1864 Diag(Types[I]->getTypeLoc().getBeginLoc(),
1865 diag::note_compat_assoc)
1866 << Types[I]->getTypeLoc().getSourceRange()
1867 << Types[I]->getType();
1868 }
1869 return ExprError();
1870 }
1871
1872 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1873 // its controlling expression shall have type compatible with exactly one of
1874 // the types named in its generic association list."
1875 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1876 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
1877 SourceRange SR = P.first;
1878 Diag(SR.getBegin(), diag::err_generic_sel_no_match) << SR << P.second;
1879 return ExprError();
1880 }
1881
1882 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1883 // type name that is compatible with the type of the controlling expression,
1884 // then the result expression of the generic selection is the expression
1885 // in that generic association. Otherwise, the result expression of the
1886 // generic selection is the expression in the default generic association."
1887 unsigned ResultIndex =
1888 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1889
1890 if (ControllingExpr) {
1892 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1893 ContainsUnexpandedParameterPack, ResultIndex);
1894 }
1896 Context, KeyLoc, ControllingType, Types, Exprs, DefaultLoc, RParenLoc,
1897 ContainsUnexpandedParameterPack, ResultIndex);
1898}
1899
1901 switch (Kind) {
1902 default:
1903 llvm_unreachable("unexpected TokenKind");
1904 case tok::kw___func__:
1905 return PredefinedIdentKind::Func; // [C99 6.4.2.2]
1906 case tok::kw___FUNCTION__:
1908 case tok::kw___FUNCDNAME__:
1909 return PredefinedIdentKind::FuncDName; // [MS]
1910 case tok::kw___FUNCSIG__:
1911 return PredefinedIdentKind::FuncSig; // [MS]
1912 case tok::kw_L__FUNCTION__:
1913 return PredefinedIdentKind::LFunction; // [MS]
1914 case tok::kw_L__FUNCSIG__:
1915 return PredefinedIdentKind::LFuncSig; // [MS]
1916 case tok::kw___PRETTY_FUNCTION__:
1918 }
1919}
1920
1921/// getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used
1922/// to determine the value of a PredefinedExpr. This can be either a
1923/// block, lambda, captured statement, function, otherwise a nullptr.
1925 while (DC && !isa<BlockDecl, CapturedDecl, FunctionDecl, ObjCMethodDecl>(DC))
1926 DC = DC->getParent();
1927 return cast_or_null<Decl>(DC);
1928}
1929
1930/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1931/// location of the token and the offset of the ud-suffix within it.
1933 unsigned Offset) {
1934 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1935 S.getLangOpts());
1936}
1937
1938/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1939/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1941 IdentifierInfo *UDSuffix,
1942 SourceLocation UDSuffixLoc,
1943 ArrayRef<Expr*> Args,
1944 SourceLocation LitEndLoc) {
1945 assert(Args.size() <= 2 && "too many arguments for literal operator");
1946
1947 QualType ArgTy[2];
1948 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1949 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1950 if (ArgTy[ArgIdx]->isArrayType())
1951 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1952 }
1953
1954 DeclarationName OpName =
1956 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1957 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1958
1959 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1960 if (S.LookupLiteralOperator(Scope, R, llvm::ArrayRef(ArgTy, Args.size()),
1961 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1962 /*AllowStringTemplatePack*/ false,
1963 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1964 return ExprError();
1965
1966 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1967}
1968
1970 // StringToks needs backing storage as it doesn't hold array elements itself
1971 std::vector<Token> ExpandedToks;
1972 if (getLangOpts().MicrosoftExt)
1973 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
1974
1975 StringLiteralParser Literal(StringToks, PP,
1977 if (Literal.hadError)
1978 return ExprError();
1979
1980 SmallVector<SourceLocation, 4> StringTokLocs;
1981 for (const Token &Tok : StringToks)
1982 StringTokLocs.push_back(Tok.getLocation());
1983
1985 Context, Literal.GetString(), StringLiteralKind::Unevaluated, false, {},
1986 &StringTokLocs[0], StringTokLocs.size());
1987
1988 if (!Literal.getUDSuffix().empty()) {
1989 SourceLocation UDSuffixLoc =
1990 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1991 Literal.getUDSuffixOffset());
1992 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1993 }
1994
1995 return Lit;
1996}
1997
1998std::vector<Token>
2000 // MSVC treats some predefined identifiers (e.g. __FUNCTION__) as function
2001 // local macros that expand to string literals that may be concatenated.
2002 // These macros are expanded here (in Sema), because StringLiteralParser
2003 // (in Lex) doesn't know the enclosing function (because it hasn't been
2004 // parsed yet).
2005 assert(getLangOpts().MicrosoftExt);
2006
2007 // Note: Although function local macros are defined only inside functions,
2008 // we ensure a valid `CurrentDecl` even outside of a function. This allows
2009 // expansion of macros into empty string literals without additional checks.
2010 Decl *CurrentDecl = getPredefinedExprDecl(CurContext);
2011 if (!CurrentDecl)
2012 CurrentDecl = Context.getTranslationUnitDecl();
2013
2014 std::vector<Token> ExpandedToks;
2015 ExpandedToks.reserve(Toks.size());
2016 for (const Token &Tok : Toks) {
2017 if (!isFunctionLocalStringLiteralMacro(Tok.getKind(), getLangOpts())) {
2018 assert(tok::isStringLiteral(Tok.getKind()));
2019 ExpandedToks.emplace_back(Tok);
2020 continue;
2021 }
2022 if (isa<TranslationUnitDecl>(CurrentDecl))
2023 Diag(Tok.getLocation(), diag::ext_predef_outside_function);
2024 // Stringify predefined expression
2025 Diag(Tok.getLocation(), diag::ext_string_literal_from_predefined)
2026 << Tok.getKind();
2027 SmallString<64> Str;
2028 llvm::raw_svector_ostream OS(Str);
2029 Token &Exp = ExpandedToks.emplace_back();
2030 Exp.startToken();
2031 if (Tok.getKind() == tok::kw_L__FUNCTION__ ||
2032 Tok.getKind() == tok::kw_L__FUNCSIG__) {
2033 OS << 'L';
2034 Exp.setKind(tok::wide_string_literal);
2035 } else {
2036 Exp.setKind(tok::string_literal);
2037 }
2038 OS << '"'
2040 getPredefinedExprKind(Tok.getKind()), CurrentDecl))
2041 << '"';
2042 PP.CreateString(OS.str(), Exp, Tok.getLocation(), Tok.getEndLoc());
2043 }
2044 return ExpandedToks;
2045}
2046
2049 assert(!StringToks.empty() && "Must have at least one string!");
2050
2051 // StringToks needs backing storage as it doesn't hold array elements itself
2052 std::vector<Token> ExpandedToks;
2053 if (getLangOpts().MicrosoftExt)
2054 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
2055
2056 StringLiteralParser Literal(StringToks, PP);
2057 if (Literal.hadError)
2058 return ExprError();
2059
2060 SmallVector<SourceLocation, 4> StringTokLocs;
2061 for (const Token &Tok : StringToks)
2062 StringTokLocs.push_back(Tok.getLocation());
2063
2064 QualType CharTy = Context.CharTy;
2066 if (Literal.isWide()) {
2067 CharTy = Context.getWideCharType();
2069 } else if (Literal.isUTF8()) {
2070 if (getLangOpts().Char8)
2071 CharTy = Context.Char8Ty;
2072 else if (getLangOpts().C23)
2073 CharTy = Context.UnsignedCharTy;
2075 } else if (Literal.isUTF16()) {
2076 CharTy = Context.Char16Ty;
2078 } else if (Literal.isUTF32()) {
2079 CharTy = Context.Char32Ty;
2081 } else if (Literal.isPascal()) {
2082 CharTy = Context.UnsignedCharTy;
2083 }
2084
2085 // Warn on u8 string literals before C++20 and C23, whose type
2086 // was an array of char before but becomes an array of char8_t.
2087 // In C++20, it cannot be used where a pointer to char is expected.
2088 // In C23, it might have an unexpected value if char was signed.
2089 if (Kind == StringLiteralKind::UTF8 &&
2091 ? !getLangOpts().CPlusPlus20 && !getLangOpts().Char8
2092 : !getLangOpts().C23)) {
2093 Diag(StringTokLocs.front(), getLangOpts().CPlusPlus
2094 ? diag::warn_cxx20_compat_utf8_string
2095 : diag::warn_c23_compat_utf8_string);
2096
2097 // Create removals for all 'u8' prefixes in the string literal(s). This
2098 // ensures C++20/C23 compatibility (but may change the program behavior when
2099 // built by non-Clang compilers for which the execution character set is
2100 // not always UTF-8).
2101 auto RemovalDiag = PDiag(diag::note_cxx20_c23_compat_utf8_string_remove_u8);
2102 SourceLocation RemovalDiagLoc;
2103 for (const Token &Tok : StringToks) {
2104 if (Tok.getKind() == tok::utf8_string_literal) {
2105 if (RemovalDiagLoc.isInvalid())
2106 RemovalDiagLoc = Tok.getLocation();
2108 Tok.getLocation(),
2109 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
2111 }
2112 }
2113 Diag(RemovalDiagLoc, RemovalDiag);
2114 }
2115
2116 QualType StrTy =
2117 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
2118
2119 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
2120 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
2121 Kind, Literal.Pascal, StrTy,
2122 &StringTokLocs[0],
2123 StringTokLocs.size());
2124 if (Literal.getUDSuffix().empty())
2125 return Lit;
2126
2127 // We're building a user-defined literal.
2128 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2129 SourceLocation UDSuffixLoc =
2130 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
2131 Literal.getUDSuffixOffset());
2132
2133 // Make sure we're allowed user-defined literals here.
2134 if (!UDLScope)
2135 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
2136
2137 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
2138 // operator "" X (str, len)
2139 QualType SizeType = Context.getSizeType();
2140
2141 DeclarationName OpName =
2143 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2144 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2145
2146 QualType ArgTy[] = {
2147 Context.getArrayDecayedType(StrTy), SizeType
2148 };
2149
2150 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2151 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
2152 /*AllowRaw*/ false, /*AllowTemplate*/ true,
2153 /*AllowStringTemplatePack*/ true,
2154 /*DiagnoseMissing*/ true, Lit)) {
2155
2156 case LOLR_Cooked: {
2157 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
2158 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
2159 StringTokLocs[0]);
2160 Expr *Args[] = { Lit, LenArg };
2161
2162 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
2163 }
2164
2165 case LOLR_Template: {
2166 TemplateArgumentListInfo ExplicitArgs;
2167 TemplateArgument Arg(Lit);
2168 TemplateArgumentLocInfo ArgInfo(Lit);
2169 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2170 return BuildLiteralOperatorCall(R, OpNameInfo, {}, StringTokLocs.back(),
2171 &ExplicitArgs);
2172 }
2173
2175 TemplateArgumentListInfo ExplicitArgs;
2176
2177 unsigned CharBits = Context.getIntWidth(CharTy);
2178 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
2179 llvm::APSInt Value(CharBits, CharIsUnsigned);
2180
2181 TemplateArgument TypeArg(CharTy);
2183 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
2184
2185 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
2186 Value = Lit->getCodeUnit(I);
2187 TemplateArgument Arg(Context, Value, CharTy);
2189 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2190 }
2191 return BuildLiteralOperatorCall(R, OpNameInfo, {}, StringTokLocs.back(),
2192 &ExplicitArgs);
2193 }
2194 case LOLR_Raw:
2196 llvm_unreachable("unexpected literal operator lookup result");
2197 case LOLR_Error:
2198 return ExprError();
2199 }
2200 llvm_unreachable("unexpected literal operator lookup result");
2201}
2202
2206 const CXXScopeSpec *SS) {
2207 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2208 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2209}
2210
2213 const DeclarationNameInfo &NameInfo,
2214 const CXXScopeSpec *SS, NamedDecl *FoundD,
2215 SourceLocation TemplateKWLoc,
2216 const TemplateArgumentListInfo *TemplateArgs) {
2219 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2220 TemplateArgs);
2221}
2222
2223// CUDA/HIP: Check whether a captured reference variable is referencing a
2224// host variable in a device or host device lambda.
2226 VarDecl *VD) {
2227 if (!S.getLangOpts().CUDA || !VD->hasInit())
2228 return false;
2229 assert(VD->getType()->isReferenceType());
2230
2231 // Check whether the reference variable is referencing a host variable.
2232 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
2233 if (!DRE)
2234 return false;
2235 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
2236 if (!Referee || !Referee->hasGlobalStorage() ||
2237 Referee->hasAttr<CUDADeviceAttr>())
2238 return false;
2239
2240 // Check whether the current function is a device or host device lambda.
2241 // Check whether the reference variable is a capture by getDeclContext()
2242 // since refersToEnclosingVariableOrCapture() is not ready at this point.
2243 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
2244 if (MD && MD->getParent()->isLambda() &&
2245 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2246 VD->getDeclContext() != MD)
2247 return true;
2248
2249 return false;
2250}
2251
2253 // A declaration named in an unevaluated operand never constitutes an odr-use.
2255 return NOUR_Unevaluated;
2256
2257 // C++2a [basic.def.odr]p4:
2258 // A variable x whose name appears as a potentially-evaluated expression e
2259 // is odr-used by e unless [...] x is a reference that is usable in
2260 // constant expressions.
2261 // CUDA/HIP:
2262 // If a reference variable referencing a host variable is captured in a
2263 // device or host device lambda, the value of the referee must be copied
2264 // to the capture and the reference variable must be treated as odr-use
2265 // since the value of the referee is not known at compile time and must
2266 // be loaded from the captured.
2267 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2268 if (VD->getType()->isReferenceType() &&
2269 !(getLangOpts().OpenMP && OpenMP().isOpenMPCapturedDecl(D)) &&
2271 VD->isUsableInConstantExpressions(Context))
2272 return NOUR_Constant;
2273 }
2274
2275 // All remaining non-variable cases constitute an odr-use. For variables, we
2276 // need to wait and see how the expression is used.
2277 return NOUR_None;
2278}
2279
2282 const DeclarationNameInfo &NameInfo,
2283 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2284 SourceLocation TemplateKWLoc,
2285 const TemplateArgumentListInfo *TemplateArgs) {
2286 bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(D) &&
2287 NeedToCaptureVariable(D, NameInfo.getLoc());
2288
2290 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2291 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2293
2294 // C++ [except.spec]p17:
2295 // An exception-specification is considered to be needed when:
2296 // - in an expression, the function is the unique lookup result or
2297 // the selected member of a set of overloaded functions.
2298 //
2299 // We delay doing this until after we've built the function reference and
2300 // marked it as used so that:
2301 // a) if the function is defaulted, we get errors from defining it before /
2302 // instead of errors from computing its exception specification, and
2303 // b) if the function is a defaulted comparison, we can use the body we
2304 // build when defining it as input to the exception specification
2305 // computation rather than computing a new body.
2306 if (const auto *FPT = Ty->getAs<FunctionProtoType>()) {
2307 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2308 if (const auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2310 }
2311 }
2312
2313 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2315 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2317
2318 const auto *FD = dyn_cast<FieldDecl>(D);
2319 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D))
2320 FD = IFD->getAnonField();
2321 if (FD) {
2322 UnusedPrivateFields.remove(FD);
2323 // Just in case we're building an illegal pointer-to-member.
2324 if (FD->isBitField())
2326 }
2327
2328 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2329 // designates a bit-field.
2330 if (const auto *BD = dyn_cast<BindingDecl>(D))
2331 if (const auto *BE = BD->getBinding())
2332 E->setObjectKind(BE->getObjectKind());
2333
2334 return E;
2335}
2336
2337void
2340 DeclarationNameInfo &NameInfo,
2341 const TemplateArgumentListInfo *&TemplateArgs) {
2342 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2343 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2344 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2345
2346 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2347 Id.TemplateId->NumArgs);
2348 translateTemplateArguments(TemplateArgsPtr, Buffer);
2349
2350 TemplateName TName = Id.TemplateId->Template.get();
2351 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2352 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2353 TemplateArgs = &Buffer;
2354 } else {
2355 NameInfo = GetNameFromUnqualifiedId(Id);
2356 TemplateArgs = nullptr;
2357 }
2358}
2359
2361 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2363 unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2364 DeclContext *Ctx =
2365 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2366 if (!TC) {
2367 // Emit a special diagnostic for failed member lookups.
2368 // FIXME: computing the declaration context might fail here (?)
2369 if (Ctx)
2370 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2371 << SS.getRange();
2372 else
2373 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2374 return;
2375 }
2376
2377 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2378 bool DroppedSpecifier =
2379 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2380 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2381 ? diag::note_implicit_param_decl
2382 : diag::note_previous_decl;
2383 if (!Ctx)
2384 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2385 SemaRef.PDiag(NoteID));
2386 else
2387 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2388 << Typo << Ctx << DroppedSpecifier
2389 << SS.getRange(),
2390 SemaRef.PDiag(NoteID));
2391}
2392
2394 // During a default argument instantiation the CurContext points
2395 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2396 // function parameter list, hence add an explicit check.
2397 bool isDefaultArgument =
2398 !CodeSynthesisContexts.empty() &&
2399 CodeSynthesisContexts.back().Kind ==
2401 const auto *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2402 bool isInstance = CurMethod && CurMethod->isInstance() &&
2403 R.getNamingClass() == CurMethod->getParent() &&
2404 !isDefaultArgument;
2405
2406 // There are two ways we can find a class-scope declaration during template
2407 // instantiation that we did not find in the template definition: if it is a
2408 // member of a dependent base class, or if it is declared after the point of
2409 // use in the same class. Distinguish these by comparing the class in which
2410 // the member was found to the naming class of the lookup.
2411 unsigned DiagID = diag::err_found_in_dependent_base;
2412 unsigned NoteID = diag::note_member_declared_at;
2414 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2415 : diag::err_found_later_in_class;
2416 } else if (getLangOpts().MSVCCompat) {
2417 DiagID = diag::ext_found_in_dependent_base;
2418 NoteID = diag::note_dependent_member_use;
2419 }
2420
2421 if (isInstance) {
2422 // Give a code modification hint to insert 'this->'.
2423 Diag(R.getNameLoc(), DiagID)
2424 << R.getLookupName()
2425 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2427 } else {
2428 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2429 // they're not shadowed).
2430 Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2431 }
2432
2433 for (const NamedDecl *D : R)
2434 Diag(D->getLocation(), NoteID);
2435
2436 // Return true if we are inside a default argument instantiation
2437 // and the found name refers to an instance member function, otherwise
2438 // the caller will try to create an implicit member call and this is wrong
2439 // for default arguments.
2440 //
2441 // FIXME: Is this special case necessary? We could allow the caller to
2442 // diagnose this.
2443 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2444 Diag(R.getNameLoc(), diag::err_member_call_without_object) << 0;
2445 return true;
2446 }
2447
2448 // Tell the callee to try to recover.
2449 return false;
2450}
2451
2454 TemplateArgumentListInfo *ExplicitTemplateArgs,
2455 ArrayRef<Expr *> Args, DeclContext *LookupCtx,
2456 TypoExpr **Out) {
2457 DeclarationName Name = R.getLookupName();
2458
2459 unsigned diagnostic = diag::err_undeclared_var_use;
2460 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2461 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2462 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2463 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2464 diagnostic = diag::err_undeclared_use;
2465 diagnostic_suggest = diag::err_undeclared_use_suggest;
2466 }
2467
2468 // If the original lookup was an unqualified lookup, fake an
2469 // unqualified lookup. This is useful when (for example) the
2470 // original lookup would not have found something because it was a
2471 // dependent name.
2472 DeclContext *DC =
2473 LookupCtx ? LookupCtx : (SS.isEmpty() ? CurContext : nullptr);
2474 while (DC) {
2475 if (isa<CXXRecordDecl>(DC)) {
2476 if (ExplicitTemplateArgs) {
2478 R, S, SS, Context.getRecordType(cast<CXXRecordDecl>(DC)),
2479 /*EnteringContext*/ false, TemplateNameIsRequired,
2480 /*RequiredTemplateKind*/ nullptr, /*AllowTypoCorrection*/ true))
2481 return true;
2482 } else {
2483 LookupQualifiedName(R, DC);
2484 }
2485
2486 if (!R.empty()) {
2487 // Don't give errors about ambiguities in this lookup.
2489
2490 // If there's a best viable function among the results, only mention
2491 // that one in the notes.
2492 OverloadCandidateSet Candidates(R.getNameLoc(),
2494 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2496 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2497 OR_Success) {
2498 R.clear();
2499 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2500 R.resolveKind();
2501 }
2502
2504 }
2505
2506 R.clear();
2507 }
2508
2509 DC = DC->getLookupParent();
2510 }
2511
2512 // We didn't find anything, so try to correct for a typo.
2513 TypoCorrection Corrected;
2514 if (S && Out) {
2515 SourceLocation TypoLoc = R.getNameLoc();
2516 assert(!ExplicitTemplateArgs &&
2517 "Diagnosing an empty lookup with explicit template args!");
2518 *Out = CorrectTypoDelayed(
2519 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2520 [=](const TypoCorrection &TC) {
2521 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2522 diagnostic, diagnostic_suggest);
2523 },
2524 nullptr, CTK_ErrorRecovery, LookupCtx);
2525 if (*Out)
2526 return true;
2527 } else if (S && (Corrected =
2529 &SS, CCC, CTK_ErrorRecovery, LookupCtx))) {
2530 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2531 bool DroppedSpecifier =
2532 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2533 R.setLookupName(Corrected.getCorrection());
2534
2535 bool AcceptableWithRecovery = false;
2536 bool AcceptableWithoutRecovery = false;
2537 NamedDecl *ND = Corrected.getFoundDecl();
2538 if (ND) {
2539 if (Corrected.isOverloaded()) {
2543 for (NamedDecl *CD : Corrected) {
2544 if (FunctionTemplateDecl *FTD =
2545 dyn_cast<FunctionTemplateDecl>(CD))
2547 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2548 Args, OCS);
2549 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2550 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2552 Args, OCS);
2553 }
2554 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2555 case OR_Success:
2556 ND = Best->FoundDecl;
2557 Corrected.setCorrectionDecl(ND);
2558 break;
2559 default:
2560 // FIXME: Arbitrarily pick the first declaration for the note.
2561 Corrected.setCorrectionDecl(ND);
2562 break;
2563 }
2564 }
2565 R.addDecl(ND);
2566 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2567 CXXRecordDecl *Record = nullptr;
2568 if (Corrected.getCorrectionSpecifier()) {
2569 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2570 Record = Ty->getAsCXXRecordDecl();
2571 }
2572 if (!Record)
2573 Record = cast<CXXRecordDecl>(
2576 }
2577
2578 auto *UnderlyingND = ND->getUnderlyingDecl();
2579 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2580 isa<FunctionTemplateDecl>(UnderlyingND);
2581 // FIXME: If we ended up with a typo for a type name or
2582 // Objective-C class name, we're in trouble because the parser
2583 // is in the wrong place to recover. Suggest the typo
2584 // correction, but don't make it a fix-it since we're not going
2585 // to recover well anyway.
2586 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2587 getAsTypeTemplateDecl(UnderlyingND) ||
2588 isa<ObjCInterfaceDecl>(UnderlyingND);
2589 } else {
2590 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2591 // because we aren't able to recover.
2592 AcceptableWithoutRecovery = true;
2593 }
2594
2595 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2596 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2597 ? diag::note_implicit_param_decl
2598 : diag::note_previous_decl;
2599 if (SS.isEmpty())
2600 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2601 PDiag(NoteID), AcceptableWithRecovery);
2602 else
2603 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2604 << Name << computeDeclContext(SS, false)
2605 << DroppedSpecifier << SS.getRange(),
2606 PDiag(NoteID), AcceptableWithRecovery);
2607
2608 // Tell the callee whether to try to recover.
2609 return !AcceptableWithRecovery;
2610 }
2611 }
2612 R.clear();
2613
2614 // Emit a special diagnostic for failed member lookups.
2615 // FIXME: computing the declaration context might fail here (?)
2616 if (!SS.isEmpty()) {
2617 Diag(R.getNameLoc(), diag::err_no_member)
2618 << Name << computeDeclContext(SS, false)
2619 << SS.getRange();
2620 return true;
2621 }
2622
2623 // Give up, we can't recover.
2624 Diag(R.getNameLoc(), diagnostic) << Name;
2625 return true;
2626}
2627
2628/// In Microsoft mode, if we are inside a template class whose parent class has
2629/// dependent base classes, and we can't resolve an unqualified identifier, then
2630/// assume the identifier is a member of a dependent base class. We can only
2631/// recover successfully in static methods, instance methods, and other contexts
2632/// where 'this' is available. This doesn't precisely match MSVC's
2633/// instantiation model, but it's close enough.
2634static Expr *
2636 DeclarationNameInfo &NameInfo,
2637 SourceLocation TemplateKWLoc,
2638 const TemplateArgumentListInfo *TemplateArgs) {
2639 // Only try to recover from lookup into dependent bases in static methods or
2640 // contexts where 'this' is available.
2641 QualType ThisType = S.getCurrentThisType();
2642 const CXXRecordDecl *RD = nullptr;
2643 if (!ThisType.isNull())
2644 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2645 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2646 RD = MD->getParent();
2647 if (!RD || !RD->hasDefinition() || !RD->hasAnyDependentBases())
2648 return nullptr;
2649
2650 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2651 // is available, suggest inserting 'this->' as a fixit.
2652 SourceLocation Loc = NameInfo.getLoc();
2653 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2654 DB << NameInfo.getName() << RD;
2655
2656 if (!ThisType.isNull()) {
2657 DB << FixItHint::CreateInsertion(Loc, "this->");
2659 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2660 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2661 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2662 }
2663
2664 // Synthesize a fake NNS that points to the derived class. This will
2665 // perform name lookup during template instantiation.
2666 CXXScopeSpec SS;
2667 auto *NNS =
2668 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2669 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2671 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2672 TemplateArgs);
2673}
2674
2677 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2678 bool HasTrailingLParen, bool IsAddressOfOperand,
2680 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2681 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2682 "cannot be direct & operand and have a trailing lparen");
2683 if (SS.isInvalid())
2684 return ExprError();
2685
2686 TemplateArgumentListInfo TemplateArgsBuffer;
2687
2688 // Decompose the UnqualifiedId into the following data.
2689 DeclarationNameInfo NameInfo;
2690 const TemplateArgumentListInfo *TemplateArgs;
2691 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2692
2693 DeclarationName Name = NameInfo.getName();
2694 IdentifierInfo *II = Name.getAsIdentifierInfo();
2695 SourceLocation NameLoc = NameInfo.getLoc();
2696
2697 if (II && II->isEditorPlaceholder()) {
2698 // FIXME: When typed placeholders are supported we can create a typed
2699 // placeholder expression node.
2700 return ExprError();
2701 }
2702
2703 // This specially handles arguments of attributes appertains to a type of C
2704 // struct field such that the name lookup within a struct finds the member
2705 // name, which is not the case for other contexts in C.
2706 if (isAttrContext() && !getLangOpts().CPlusPlus && S->isClassScope()) {
2707 // See if this is reference to a field of struct.
2708 LookupResult R(*this, NameInfo, LookupMemberName);
2709 // LookupName handles a name lookup from within anonymous struct.
2710 if (LookupName(R, S)) {
2711 if (auto *VD = dyn_cast<ValueDecl>(R.getFoundDecl())) {
2712 QualType type = VD->getType().getNonReferenceType();
2713 // This will eventually be translated into MemberExpr upon
2714 // the use of instantiated struct fields.
2715 return BuildDeclRefExpr(VD, type, VK_LValue, NameLoc);
2716 }
2717 }
2718 }
2719
2720 // Perform the required lookup.
2721 LookupResult R(*this, NameInfo,
2725 if (TemplateKWLoc.isValid() || TemplateArgs) {
2726 // Lookup the template name again to correctly establish the context in
2727 // which it was found. This is really unfortunate as we already did the
2728 // lookup to determine that it was a template name in the first place. If
2729 // this becomes a performance hit, we can work harder to preserve those
2730 // results until we get here but it's likely not worth it.
2731 AssumedTemplateKind AssumedTemplate;
2732 if (LookupTemplateName(R, S, SS, /*ObjectType=*/QualType(),
2733 /*EnteringContext=*/false, TemplateKWLoc,
2734 &AssumedTemplate))
2735 return ExprError();
2736
2738 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2739 IsAddressOfOperand, TemplateArgs);
2740 } else {
2741 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2742 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType(),
2743 /*AllowBuiltinCreation=*/!IvarLookupFollowUp);
2744
2745 // If the result might be in a dependent base class, this is a dependent
2746 // id-expression.
2748 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2749 IsAddressOfOperand, TemplateArgs);
2750
2751 // If this reference is in an Objective-C method, then we need to do
2752 // some special Objective-C lookup, too.
2753 if (IvarLookupFollowUp) {
2754 ExprResult E(ObjC().LookupInObjCMethod(R, S, II, true));
2755 if (E.isInvalid())
2756 return ExprError();
2757
2758 if (Expr *Ex = E.getAs<Expr>())
2759 return Ex;
2760 }
2761 }
2762
2763 if (R.isAmbiguous())
2764 return ExprError();
2765
2766 // This could be an implicitly declared function reference if the language
2767 // mode allows it as a feature.
2768 if (R.empty() && HasTrailingLParen && II &&
2769 getLangOpts().implicitFunctionsAllowed()) {
2770 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2771 if (D) R.addDecl(D);
2772 }
2773
2774 // Determine whether this name might be a candidate for
2775 // argument-dependent lookup.
2776 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2777
2778 if (R.empty() && !ADL) {
2779 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2780 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2781 TemplateKWLoc, TemplateArgs))
2782 return E;
2783 }
2784
2785 // Don't diagnose an empty lookup for inline assembly.
2786 if (IsInlineAsmIdentifier)
2787 return ExprError();
2788
2789 // If this name wasn't predeclared and if this is not a function
2790 // call, diagnose the problem.
2791 TypoExpr *TE = nullptr;
2792 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2793 : nullptr);
2794 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2795 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2796 "Typo correction callback misconfigured");
2797 if (CCC) {
2798 // Make sure the callback knows what the typo being diagnosed is.
2799 CCC->setTypoName(II);
2800 if (SS.isValid())
2801 CCC->setTypoNNS(SS.getScopeRep());
2802 }
2803 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2804 // a template name, but we happen to have always already looked up the name
2805 // before we get here if it must be a template name.
2806 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2807 {}, nullptr, &TE)) {
2808 if (TE && KeywordReplacement) {
2809 auto &State = getTypoExprState(TE);
2810 auto BestTC = State.Consumer->getNextCorrection();
2811 if (BestTC.isKeyword()) {
2812 auto *II = BestTC.getCorrectionAsIdentifierInfo();
2813 if (State.DiagHandler)
2814 State.DiagHandler(BestTC);
2815 KeywordReplacement->startToken();
2816 KeywordReplacement->setKind(II->getTokenID());
2817 KeywordReplacement->setIdentifierInfo(II);
2818 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2819 // Clean up the state associated with the TypoExpr, since it has
2820 // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2821 clearDelayedTypo(TE);
2822 // Signal that a correction to a keyword was performed by returning a
2823 // valid-but-null ExprResult.
2824 return (Expr*)nullptr;
2825 }
2826 State.Consumer->resetCorrectionStream();
2827 }
2828 return TE ? TE : ExprError();
2829 }
2830
2831 assert(!R.empty() &&
2832 "DiagnoseEmptyLookup returned false but added no results");
2833
2834 // If we found an Objective-C instance variable, let
2835 // LookupInObjCMethod build the appropriate expression to
2836 // reference the ivar.
2837 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2838 R.clear();
2839 ExprResult E(ObjC().LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2840 // In a hopelessly buggy code, Objective-C instance variable
2841 // lookup fails and no expression will be built to reference it.
2842 if (!E.isInvalid() && !E.get())
2843 return ExprError();
2844 return E;
2845 }
2846 }
2847
2848 // This is guaranteed from this point on.
2849 assert(!R.empty() || ADL);
2850
2851 // Check whether this might be a C++ implicit instance member access.
2852 // C++ [class.mfct.non-static]p3:
2853 // When an id-expression that is not part of a class member access
2854 // syntax and not used to form a pointer to member is used in the
2855 // body of a non-static member function of class X, if name lookup
2856 // resolves the name in the id-expression to a non-static non-type
2857 // member of some class C, the id-expression is transformed into a
2858 // class member access expression using (*this) as the
2859 // postfix-expression to the left of the . operator.
2860 //
2861 // But we don't actually need to do this for '&' operands if R
2862 // resolved to a function or overloaded function set, because the
2863 // expression is ill-formed if it actually works out to be a
2864 // non-static member function:
2865 //
2866 // C++ [expr.ref]p4:
2867 // Otherwise, if E1.E2 refers to a non-static member function. . .
2868 // [t]he expression can be used only as the left-hand operand of a
2869 // member function call.
2870 //
2871 // There are other safeguards against such uses, but it's important
2872 // to get this right here so that we don't end up making a
2873 // spuriously dependent expression if we're inside a dependent
2874 // instance method.
2875 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
2876 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
2877 S);
2878
2879 if (TemplateArgs || TemplateKWLoc.isValid()) {
2880
2881 // In C++1y, if this is a variable template id, then check it
2882 // in BuildTemplateIdExpr().
2883 // The single lookup result must be a variable template declaration.
2884 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2885 Id.TemplateId->Kind == TNK_Var_template) {
2886 assert(R.getAsSingle<VarTemplateDecl>() &&
2887 "There should only be one declaration found.");
2888 }
2889
2890 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2891 }
2892
2893 return BuildDeclarationNameExpr(SS, R, ADL);
2894}
2895
2897 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2898 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI) {
2899 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2900 LookupParsedName(R, /*S=*/nullptr, &SS, /*ObjectType=*/QualType());
2901
2902 if (R.isAmbiguous())
2903 return ExprError();
2904
2906 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2907 NameInfo, /*TemplateArgs=*/nullptr);
2908
2909 if (R.empty()) {
2910 // Don't diagnose problems with invalid record decl, the secondary no_member
2911 // diagnostic during template instantiation is likely bogus, e.g. if a class
2912 // is invalid because it's derived from an invalid base class, then missing
2913 // members were likely supposed to be inherited.
2915 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2916 if (CD->isInvalidDecl())
2917 return ExprError();
2918 Diag(NameInfo.getLoc(), diag::err_no_member)
2919 << NameInfo.getName() << DC << SS.getRange();
2920 return ExprError();
2921 }
2922
2923 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2924 // Diagnose a missing typename if this resolved unambiguously to a type in
2925 // a dependent context. If we can recover with a type, downgrade this to
2926 // a warning in Microsoft compatibility mode.
2927 unsigned DiagID = diag::err_typename_missing;
2928 if (RecoveryTSI && getLangOpts().MSVCCompat)
2929 DiagID = diag::ext_typename_missing;
2931 auto D = Diag(Loc, DiagID);
2932 D << SS.getScopeRep() << NameInfo.getName().getAsString()
2933 << SourceRange(Loc, NameInfo.getEndLoc());
2934
2935 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2936 // context.
2937 if (!RecoveryTSI)
2938 return ExprError();
2939
2940 // Only issue the fixit if we're prepared to recover.
2941 D << FixItHint::CreateInsertion(Loc, "typename ");
2942
2943 // Recover by pretending this was an elaborated type.
2945 TypeLocBuilder TLB;
2946 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2947
2952
2953 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2954
2955 return ExprEmpty();
2956 }
2957
2958 // If necessary, build an implicit class member access.
2959 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
2961 /*TemplateKWLoc=*/SourceLocation(),
2962 R, /*TemplateArgs=*/nullptr,
2963 /*S=*/nullptr);
2964
2965 return BuildDeclarationNameExpr(SS, R, /*ADL=*/false);
2966}
2967
2970 NestedNameSpecifier *Qualifier,
2971 NamedDecl *FoundDecl,
2972 NamedDecl *Member) {
2973 const auto *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2974 if (!RD)
2975 return From;
2976
2977 QualType DestRecordType;
2978 QualType DestType;
2979 QualType FromRecordType;
2980 QualType FromType = From->getType();
2981 bool PointerConversions = false;
2982 if (isa<FieldDecl>(Member)) {
2983 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2984 auto FromPtrType = FromType->getAs<PointerType>();
2985 DestRecordType = Context.getAddrSpaceQualType(
2986 DestRecordType, FromPtrType
2987 ? FromType->getPointeeType().getAddressSpace()
2988 : FromType.getAddressSpace());
2989
2990 if (FromPtrType) {
2991 DestType = Context.getPointerType(DestRecordType);
2992 FromRecordType = FromPtrType->getPointeeType();
2993 PointerConversions = true;
2994 } else {
2995 DestType = DestRecordType;
2996 FromRecordType = FromType;
2997 }
2998 } else if (const auto *Method = dyn_cast<CXXMethodDecl>(Member)) {
2999 if (!Method->isImplicitObjectMemberFunction())
3000 return From;
3001
3002 DestType = Method->getThisType().getNonReferenceType();
3003 DestRecordType = Method->getFunctionObjectParameterType();
3004
3005 if (FromType->getAs<PointerType>()) {
3006 FromRecordType = FromType->getPointeeType();
3007 PointerConversions = true;
3008 } else {
3009 FromRecordType = FromType;
3010 DestType = DestRecordType;
3011 }
3012
3013 LangAS FromAS = FromRecordType.getAddressSpace();
3014 LangAS DestAS = DestRecordType.getAddressSpace();
3015 if (FromAS != DestAS) {
3016 QualType FromRecordTypeWithoutAS =
3017 Context.removeAddrSpaceQualType(FromRecordType);
3018 QualType FromTypeWithDestAS =
3019 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
3020 if (PointerConversions)
3021 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
3022 From = ImpCastExprToType(From, FromTypeWithDestAS,
3023 CK_AddressSpaceConversion, From->getValueKind())
3024 .get();
3025 }
3026 } else {
3027 // No conversion necessary.
3028 return From;
3029 }
3030
3031 if (DestType->isDependentType() || FromType->isDependentType())
3032 return From;
3033
3034 // If the unqualified types are the same, no conversion is necessary.
3035 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3036 return From;
3037
3038 SourceRange FromRange = From->getSourceRange();
3039 SourceLocation FromLoc = FromRange.getBegin();
3040
3041 ExprValueKind VK = From->getValueKind();
3042
3043 // C++ [class.member.lookup]p8:
3044 // [...] Ambiguities can often be resolved by qualifying a name with its
3045 // class name.
3046 //
3047 // If the member was a qualified name and the qualified referred to a
3048 // specific base subobject type, we'll cast to that intermediate type
3049 // first and then to the object in which the member is declared. That allows
3050 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3051 //
3052 // class Base { public: int x; };
3053 // class Derived1 : public Base { };
3054 // class Derived2 : public Base { };
3055 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3056 //
3057 // void VeryDerived::f() {
3058 // x = 17; // error: ambiguous base subobjects
3059 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3060 // }
3061 if (Qualifier && Qualifier->getAsType()) {
3062 QualType QType = QualType(Qualifier->getAsType(), 0);
3063 assert(QType->isRecordType() && "lookup done with non-record type");
3064
3065 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3066
3067 // In C++98, the qualifier type doesn't actually have to be a base
3068 // type of the object type, in which case we just ignore it.
3069 // Otherwise build the appropriate casts.
3070 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3071 CXXCastPath BasePath;
3072 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3073 FromLoc, FromRange, &BasePath))
3074 return ExprError();
3075
3076 if (PointerConversions)
3077 QType = Context.getPointerType(QType);
3078 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3079 VK, &BasePath).get();
3080
3081 FromType = QType;
3082 FromRecordType = QRecordType;
3083
3084 // If the qualifier type was the same as the destination type,
3085 // we're done.
3086 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3087 return From;
3088 }
3089 }
3090
3091 CXXCastPath BasePath;
3092 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3093 FromLoc, FromRange, &BasePath,
3094 /*IgnoreAccess=*/true))
3095 return ExprError();
3096
3097 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
3098 VK, &BasePath);
3099}
3100
3102 const LookupResult &R,
3103 bool HasTrailingLParen) {
3104 // Only when used directly as the postfix-expression of a call.
3105 if (!HasTrailingLParen)
3106 return false;
3107
3108 // Never if a scope specifier was provided.
3109 if (SS.isNotEmpty())
3110 return false;
3111
3112 // Only in C++ or ObjC++.
3113 if (!getLangOpts().CPlusPlus)
3114 return false;
3115
3116 // Turn off ADL when we find certain kinds of declarations during
3117 // normal lookup:
3118 for (const NamedDecl *D : R) {
3119 // C++0x [basic.lookup.argdep]p3:
3120 // -- a declaration of a class member
3121 // Since using decls preserve this property, we check this on the
3122 // original decl.
3123 if (D->isCXXClassMember())
3124 return false;
3125
3126 // C++0x [basic.lookup.argdep]p3:
3127 // -- a block-scope function declaration that is not a
3128 // using-declaration
3129 // NOTE: we also trigger this for function templates (in fact, we
3130 // don't check the decl type at all, since all other decl types
3131 // turn off ADL anyway).
3132 if (isa<UsingShadowDecl>(D))
3133 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3135 return false;
3136
3137 // C++0x [basic.lookup.argdep]p3:
3138 // -- a declaration that is neither a function or a function
3139 // template
3140 // And also for builtin functions.
3141 if (const auto *FDecl = dyn_cast<FunctionDecl>(D)) {
3142 // But also builtin functions.
3143 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3144 return false;
3145 } else if (!isa<FunctionTemplateDecl>(D))
3146 return false;
3147 }
3148
3149 return true;
3150}
3151
3152
3153/// Diagnoses obvious problems with the use of the given declaration
3154/// as an expression. This is only actually called for lookups that
3155/// were not overloaded, and it doesn't promise that the declaration
3156/// will in fact be used.
3158 bool AcceptInvalid) {
3159 if (D->isInvalidDecl() && !AcceptInvalid)
3160 return true;
3161
3162 if (isa<TypedefNameDecl>(D)) {
3163 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3164 return true;
3165 }
3166
3167 if (isa<ObjCInterfaceDecl>(D)) {
3168 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3169 return true;
3170 }
3171
3172 if (isa<NamespaceDecl>(D)) {
3173 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3174 return true;
3175 }
3176
3177 return false;
3178}
3179
3180// Certain multiversion types should be treated as overloaded even when there is
3181// only one result.
3183 assert(R.isSingleResult() && "Expected only a single result");
3184 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3185 return FD &&
3186 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3187}
3188
3190 LookupResult &R, bool NeedsADL,
3191 bool AcceptInvalidDecl) {
3192 // If this is a single, fully-resolved result and we don't need ADL,
3193 // just build an ordinary singleton decl ref.
3194 if (!NeedsADL && R.isSingleResult() &&
3198 R.getRepresentativeDecl(), nullptr,
3199 AcceptInvalidDecl);
3200
3201 // We only need to check the declaration if there's exactly one
3202 // result, because in the overloaded case the results can only be
3203 // functions and function templates.
3205 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl(),
3206 AcceptInvalidDecl))
3207 return ExprError();
3208
3209 // Otherwise, just build an unresolved lookup expression. Suppress
3210 // any lookup-related diagnostics; we'll hash these out later, when
3211 // we've picked a target.
3213
3216 R.getLookupNameInfo(), NeedsADL, R.begin(), R.end(),
3217 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
3218
3219 return ULE;
3220}
3221
3223 SourceLocation loc,
3224 ValueDecl *var);
3225
3227 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3228 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3229 bool AcceptInvalidDecl) {
3230 assert(D && "Cannot refer to a NULL declaration");
3231 assert(!isa<FunctionTemplateDecl>(D) &&
3232 "Cannot refer unambiguously to a function template");
3233
3234 SourceLocation Loc = NameInfo.getLoc();
3235 if (CheckDeclInExpr(*this, Loc, D, AcceptInvalidDecl)) {
3236 // Recovery from invalid cases (e.g. D is an invalid Decl).
3237 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3238 // diagnostics, as invalid decls use int as a fallback type.
3239 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
3240 }
3241
3242 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) {
3243 // Specifically diagnose references to class templates that are missing
3244 // a template argument list.
3245 diagnoseMissingTemplateArguments(SS, /*TemplateKeyword=*/false, TD, Loc);
3246 return ExprError();
3247 }
3248
3249 // Make sure that we're referring to a value.
3250 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) {
3251 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3252 Diag(D->getLocation(), diag::note_declared_at);
3253 return ExprError();
3254 }
3255
3256 // Check whether this declaration can be used. Note that we suppress
3257 // this check when we're going to perform argument-dependent lookup
3258 // on this function name, because this might not be the function
3259 // that overload resolution actually selects.
3260 if (DiagnoseUseOfDecl(D, Loc))
3261 return ExprError();
3262
3263 auto *VD = cast<ValueDecl>(D);
3264
3265 // Only create DeclRefExpr's for valid Decl's.
3266 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3267 return ExprError();
3268
3269 // Handle members of anonymous structs and unions. If we got here,
3270 // and the reference is to a class member indirect field, then this
3271 // must be the subject of a pointer-to-member expression.
3272 if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(VD);
3273 IndirectField && !IndirectField->isCXXClassMember())
3275 IndirectField);
3276
3277 QualType type = VD->getType();
3278 if (type.isNull())
3279 return ExprError();
3280 ExprValueKind valueKind = VK_PRValue;
3281
3282 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3283 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3284 // is expanded by some outer '...' in the context of the use.
3285 type = type.getNonPackExpansionType();
3286
3287 switch (D->getKind()) {
3288 // Ignore all the non-ValueDecl kinds.
3289#define ABSTRACT_DECL(kind)
3290#define VALUE(type, base)
3291#define DECL(type, base) case Decl::type:
3292#include "clang/AST/DeclNodes.inc"
3293 llvm_unreachable("invalid value decl kind");
3294
3295 // These shouldn't make it here.
3296 case Decl::ObjCAtDefsField:
3297 llvm_unreachable("forming non-member reference to ivar?");
3298
3299 // Enum constants are always r-values and never references.
3300 // Unresolved using declarations are dependent.
3301 case Decl::EnumConstant:
3302 case Decl::UnresolvedUsingValue:
3303 case Decl::OMPDeclareReduction:
3304 case Decl::OMPDeclareMapper:
3305 valueKind = VK_PRValue;
3306 break;
3307
3308 // Fields and indirect fields that got here must be for
3309 // pointer-to-member expressions; we just call them l-values for
3310 // internal consistency, because this subexpression doesn't really
3311 // exist in the high-level semantics.
3312 case Decl::Field:
3313 case Decl::IndirectField:
3314 case Decl::ObjCIvar:
3315 assert((getLangOpts().CPlusPlus || isAttrContext()) &&
3316 "building reference to field in C?");
3317
3318 // These can't have reference type in well-formed programs, but
3319 // for internal consistency we do this anyway.
3320 type = type.getNonReferenceType();
3321 valueKind = VK_LValue;
3322 break;
3323
3324 // Non-type template parameters are either l-values or r-values
3325 // depending on the type.
3326 case Decl::NonTypeTemplateParm: {
3327 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3328 type = reftype->getPointeeType();
3329 valueKind = VK_LValue; // even if the parameter is an r-value reference
3330 break;
3331 }
3332
3333 // [expr.prim.id.unqual]p2:
3334 // If the entity is a template parameter object for a template
3335 // parameter of type T, the type of the expression is const T.
3336 // [...] The expression is an lvalue if the entity is a [...] template
3337 // parameter object.
3338 if (type->isRecordType()) {
3339 type = type.getUnqualifiedType().withConst();
3340 valueKind = VK_LValue;
3341 break;
3342 }
3343
3344 // For non-references, we need to strip qualifiers just in case
3345 // the template parameter was declared as 'const int' or whatever.
3346 valueKind = VK_PRValue;
3347 type = type.getUnqualifiedType();
3348 break;
3349 }
3350
3351 case Decl::Var:
3352 case Decl::VarTemplateSpecialization:
3353 case Decl::VarTemplatePartialSpecialization:
3354 case Decl::Decomposition:
3355 case Decl::Binding:
3356 case Decl::OMPCapturedExpr:
3357 // In C, "extern void blah;" is valid and is an r-value.
3358 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3359 type->isVoidType()) {
3360 valueKind = VK_PRValue;
3361 break;
3362 }
3363 [[fallthrough]];
3364
3365 case Decl::ImplicitParam:
3366 case Decl::ParmVar: {
3367 // These are always l-values.
3368 valueKind = VK_LValue;
3369 type = type.getNonReferenceType();
3370
3371 // FIXME: Does the addition of const really only apply in
3372 // potentially-evaluated contexts? Since the variable isn't actually
3373 // captured in an unevaluated context, it seems that the answer is no.
3374 if (!isUnevaluatedContext()) {
3375 QualType CapturedType = getCapturedDeclRefType(cast<ValueDecl>(VD), Loc);
3376 if (!CapturedType.isNull())
3377 type = CapturedType;
3378 }
3379 break;
3380 }
3381
3382 case Decl::Function: {
3383 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3386 valueKind = VK_PRValue;
3387 break;
3388 }
3389 }
3390
3391 const FunctionType *fty = type->castAs<FunctionType>();
3392
3393 // If we're referring to a function with an __unknown_anytype
3394 // result type, make the entire expression __unknown_anytype.
3395 if (fty->getReturnType() == Context.UnknownAnyTy) {
3397 valueKind = VK_PRValue;
3398 break;
3399 }
3400
3401 // Functions are l-values in C++.
3402 if (getLangOpts().CPlusPlus) {
3403 valueKind = VK_LValue;
3404 break;
3405 }
3406
3407 // C99 DR 316 says that, if a function type comes from a
3408 // function definition (without a prototype), that type is only
3409 // used for checking compatibility. Therefore, when referencing
3410 // the function, we pretend that we don't have the full function
3411 // type.
3412 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3414 fty->getExtInfo());
3415
3416 // Functions are r-values in C.
3417 valueKind = VK_PRValue;
3418 break;
3419 }
3420
3421 case Decl::CXXDeductionGuide:
3422 llvm_unreachable("building reference to deduction guide");
3423
3424 case Decl::MSProperty:
3425 case Decl::MSGuid:
3426 case Decl::TemplateParamObject:
3427 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3428 // capture in OpenMP, or duplicated between host and device?
3429 valueKind = VK_LValue;
3430 break;
3431
3432 case Decl::UnnamedGlobalConstant:
3433 valueKind = VK_LValue;
3434 break;
3435
3436 case Decl::CXXMethod:
3437 // If we're referring to a method with an __unknown_anytype
3438 // result type, make the entire expression __unknown_anytype.
3439 // This should only be possible with a type written directly.
3440 if (const FunctionProtoType *proto =
3441 dyn_cast<FunctionProtoType>(VD->getType()))
3442 if (proto->getReturnType() == Context.UnknownAnyTy) {
3444 valueKind = VK_PRValue;
3445 break;
3446 }
3447
3448 // C++ methods are l-values if static, r-values if non-static.
3449 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3450 valueKind = VK_LValue;
3451 break;
3452 }
3453 [[fallthrough]];
3454
3455 case Decl::CXXConversion:
3456 case Decl::CXXDestructor:
3457 case Decl::CXXConstructor:
3458 valueKind = VK_PRValue;
3459 break;
3460 }
3461
3462 auto *E =
3463 BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3464 /*FIXME: TemplateKWLoc*/ SourceLocation(), TemplateArgs);
3465 // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3466 // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3467 // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3468 // diagnostics).
3469 if (VD->isInvalidDecl() && E)
3470 return CreateRecoveryExpr(E->getBeginLoc(), E->getEndLoc(), {E});
3471 return E;
3472}
3473
3474static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3476 Target.resize(CharByteWidth * (Source.size() + 1));
3477 char *ResultPtr = &Target[0];
3478 const llvm::UTF8 *ErrorPtr;
3479 bool success =
3480 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3481 (void)success;
3482 assert(success);
3483 Target.resize(ResultPtr - &Target[0]);
3484}
3485
3488 Decl *currentDecl = getPredefinedExprDecl(CurContext);
3489 if (!currentDecl) {
3490 Diag(Loc, diag::ext_predef_outside_function);
3491 currentDecl = Context.getTranslationUnitDecl();
3492 }
3493
3494 QualType ResTy;
3495 StringLiteral *SL = nullptr;
3496 if (cast<DeclContext>(currentDecl)->isDependentContext())
3497 ResTy = Context.DependentTy;
3498 else {
3499 // Pre-defined identifiers are of type char[x], where x is the length of
3500 // the string.
3501 bool ForceElaboratedPrinting =
3502 IK == PredefinedIdentKind::Function && getLangOpts().MSVCCompat;
3503 auto Str =
3504 PredefinedExpr::ComputeName(IK, currentDecl, ForceElaboratedPrinting);
3505 unsigned Length = Str.length();
3506
3507 llvm::APInt LengthI(32, Length + 1);
3510 ResTy =
3512 SmallString<32> RawChars;
3514 Str, RawChars);
3515 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3517 /*IndexTypeQuals*/ 0);
3519 /*Pascal*/ false, ResTy, Loc);
3520 } else {
3522 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3524 /*IndexTypeQuals*/ 0);
3526 /*Pascal*/ false, ResTy, Loc);
3527 }
3528 }
3529
3530 return PredefinedExpr::Create(Context, Loc, ResTy, IK, LangOpts.MicrosoftExt,
3531 SL);
3532}
3533
3536}
3537
3539 SmallString<16> CharBuffer;
3540 bool Invalid = false;
3541 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3542 if (Invalid)
3543 return ExprError();
3544
3545 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3546 PP, Tok.getKind());
3547 if (Literal.hadError())
3548 return ExprError();
3549
3550 QualType Ty;
3551 if (Literal.isWide())
3552 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3553 else if (Literal.isUTF8() && getLangOpts().C23)
3554 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C23
3555 else if (Literal.isUTF8() && getLangOpts().Char8)
3556 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3557 else if (Literal.isUTF16())
3558 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3559 else if (Literal.isUTF32())
3560 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3561 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3562 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3563 else
3564 Ty = Context.CharTy; // 'x' -> char in C++;
3565 // u8'x' -> char in C11-C17 and in C++ without char8_t.
3566
3568 if (Literal.isWide())
3570 else if (Literal.isUTF16())
3572 else if (Literal.isUTF32())
3574 else if (Literal.isUTF8())
3576
3577 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3578 Tok.getLocation());
3579
3580 if (Literal.getUDSuffix().empty())
3581 return Lit;
3582
3583 // We're building a user-defined literal.
3584 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3585 SourceLocation UDSuffixLoc =
3586 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3587
3588 // Make sure we're allowed user-defined literals here.
3589 if (!UDLScope)
3590 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3591
3592 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3593 // operator "" X (ch)
3594 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3595 Lit, Tok.getLocation());
3596}
3597
3599 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3601 llvm::APInt(IntSize, Val, /*isSigned=*/true),
3602 Context.IntTy, Loc);
3603}
3604
3607 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3608
3609 using llvm::APFloat;
3610 APFloat Val(Format);
3611
3612 llvm::RoundingMode RM = S.CurFPFeatures.getRoundingMode();
3613 if (RM == llvm::RoundingMode::Dynamic)
3614 RM = llvm::RoundingMode::NearestTiesToEven;
3615 APFloat::opStatus result = Literal.GetFloatValue(Val, RM);
3616
3617 // Overflow is always an error, but underflow is only an error if
3618 // we underflowed to zero (APFloat reports denormals as underflow).
3619 if ((result & APFloat::opOverflow) ||
3620 ((result & APFloat::opUnderflow) && Val.isZero())) {
3621 unsigned diagnostic;
3622 SmallString<20> buffer;
3623 if (result & APFloat::opOverflow) {
3624 diagnostic = diag::warn_float_overflow;
3625 APFloat::getLargest(Format).toString(buffer);
3626 } else {
3627 diagnostic = diag::warn_float_underflow;
3628 APFloat::getSmallest(Format).toString(buffer);
3629 }
3630
3631 S.Diag(Loc, diagnostic) << Ty << buffer.str();
3632 }
3633
3634 bool isExact = (result == APFloat::opOK);
3635 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3636}
3637
3639 assert(E && "Invalid expression");
3640
3641 if (E->isValueDependent())
3642 return false;
3643
3644 QualType QT = E->getType();
3645 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3646 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3647 return true;
3648 }
3649
3650 llvm::APSInt ValueAPS;
3652
3653 if (R.isInvalid())
3654 return true;
3655
3656 // GCC allows the value of unroll count to be 0.
3657 // https://gcc.gnu.org/onlinedocs/gcc/Loop-Specific-Pragmas.html says
3658 // "The values of 0 and 1 block any unrolling of the loop."
3659 // The values doesn't have to be strictly positive in '#pragma GCC unroll' and
3660 // '#pragma unroll' cases.
3661 bool ValueIsPositive =
3662 AllowZero ? ValueAPS.isNonNegative() : ValueAPS.isStrictlyPositive();
3663 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3664 Diag(E->getExprLoc(), diag::err_requires_positive_value)
3665 << toString(ValueAPS, 10) << ValueIsPositive;
3666 return true;
3667 }
3668
3669 return false;
3670}
3671
3673 // Fast path for a single digit (which is quite common). A single digit
3674 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3675 if (Tok.getLength() == 1 || Tok.getKind() == tok::binary_data) {
3676 const uint8_t Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3677 return ActOnIntegerConstant(Tok.getLocation(), Val);
3678 }
3679
3680 SmallString<128> SpellingBuffer;
3681 // NumericLiteralParser wants to overread by one character. Add padding to
3682 // the buffer in case the token is copied to the buffer. If getSpelling()
3683 // returns a StringRef to the memory buffer, it should have a null char at
3684 // the EOF, so it is also safe.
3685 SpellingBuffer.resize(Tok.getLength() + 1);
3686
3687 // Get the spelling of the token, which eliminates trigraphs, etc.
3688 bool Invalid = false;
3689 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3690 if (Invalid)
3691 return ExprError();
3692
3693 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3696 if (Literal.hadError)
3697 return ExprError();
3698
3699 if (Literal.hasUDSuffix()) {
3700 // We're building a user-defined literal.
3701 const IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3702 SourceLocation UDSuffixLoc =
3703 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3704
3705 // Make sure we're allowed user-defined literals here.
3706 if (!UDLScope)
3707 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3708
3709 QualType CookedTy;
3710 if (Literal.isFloatingLiteral()) {
3711 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3712 // long double, the literal is treated as a call of the form
3713 // operator "" X (f L)
3714 CookedTy = Context.LongDoubleTy;
3715 } else {
3716 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3717 // unsigned long long, the literal is treated as a call of the form
3718 // operator "" X (n ULL)
3719 CookedTy = Context.UnsignedLongLongTy;
3720 }
3721
3722 DeclarationName OpName =
3724 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3725 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3726
3727 SourceLocation TokLoc = Tok.getLocation();
3728
3729 // Perform literal operator lookup to determine if we're building a raw
3730 // literal or a cooked one.
3731 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3732 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3733 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3734 /*AllowStringTemplatePack*/ false,
3735 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3737 // Lookup failure for imaginary constants isn't fatal, there's still the
3738 // GNU extension producing _Complex types.
3739 break;
3740 case LOLR_Error:
3741 return ExprError();
3742 case LOLR_Cooked: {
3743 Expr *Lit;
3744 if (Literal.isFloatingLiteral()) {
3745 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3746 } else {
3747 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3748 if (Literal.GetIntegerValue(ResultVal))
3749 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3750 << /* Unsigned */ 1;
3751 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3752 Tok.getLocation());
3753 }
3754 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3755 }
3756
3757 case LOLR_Raw: {
3758 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3759 // literal is treated as a call of the form
3760 // operator "" X ("n")
3761 unsigned Length = Literal.getUDSuffixOffset();
3764 llvm::APInt(32, Length + 1), nullptr, ArraySizeModifier::Normal, 0);
3765 Expr *Lit =
3766 StringLiteral::Create(Context, StringRef(TokSpelling.data(), Length),
3768 /*Pascal*/ false, StrTy, &TokLoc, 1);
3769 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3770 }
3771
3772 case LOLR_Template: {
3773 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3774 // template), L is treated as a call fo the form
3775 // operator "" X <'c1', 'c2', ... 'ck'>()
3776 // where n is the source character sequence c1 c2 ... ck.
3777 TemplateArgumentListInfo ExplicitArgs;
3778 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3779 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3780 llvm::APSInt Value(CharBits, CharIsUnsigned);
3781 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3782 Value = TokSpelling[I];
3785 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3786 }
3787 return BuildLiteralOperatorCall(R, OpNameInfo, {}, TokLoc, &ExplicitArgs);
3788 }
3790 llvm_unreachable("unexpected literal operator lookup result");
3791 }
3792 }
3793
3794 Expr *Res;
3795
3796 if (Literal.isFixedPointLiteral()) {
3797 QualType Ty;
3798
3799 if (Literal.isAccum) {
3800 if (Literal.isHalf) {
3801 Ty = Context.ShortAccumTy;
3802 } else if (Literal.isLong) {
3803 Ty = Context.LongAccumTy;
3804 } else {
3805 Ty = Context.AccumTy;
3806 }
3807 } else if (Literal.isFract) {
3808 if (Literal.isHalf) {
3809 Ty = Context.ShortFractTy;
3810 } else if (Literal.isLong) {
3811 Ty = Context.LongFractTy;
3812 } else {
3813 Ty = Context.FractTy;
3814 }
3815 }
3816
3817 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3818
3819 bool isSigned = !Literal.isUnsigned;
3820 unsigned scale = Context.getFixedPointScale(Ty);
3821 unsigned bit_width = Context.getTypeInfo(Ty).Width;
3822
3823 llvm::APInt Val(bit_width, 0, isSigned);
3824 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3825 bool ValIsZero = Val.isZero() && !Overflowed;
3826
3827 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3828 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3829 // Clause 6.4.4 - The value of a constant shall be in the range of
3830 // representable values for its type, with exception for constants of a
3831 // fract type with a value of exactly 1; such a constant shall denote
3832 // the maximal value for the type.
3833 --Val;
3834 else if (Val.ugt(MaxVal) || Overflowed)
3835 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3836
3838 Tok.getLocation(), scale);
3839 } else if (Literal.isFloatingLiteral()) {
3840 QualType Ty;
3841 if (Literal.isHalf){
3842 if (getLangOpts().HLSL ||
3843 getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
3844 Ty = Context.HalfTy;
3845 else {
3846 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3847 return ExprError();
3848 }
3849 } else if (Literal.isFloat)
3850 Ty = Context.FloatTy;
3851 else if (Literal.isLong)
3853 else if (Literal.isFloat16)
3854 Ty = Context.Float16Ty;
3855 else if (Literal.isFloat128)
3856 Ty = Context.Float128Ty;
3857 else if (getLangOpts().HLSL)
3858 Ty = Context.FloatTy;
3859 else
3860 Ty = Context.DoubleTy;
3861
3862 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3863
3864 if (Ty == Context.DoubleTy) {
3865 if (getLangOpts().SinglePrecisionConstants) {
3866 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
3867 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3868 }
3869 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
3870 "cl_khr_fp64", getLangOpts())) {
3871 // Impose single-precision float type when cl_khr_fp64 is not enabled.
3872 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
3874 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3875 }
3876 }
3877 } else if (!Literal.isIntegerLiteral()) {
3878 return ExprError();
3879 } else {
3880 QualType Ty;
3881
3882 // 'z/uz' literals are a C++23 feature.
3883 if (Literal.isSizeT)
3886 ? diag::warn_cxx20_compat_size_t_suffix
3887 : diag::ext_cxx23_size_t_suffix
3888 : diag::err_cxx23_size_t_suffix);
3889
3890 // 'wb/uwb' literals are a C23 feature. We support _BitInt as a type in C++,
3891 // but we do not currently support the suffix in C++ mode because it's not
3892 // entirely clear whether WG21 will prefer this suffix to return a library
3893 // type such as std::bit_int instead of returning a _BitInt. '__wb/__uwb'
3894 // literals are a C++ extension.
3895 if (Literal.isBitInt)
3896 PP.Diag(Tok.getLocation(),
3897 getLangOpts().CPlusPlus ? diag::ext_cxx_bitint_suffix
3898 : getLangOpts().C23 ? diag::warn_c23_compat_bitint_suffix
3899 : diag::ext_c23_bitint_suffix);
3900
3901 // Get the value in the widest-possible width. What is "widest" depends on
3902 // whether the literal is a bit-precise integer or not. For a bit-precise
3903 // integer type, try to scan the source to determine how many bits are
3904 // needed to represent the value. This may seem a bit expensive, but trying
3905 // to get the integer value from an overly-wide APInt is *extremely*
3906 // expensive, so the naive approach of assuming
3907 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
3908 unsigned BitsNeeded =
3909 Literal.isBitInt ? llvm::APInt::getSufficientBitsNeeded(
3910 Literal.getLiteralDigits(), Literal.getRadix())
3912 llvm::APInt ResultVal(BitsNeeded, 0);
3913
3914 if (Literal.GetIntegerValue(ResultVal)) {
3915 // If this value didn't fit into uintmax_t, error and force to ull.
3916 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3917 << /* Unsigned */ 1;
3919 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3920 "long long is not intmax_t?");
3921 } else {
3922 // If this value fits into a ULL, try to figure out what else it fits into
3923 // according to the rules of C99 6.4.4.1p5.
3924
3925 // Octal, Hexadecimal, and integers with a U suffix are allowed to
3926 // be an unsigned int.
3927 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3928
3929 // HLSL doesn't really have `long` or `long long`. We support the `ll`
3930 // suffix for portability of code with C++, but both `l` and `ll` are
3931 // 64-bit integer types, and we want the type of `1l` and `1ll` to be the
3932 // same.
3933 if (getLangOpts().HLSL && !Literal.isLong && Literal.isLongLong) {
3934 Literal.isLong = true;
3935 Literal.isLongLong = false;
3936 }
3937
3938 // Check from smallest to largest, picking the smallest type we can.
3939 unsigned Width = 0;
3940
3941 // Microsoft specific integer suffixes are explicitly sized.
3942 if (Literal.MicrosoftInteger) {
3943 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3944 Width = 8;
3945 Ty = Context.CharTy;
3946 } else {
3947 Width = Literal.MicrosoftInteger;
3948 Ty = Context.getIntTypeForBitwidth(Width,
3949 /*Signed=*/!Literal.isUnsigned);
3950 }
3951 }
3952
3953 // Bit-precise integer literals are automagically-sized based on the
3954 // width required by the literal.
3955 if (Literal.isBitInt) {
3956 // The signed version has one more bit for the sign value. There are no
3957 // zero-width bit-precise integers, even if the literal value is 0.
3958 Width = std::max(ResultVal.getActiveBits(), 1u) +
3959 (Literal.isUnsigned ? 0u : 1u);
3960
3961 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
3962 // and reset the type to the largest supported width.
3963 unsigned int MaxBitIntWidth =
3965 if (Width > MaxBitIntWidth) {
3966 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3967 << Literal.isUnsigned;
3968 Width = MaxBitIntWidth;
3969 }
3970
3971 // Reset the result value to the smaller APInt and select the correct
3972 // type to be used. Note, we zext even for signed values because the
3973 // literal itself is always an unsigned value (a preceeding - is a
3974 // unary operator, not part of the literal).
3975 ResultVal = ResultVal.zextOrTrunc(Width);
3976 Ty = Context.getBitIntType(Literal.isUnsigned, Width);
3977 }
3978
3979 // Check C++23 size_t literals.
3980 if (Literal.isSizeT) {
3981 assert(!Literal.MicrosoftInteger &&
3982 "size_t literals can't be Microsoft literals");
3983 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
3985
3986 // Does it fit in size_t?
3987 if (ResultVal.isIntN(SizeTSize)) {
3988 // Does it fit in ssize_t?
3989 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
3991 else if (AllowUnsigned)
3992 Ty = Context.getSizeType();
3993 Width = SizeTSize;
3994 }
3995 }
3996
3997 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
3998 !Literal.isSizeT) {
3999 // Are int/unsigned possibilities?
4000 unsigned IntSize = Context.getTargetInfo().getIntWidth();
4001
4002 // Does it fit in a unsigned int?
4003 if (ResultVal.isIntN(IntSize)) {
4004 // Does it fit in a signed int?
4005 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4006 Ty = Context.IntTy;
4007 else if (AllowUnsigned)
4009 Width = IntSize;
4010 }
4011 }
4012
4013 // Are long/unsigned long possibilities?
4014 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4015 unsigned LongSize = Context.getTargetInfo().getLongWidth();
4016
4017 // Does it fit in a unsigned long?
4018 if (ResultVal.isIntN(LongSize)) {
4019 // Does it fit in a signed long?
4020 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4021 Ty = Context.LongTy;
4022 else if (AllowUnsigned)
4024 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4025 // is compatible.
4026 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4027 const unsigned LongLongSize =
4029 Diag(Tok.getLocation(),
4031 ? Literal.isLong
4032 ? diag::warn_old_implicitly_unsigned_long_cxx
4033 : /*C++98 UB*/ diag::
4034 ext_old_implicitly_unsigned_long_cxx
4035 : diag::warn_old_implicitly_unsigned_long)
4036 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4037 : /*will be ill-formed*/ 1);
4039 }
4040 Width = LongSize;
4041 }
4042 }
4043
4044 // Check long long if needed.
4045 if (Ty.isNull() && !Literal.isSizeT) {
4046 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4047
4048 // Does it fit in a unsigned long long?
4049 if (ResultVal.isIntN(LongLongSize)) {
4050 // Does it fit in a signed long long?
4051 // To be compatible with MSVC, hex integer literals ending with the
4052 // LL or i64 suffix are always signed in Microsoft mode.
4053 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4054 (getLangOpts().MSVCCompat && Literal.isLongLong)))
4055 Ty = Context.LongLongTy;
4056 else if (AllowUnsigned)
4058 Width = LongLongSize;
4059
4060 // 'long long' is a C99 or C++11 feature, whether the literal
4061 // explicitly specified 'long long' or we needed the extra width.
4062 if (getLangOpts().CPlusPlus)
4063 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11
4064 ? diag::warn_cxx98_compat_longlong
4065 : diag::ext_cxx11_longlong);
4066 else if (!getLangOpts().C99)
4067 Diag(Tok.getLocation(), diag::ext_c99_longlong);
4068 }
4069 }
4070
4071 // If we still couldn't decide a type, we either have 'size_t' literal
4072 // that is out of range, or a decimal literal that does not fit in a
4073 // signed long long and has no U suffix.
4074 if (Ty.isNull()) {
4075 if (Literal.isSizeT)
4076 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4077 << Literal.isUnsigned;
4078 else
4079 Diag(Tok.getLocation(),
4080 diag::ext_integer_literal_too_large_for_signed);
4083 }
4084
4085 if (ResultVal.getBitWidth() != Width)
4086 ResultVal = ResultVal.trunc(Width);
4087 }
4088 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4089 }
4090
4091 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4092 if (Literal.isImaginary) {
4093 Res = new (Context) ImaginaryLiteral(Res,
4095
4096 // In C++, this is a GNU extension. In C, it's a C2y extension.
4097 unsigned DiagId;
4098 if (getLangOpts().CPlusPlus)
4099 DiagId = diag::ext_gnu_imaginary_constant;
4100 else if (getLangOpts().C2y)
4101 DiagId = diag::warn_c23_compat_imaginary_constant;
4102 else
4103 DiagId = diag::ext_c2y_imaginary_constant;
4104 Diag(Tok.getLocation(), DiagId);
4105 }
4106 return Res;
4107}
4108
4110 assert(E && "ActOnParenExpr() missing expr");
4111 QualType ExprTy = E->getType();
4112 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4113 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4114 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4115 return new (Context) ParenExpr(L, R, E);
4116}
4117
4120 SourceRange ArgRange) {
4121 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4122 // scalar or vector data type argument..."
4123 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4124 // type (C99 6.2.5p18) or void.
4125 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4126 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4127 << T << ArgRange;
4128 return true;
4129 }
4130
4131 assert((T->isVoidType() || !T->isIncompleteType()) &&
4132 "Scalar types should always be complete");
4133 return false;
4134}
4135
4138 SourceRange ArgRange) {
4139 // builtin_vectorelements supports both fixed-sized and scalable vectors.
4140 if (!T->isVectorType() && !T->isSizelessVectorType())
4141 return S.Diag(Loc, diag::err_builtin_non_vector_type)
4142 << ""
4143 << "__builtin_vectorelements" << T << ArgRange;
4144
4145 return false;
4146}
4147
4150 SourceRange ArgRange) {
4151 if (S.checkPointerAuthEnabled(Loc, ArgRange))
4152 return true;
4153
4154 if (!T->isFunctionType() && !T->isFunctionPointerType() &&
4156 S.Diag(Loc, diag::err_ptrauth_type_disc_undiscriminated) << T << ArgRange;
4157 return true;
4158 }
4159
4160 return false;
4161}
4162
4165 SourceRange ArgRange,
4166 UnaryExprOrTypeTrait TraitKind) {
4167 // Invalid types must be hard errors for SFINAE in C++.
4168 if (S.LangOpts.CPlusPlus)
4169 return true;
4170
4171 // C99 6.5.3.4p1:
4172 if (T->isFunctionType() &&
4173 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4174 TraitKind == UETT_PreferredAlignOf)) {
4175 // sizeof(function)/alignof(function) is allowed as an extension.
4176 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4177 << getTraitSpelling(TraitKind) << ArgRange;
4178 return false;
4179 }
4180
4181 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4182 // this is an error (OpenCL v1.1 s6.3.k)
4183 if (T->isVoidType()) {
4184 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4185 : diag::ext_sizeof_alignof_void_type;
4186 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4187 return false;
4188 }
4189
4190 return true;
4191}
4192
4195 SourceRange ArgRange,
4196 UnaryExprOrTypeTrait TraitKind) {
4197 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4198 // runtime doesn't allow it.
4200 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4201 << T << (TraitKind == UETT_SizeOf)
4202 << ArgRange;
4203 return true;
4204 }
4205
4206 return false;
4207}
4208
4209/// Check whether E is a pointer from a decayed array type (the decayed
4210/// pointer type is equal to T) and emit a warning if it is.
4212 const Expr *E) {
4213 // Don't warn if the operation changed the type.
4214 if (T != E->getType())
4215 return;
4216
4217 // Now look for array decays.
4218 const auto *ICE = dyn_cast<ImplicitCastExpr>(E);
4219 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4220 return;
4221
4222 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4223 << ICE->getType()
4224 << ICE->getSubExpr()->getType();
4225}
4226
4228 UnaryExprOrTypeTrait ExprKind) {
4229 QualType ExprTy = E->getType();
4230 assert(!ExprTy->isReferenceType());
4231
4232 bool IsUnevaluatedOperand =
4233 (ExprKind == UETT_SizeOf || ExprKind == UETT_DataSizeOf ||
4234 ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4235 ExprKind == UETT_VecStep);
4236 if (IsUnevaluatedOperand) {
4238 if (Result.isInvalid())
4239 return true;
4240 E = Result.get();
4241 }
4242
4243 // The operand for sizeof and alignof is in an unevaluated expression context,
4244 // so side effects could result in unintended consequences.
4245 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4246 // used to build SFINAE gadgets.
4247 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4248 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4250 !E->getType()->isVariableArrayType() &&
4251 E->HasSideEffects(Context, false))
4252 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4253
4254 if (ExprKind == UETT_VecStep)
4255 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4256 E->getSourceRange());
4257
4258 if (ExprKind == UETT_VectorElements)
4259 return CheckVectorElementsTraitOperandType(*this, ExprTy, E->getExprLoc(),
4260 E->getSourceRange());
4261
4262 // Explicitly list some types as extensions.
4263 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4264 E->getSourceRange(), ExprKind))
4265 return false;
4266
4267 // WebAssembly tables are always illegal operands to unary expressions and
4268 // type traits.
4269 if (Context.getTargetInfo().getTriple().isWasm() &&
4271 Diag(E->getExprLoc(), diag::err_wasm_table_invalid_uett_operand)
4272 << getTraitSpelling(ExprKind);
4273 return true;
4274 }
4275
4276 // 'alignof' applied to an expression only requires the base element type of
4277 // the expression to be complete. 'sizeof' requires the expression's type to
4278 // be complete (and will attempt to complete it if it's an array of unknown
4279 // bound).
4280 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4283 diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4284 getTraitSpelling(ExprKind), E->getSourceRange()))
4285 return true;
4286 } else {
4288 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4289 getTraitSpelling(ExprKind), E->getSourceRange()))
4290 return true;
4291 }
4292
4293 // Completing the expression's type may have changed it.
4294 ExprTy = E->getType();
4295 assert(!ExprTy->isReferenceType());
4296
4297 if (ExprTy->isFunctionType()) {
4298 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4299 << getTraitSpelling(ExprKind) << E->getSourceRange();
4300 return true;
4301 }
4302
4303 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4304 E->getSourceRange(), ExprKind))
4305 return true;
4306
4307 if (ExprKind == UETT_SizeOf) {
4308 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4309 if (const auto *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4310 QualType OType = PVD->getOriginalType();
4311 QualType Type = PVD->getType();
4312 if (Type->isPointerType() && OType->isArrayType()) {
4313 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4314 << Type << OType;
4315 Diag(PVD->getLocation(), diag::note_declared_at);
4316 }
4317 }
4318 }
4319
4320 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4321 // decays into a pointer and returns an unintended result. This is most
4322 // likely a typo for "sizeof(array) op x".
4323 if (const auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4324 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4325 BO->getLHS());
4326 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4327 BO->getRHS());
4328 }
4329 }
4330
4331 return false;
4332}
4333
4334static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4335 // Cannot know anything else if the expression is dependent.
4336 if (E->isTypeDependent())
4337 return false;
4338
4339 if (E->getObjectKind() == OK_BitField) {
4340 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4341 << 1 << E->getSourceRange();
4342 return true;
4343 }
4344
4345 ValueDecl *D = nullptr;
4346 Expr *Inner = E->IgnoreParens();
4347 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4348 D = DRE->getDecl();
4349 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4350 D = ME->getMemberDecl();
4351 }
4352
4353 // If it's a field, require the containing struct to have a
4354 // complete definition so that we can compute the layout.
4355 //
4356 // This can happen in C++11 onwards, either by naming the member
4357 // in a way that is not transformed into a member access expression
4358 // (in an unevaluated operand, for instance), or by naming the member
4359 // in a trailing-return-type.
4360 //
4361 // For the record, since __alignof__ on expressions is a GCC
4362 // extension, GCC seems to permit this but always gives the
4363 // nonsensical answer 0.
4364 //
4365 // We don't really need the layout here --- we could instead just
4366 // directly check for all the appropriate alignment-lowing
4367 // attributes --- but that would require duplicating a lot of
4368 // logic that just isn't worth duplicating for such a marginal
4369 // use-case.
4370 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4371 // Fast path this check, since we at least know the record has a
4372 // definition if we can find a member of it.
4373 if (!FD->getParent()->isCompleteDefinition()) {
4374 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4375 << E->getSourceRange();
4376 return true;
4377 }
4378
4379 // Otherwise, if it's a field, and the field doesn't have
4380 // reference type, then it must have a complete type (or be a
4381 // flexible array member, which we explicitly want to
4382 // white-list anyway), which makes the following checks trivial.
4383 if (!FD->getType()->isReferenceType())
4384 return false;
4385 }
4386
4387 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4388}
4389
4391 E = E->IgnoreParens();
4392
4393 // Cannot know anything else if the expression is dependent.
4394 if (E->isTypeDependent())
4395 return false;
4396
4397 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4398}
4399
4401 CapturingScopeInfo *CSI) {
4402 assert(T->isVariablyModifiedType());
4403 assert(CSI != nullptr);
4404
4405 // We're going to walk down into the type and look for VLA expressions.
4406 do {
4407 const Type *Ty = T.getTypePtr();
4408 switch (Ty->getTypeClass()) {
4409#define TYPE(Class, Base)
4410#define ABSTRACT_TYPE(Class, Base)
4411#define NON_CANONICAL_TYPE(Class, Base)
4412#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4413#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4414#include "clang/AST/TypeNodes.inc"
4415 T = QualType();
4416 break;
4417 // These types are never variably-modified.
4418 case Type::Builtin:
4419 case Type::Complex:
4420 case Type::Vector:
4421 case Type::ExtVector:
4422 case Type::ConstantMatrix:
4423 case Type::Record:
4424 case Type::Enum:
4425 case Type::TemplateSpecialization:
4426 case Type::ObjCObject:
4427 case Type::ObjCInterface:
4428 case Type::ObjCObjectPointer:
4429 case Type::ObjCTypeParam:
4430 case Type::Pipe:
4431 case Type::BitInt:
4432 llvm_unreachable("type class is never variably-modified!");
4433 case Type::Elaborated:
4434 T = cast<ElaboratedType>(Ty)->getNamedType();
4435 break;
4436 case Type::Adjusted:
4437 T = cast<AdjustedType>(Ty)->getOriginalType();
4438 break;
4439 case Type::Decayed:
4440 T = cast<DecayedType>(Ty)->getPointeeType();
4441 break;
4442 case Type::ArrayParameter:
4443 T = cast<ArrayParameterType>(Ty)->getElementType();
4444 break;
4445 case Type::Pointer:
4446 T = cast<PointerType>(Ty)->getPointeeType();
4447 break;
4448 case Type::BlockPointer:
4449 T = cast<BlockPointerType>(Ty)->getPointeeType();
4450 break;
4451 case Type::LValueReference:
4452 case Type::RValueReference:
4453 T = cast<ReferenceType>(Ty)->getPointeeType();
4454 break;
4455 case Type::MemberPointer:
4456 T = cast<MemberPointerType>(Ty)->getPointeeType();
4457 break;
4458 case Type::ConstantArray:
4459 case Type::IncompleteArray:
4460 // Losing element qualification here is fine.
4461 T = cast<ArrayType>(Ty)->getElementType();
4462 break;
4463 case Type::VariableArray: {
4464 // Losing element qualification here is fine.
4465 const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4466
4467 // Unknown size indication requires no size computation.
4468 // Otherwise, evaluate and record it.
4469 auto Size = VAT->getSizeExpr();
4470 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4471 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4472 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4473
4474 T = VAT->getElementType();
4475 break;
4476 }
4477 case Type::FunctionProto:
4478 case Type::FunctionNoProto:
4479 T = cast<FunctionType>(Ty)->getReturnType();
4480 break;
4481 case Type::Paren:
4482 case Type::TypeOf:
4483 case Type::UnaryTransform:
4484 case Type::Attributed:
4485 case Type::BTFTagAttributed:
4486 case Type::HLSLAttributedResource:
4487 case Type::SubstTemplateTypeParm:
4488 case Type::MacroQualified:
4489 case Type::CountAttributed:
4490 // Keep walking after single level desugaring.
4491 T = T.getSingleStepDesugaredType(Context);
4492 break;
4493 case Type::Typedef:
4494 T = cast<TypedefType>(Ty)->desugar();
4495 break;
4496 case Type::Decltype:
4497 T = cast<DecltypeType>(Ty)->desugar();
4498 break;
4499 case Type::PackIndexing:
4500 T = cast<PackIndexingType>(Ty)->desugar();
4501 break;
4502 case Type::Using:
4503 T = cast<UsingType>(Ty)->desugar();
4504 break;
4505 case Type::Auto:
4506 case Type::DeducedTemplateSpecialization:
4507 T = cast<DeducedType>(Ty)->getDeducedType();
4508 break;
4509 case Type::TypeOfExpr:
4510 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4511 break;
4512 case Type::Atomic:
4513 T = cast<AtomicType>(Ty)->getValueType();
4514 break;
4515 }
4516 } while (!T.isNull() && T->isVariablyModifiedType());
4517}
4518
4520 SourceLocation OpLoc,
4521 SourceRange ExprRange,
4522 UnaryExprOrTypeTrait ExprKind,
4523 StringRef KWName) {
4524 if (ExprType->isDependentType())
4525 return false;
4526
4527 // C++ [expr.sizeof]p2:
4528 // When applied to a reference or a reference type, the result
4529 // is the size of the referenced type.
4530 // C++11 [expr.alignof]p3:
4531 // When alignof is applied to a reference type, the result
4532 // shall be the alignment of the referenced type.
4533 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4534 ExprType = Ref->getPointeeType();
4535
4536 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4537 // When alignof or _Alignof is applied to an array type, the result
4538 // is the alignment of the element type.
4539 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4540 ExprKind == UETT_OpenMPRequiredSimdAlign) {
4541 // If the trait is 'alignof' in C before C2y, the ability to apply the
4542 // trait to an incomplete array is an extension.
4543 if (ExprKind == UETT_AlignOf && !getLangOpts().CPlusPlus &&
4544 ExprType->isIncompleteArrayType())
4545 Diag(OpLoc, getLangOpts().C2y
4546 ? diag::warn_c2y_compat_alignof_incomplete_array
4547 : diag::ext_c2y_alignof_incomplete_array);
4548 ExprType = Context.getBaseElementType(ExprType);
4549 }
4550
4551 if (ExprKind == UETT_VecStep)
4552 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4553
4554 if (ExprKind == UETT_VectorElements)
4555 return CheckVectorElementsTraitOperandType(*this, ExprType, OpLoc,
4556 ExprRange);
4557
4558 if (ExprKind == UETT_PtrAuthTypeDiscriminator)
4559 return checkPtrAuthTypeDiscriminatorOperandType(*this, ExprType, OpLoc,
4560 ExprRange);
4561
4562 // Explicitly list some types as extensions.
4563 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4564 ExprKind))
4565 return false;
4566
4568 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4569 KWName, ExprRange))
4570 return true;
4571
4572 if (ExprType->isFunctionType()) {
4573 Diag(OpLoc, diag::err_sizeof_alignof_function_type) << KWName << ExprRange;
4574 return true;
4575 }
4576
4577 // WebAssembly tables are always illegal operands to unary expressions and
4578 // type traits.
4579 if (Context.getTargetInfo().getTriple().isWasm() &&
4580 ExprType->isWebAssemblyTableType()) {
4581 Diag(OpLoc, diag::err_wasm_table_invalid_uett_operand)
4582 << getTraitSpelling(ExprKind);
4583 return true;
4584 }
4585
4586 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4587 ExprKind))
4588 return true;
4589
4590 if (ExprType->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4591 if (auto *TT = ExprType->getAs<TypedefType>()) {
4592 for (auto I = FunctionScopes.rbegin(),
4593 E = std::prev(FunctionScopes.rend());
4594 I != E; ++I) {
4595 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4596 if (CSI == nullptr)
4597 break;
4598 DeclContext *DC = nullptr;
4599 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4600 DC = LSI->CallOperator;
4601 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4602 DC = CRSI->TheCapturedDecl;
4603 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4604 DC = BSI->TheDecl;
4605 if (DC) {
4606 if (DC->containsDecl(TT->getDecl()))
4607 break;
4608 captureVariablyModifiedType(Context, ExprType, CSI);
4609 }
4610 }
4611 }
4612 }
4613
4614 return false;
4615}
4616
4618 SourceLocation OpLoc,
4619 UnaryExprOrTypeTrait ExprKind,
4620 SourceRange R) {
4621 if (!TInfo)
4622 return ExprError();
4623
4624 QualType T = TInfo->getType();
4625
4626 if (!T->isDependentType() &&
4627 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind,
4628 getTraitSpelling(ExprKind)))
4629 return ExprError();
4630
4631 // Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to
4632 // properly deal with VLAs in nested calls of sizeof and typeof.
4633 if (isUnevaluatedContext() && ExprKind == UETT_SizeOf &&
4634 TInfo->getType()->isVariablyModifiedType())
4635 TInfo = TransformToPotentiallyEvaluated(TInfo);
4636
4637 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4638 return new (Context) UnaryExprOrTypeTraitExpr(
4639 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4640}
4641
4644 UnaryExprOrTypeTrait ExprKind) {
4646 if (PE.isInvalid())
4647 return ExprError();
4648
4649 E = PE.get();
4650
4651 // Verify that the operand is valid.
4652 bool isInvalid = false;
4653 if (E->isTypeDependent()) {
4654 // Delay type-checking for type-dependent expressions.
4655 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4656 isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4657 } else if (ExprKind == UETT_VecStep) {
4659 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4660 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4661 isInvalid = true;
4662 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4663 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4664 isInvalid = true;
4665 } else if (ExprKind == UETT_VectorElements) {
4666 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_VectorElements);
4667 } else {
4669 }
4670
4671 if (isInvalid)
4672 return ExprError();
4673
4674 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4676 if (PE.isInvalid()) return ExprError();
4677 E = PE.get();
4678 }
4679
4680 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4681 return new (Context) UnaryExprOrTypeTraitExpr(
4682 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4683}
4684
4687 UnaryExprOrTypeTrait ExprKind, bool IsType,
4688 void *TyOrEx, SourceRange ArgRange) {
4689 // If error parsing type, ignore.
4690 if (!TyOrEx) return ExprError();
4691
4692 if (IsType) {
4693 TypeSourceInfo *TInfo;
4694 (void) GetTypeFromParser(