1//===--- CGExpr.cpp - Emit LLVM Code from 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 contains code to emit Expr nodes as LLVM code.
10//
11//===----------------------------------------------------------------------===//
12
13#include "ABIInfoImpl.h"
14#include "CGCUDARuntime.h"
15#include "CGCXXABI.h"
16#include "CGCall.h"
17#include "CGCleanup.h"
18#include "CGDebugInfo.h"
19#include "CGHLSLRuntime.h"
20#include "CGObjCRuntime.h"
21#include "CGOpenMPRuntime.h"
22#include "CGRecordLayout.h"
23#include "CodeGenFunction.h"
24#include "CodeGenModule.h"
25#include "CodeGenPGO.h"
26#include "ConstantEmitter.h"
27#include "TargetInfo.h"
28#include "clang/AST/ASTContext.h"
29#include "clang/AST/ASTLambda.h"
30#include "clang/AST/Attr.h"
31#include "clang/AST/DeclObjC.h"
32#include "clang/AST/Expr.h"
33#include "clang/AST/InferAlloc.h"
34#include "clang/AST/NSAPI.h"
35#include "clang/AST/ParentMapContext.h"
36#include "clang/AST/StmtVisitor.h"
37#include "clang/Basic/Builtins.h"
38#include "clang/Basic/CodeGenOptions.h"
39#include "clang/Basic/Module.h"
40#include "clang/Basic/SourceManager.h"
41#include "llvm/ADT/STLExtras.h"
42#include "llvm/ADT/ScopeExit.h"
43#include "llvm/ADT/StringExtras.h"
44#include "llvm/IR/Constants.h"
45#include "llvm/IR/DataLayout.h"
46#include "llvm/IR/Intrinsics.h"
47#include "llvm/IR/LLVMContext.h"
48#include "llvm/IR/MDBuilder.h"
49#include "llvm/IR/MatrixBuilder.h"
50#include "llvm/Support/ConvertUTF.h"
51#include "llvm/Support/Endian.h"
52#include "llvm/Support/MathExtras.h"
53#include "llvm/Support/Path.h"
54#include "llvm/Support/xxhash.h"
55#include "llvm/Transforms/Utils/SanitizerStats.h"
56
57#include <numeric>
58#include <optional>
59#include <string>
60
61using namespace clang;
62using namespace CodeGen;
63
64namespace clang {
65// TODO: consider deprecating ClSanitizeGuardChecks; functionality is subsumed
66// by -fsanitize-skip-hot-cutoff
67llvm::cl::opt<bool> ClSanitizeGuardChecks(
68 "ubsan-guard-checks", llvm::cl::Optional,
69 llvm::cl::desc("Guard UBSAN checks with `llvm.allow.ubsan.check()`."));
70
71} // namespace clang
72
73//===--------------------------------------------------------------------===//
74// Defines for metadata
75//===--------------------------------------------------------------------===//
76
77// Those values are crucial to be the SAME as in ubsan runtime library.
78enum VariableTypeDescriptorKind : uint16_t {
79 /// An integer type.
80 TK_Integer = 0x0000,
81 /// A floating-point type.
82 TK_Float = 0x0001,
83 /// An _BitInt(N) type.
84 TK_BitInt = 0x0002,
85 /// Any other type. The value representation is unspecified.
86 TK_Unknown = 0xffff
87};
88
89//===--------------------------------------------------------------------===//
90// Miscellaneous Helper Methods
91//===--------------------------------------------------------------------===//
92
93static llvm::StringRef GetUBSanTrapForHandler(SanitizerHandler ID) {
94 switch (ID) {
95#define SANITIZER_CHECK(Enum, Name, Version, Msg) \
96 case SanitizerHandler::Enum: \
97 return Msg;
98 LIST_SANITIZER_CHECKS
99#undef SANITIZER_CHECK
100 }
101 llvm_unreachable("unhandled switch case");
102}
103
104/// CreateTempAlloca - This creates a alloca and inserts it into the entry
105/// block.
106RawAddress
107CodeGenFunction::CreateTempAllocaWithoutCast(llvm::Type *Ty, CharUnits Align,
108 const Twine &Name,
109 llvm::Value *ArraySize) {
110 auto Alloca = CreateTempAlloca(Ty, Name, ArraySize);
111 Alloca->setAlignment(Align.getAsAlign());
112 return RawAddress(Alloca, Ty, Align, KnownNonNull);
113}
114
115RawAddress CodeGenFunction::MaybeCastStackAddressSpace(RawAddress Alloca,
116 LangAS DestLangAS,
117 llvm::Value *ArraySize) {
118
119 llvm::Value *V = Alloca.getPointer();
120 // Alloca always returns a pointer in alloca address space, which may
121 // be different from the type defined by the language. For example,
122 // in C++ the auto variables are in the default address space. Therefore
123 // cast alloca to the default address space when necessary.
124
125 unsigned DestAddrSpace = getContext().getTargetAddressSpace(AS: DestLangAS);
126 if (DestAddrSpace != Alloca.getAddressSpace()) {
127 llvm::IRBuilderBase::InsertPointGuard IPG(Builder);
128 // When ArraySize is nullptr, alloca is inserted at AllocaInsertPt,
129 // otherwise alloca is inserted at the current insertion point of the
130 // builder.
131 if (!ArraySize)
132 Builder.SetInsertPoint(getPostAllocaInsertPoint());
133 V = performAddrSpaceCast(Src: V, DestTy: Builder.getPtrTy(AddrSpace: DestAddrSpace));
134 }
135
136 return RawAddress(V, Alloca.getElementType(), Alloca.getAlignment(),
137 KnownNonNull);
138}
139
140RawAddress CodeGenFunction::CreateTempAlloca(llvm::Type *Ty, LangAS DestLangAS,
141 CharUnits Align, const Twine &Name,
142 llvm::Value *ArraySize,
143 RawAddress *AllocaAddr) {
144 RawAddress Alloca = CreateTempAllocaWithoutCast(Ty, Align, Name, ArraySize);
145 if (AllocaAddr)
146 *AllocaAddr = Alloca;
147 return MaybeCastStackAddressSpace(Alloca, DestLangAS, ArraySize);
148}
149
150/// CreateTempAlloca - This creates an alloca and inserts it into the entry
151/// block if \p ArraySize is nullptr, otherwise inserts it at the current
152/// insertion point of the builder.
153llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
154 const Twine &Name,
155 llvm::Value *ArraySize) {
156 llvm::AllocaInst *Alloca;
157 if (ArraySize)
158 Alloca = Builder.CreateAlloca(Ty, ArraySize, Name);
159 else
160 Alloca =
161 new llvm::AllocaInst(Ty, CGM.getDataLayout().getAllocaAddrSpace(),
162 ArraySize, Name, AllocaInsertPt->getIterator());
163 if (SanOpts.Mask & SanitizerKind::Address) {
164 Alloca->addAnnotationMetadata(Annotations: {"alloca_name_altered", Name.str()});
165 }
166 if (Allocas) {
167 Allocas->Add(I: Alloca);
168 }
169 return Alloca;
170}
171
172/// CreateDefaultAlignTempAlloca - This creates an alloca with the
173/// default alignment of the corresponding LLVM type, which is *not*
174/// guaranteed to be related in any way to the expected alignment of
175/// an AST type that might have been lowered to Ty.
176RawAddress CodeGenFunction::CreateDefaultAlignTempAlloca(llvm::Type *Ty,
177 const Twine &Name) {
178 CharUnits Align =
179 CharUnits::fromQuantity(Quantity: CGM.getDataLayout().getPrefTypeAlign(Ty));
180 return CreateTempAlloca(Ty, align: Align, Name);
181}
182
183RawAddress CodeGenFunction::CreateIRTempWithoutCast(QualType Ty,
184 const Twine &Name) {
185 CharUnits Align = getContext().getTypeAlignInChars(T: Ty);
186 return CreateTempAllocaWithoutCast(Ty: ConvertType(T: Ty), Align, Name, ArraySize: nullptr);
187}
188
189RawAddress CodeGenFunction::CreateMemTemp(QualType Ty, const Twine &Name,
190 RawAddress *Alloca) {
191 // FIXME: Should we prefer the preferred type alignment here?
192 return CreateMemTemp(T: Ty, Align: getContext().getTypeAlignInChars(T: Ty), Name, Alloca);
193}
194
195RawAddress CodeGenFunction::CreateMemTemp(QualType Ty, CharUnits Align,
196 const Twine &Name,
197 RawAddress *Alloca) {
198 RawAddress Result = CreateTempAlloca(Ty: ConvertTypeForMem(T: Ty), align: Align, Name,
199 /*ArraySize=*/nullptr, Alloca);
200
201 if (Ty->isConstantMatrixType()) {
202 auto *ArrayTy = cast<llvm::ArrayType>(Val: Result.getElementType());
203 auto *ArrayElementTy = ArrayTy->getElementType();
204 auto ArrayElements = ArrayTy->getNumElements();
205 if (getContext().getLangOpts().HLSL) {
206 auto *VectorTy = cast<llvm::FixedVectorType>(Val: ArrayElementTy);
207 ArrayElementTy = VectorTy->getElementType();
208 ArrayElements *= VectorTy->getNumElements();
209 }
210 auto *VectorTy = llvm::FixedVectorType::get(ElementType: ArrayElementTy, NumElts: ArrayElements);
211
212 Result = Address(Result.getPointer(), VectorTy, Result.getAlignment(),
213 KnownNonNull);
214 }
215 return Result;
216}
217
218RawAddress CodeGenFunction::CreateMemTempWithoutCast(QualType Ty,
219 CharUnits Align,
220 const Twine &Name) {
221 return CreateTempAllocaWithoutCast(Ty: ConvertTypeForMem(T: Ty), Align, Name);
222}
223
224RawAddress CodeGenFunction::CreateMemTempWithoutCast(QualType Ty,
225 const Twine &Name) {
226 return CreateMemTempWithoutCast(Ty, Align: getContext().getTypeAlignInChars(T: Ty),
227 Name);
228}
229
230/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
231/// expression and compare the result against zero, returning an Int1Ty value.
232llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
233 PGO->setCurrentStmt(E);
234 if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
235 llvm::Value *MemPtr = EmitScalarExpr(E);
236 return CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF&: *this, MemPtr, MPT);
237 }
238
239 QualType BoolTy = getContext().BoolTy;
240 SourceLocation Loc = E->getExprLoc();
241 CGFPOptionsRAII FPOptsRAII(*this, E);
242 if (!E->getType()->isAnyComplexType())
243 return EmitScalarConversion(Src: EmitScalarExpr(E), SrcTy: E->getType(), DstTy: BoolTy, Loc);
244
245 return EmitComplexToScalarConversion(Src: EmitComplexExpr(E), SrcTy: E->getType(), DstTy: BoolTy,
246 Loc);
247}
248
249/// EmitIgnoredExpr - Emit code to compute the specified expression,
250/// ignoring the result.
251void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
252 if (E->isPRValue())
253 return (void)EmitAnyExpr(E, aggSlot: AggValueSlot::ignored(), ignoreResult: true);
254
255 // if this is a bitfield-resulting conditional operator, we can special case
256 // emit this. The normal 'EmitLValue' version of this is particularly
257 // difficult to codegen for, since creating a single "LValue" for two
258 // different sized arguments here is not particularly doable.
259 if (const auto *CondOp = dyn_cast<AbstractConditionalOperator>(
260 Val: E->IgnoreParenNoopCasts(Ctx: getContext()))) {
261 if (CondOp->getObjectKind() == OK_BitField)
262 return EmitIgnoredConditionalOperator(E: CondOp);
263 }
264
265 // Just emit it as an l-value and drop the result.
266 EmitLValue(E);
267}
268
269/// EmitAnyExpr - Emit code to compute the specified expression which
270/// can have any type. The result is returned as an RValue struct.
271/// If this is an aggregate expression, AggSlot indicates where the
272/// result should be returned.
273RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
274 AggValueSlot aggSlot,
275 bool ignoreResult) {
276 switch (getEvaluationKind(T: E->getType())) {
277 case TEK_Scalar:
278 return RValue::get(V: EmitScalarExpr(E, IgnoreResultAssign: ignoreResult));
279 case TEK_Complex:
280 return RValue::getComplex(C: EmitComplexExpr(E, IgnoreReal: ignoreResult, IgnoreImag: ignoreResult));
281 case TEK_Aggregate:
282 if (!ignoreResult && aggSlot.isIgnored())
283 aggSlot = CreateAggTemp(T: E->getType(), Name: "agg-temp");
284 EmitAggExpr(E, AS: aggSlot);
285 return aggSlot.asRValue();
286 }
287 llvm_unreachable("bad evaluation kind");
288}
289
290/// EmitAnyExprToTemp - Similar to EmitAnyExpr(), however, the result will
291/// always be accessible even if no aggregate location is provided.
292RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
293 AggValueSlot AggSlot = AggValueSlot::ignored();
294
295 if (hasAggregateEvaluationKind(T: E->getType()))
296 AggSlot = CreateAggTemp(T: E->getType(), Name: "agg.tmp");
297 return EmitAnyExpr(E, aggSlot: AggSlot);
298}
299
300/// EmitAnyExprToMem - Evaluate an expression into a given memory
301/// location.
302void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
303 Address Location,
304 Qualifiers Quals,
305 bool IsInit) {
306 // FIXME: This function should take an LValue as an argument.
307 switch (getEvaluationKind(T: E->getType())) {
308 case TEK_Complex:
309 EmitComplexExprIntoLValue(E, dest: MakeAddrLValue(Addr: Location, T: E->getType()),
310 /*isInit*/ false);
311 return;
312
313 case TEK_Aggregate: {
314 EmitAggExpr(E, AS: AggValueSlot::forAddr(addr: Location, quals: Quals,
315 isDestructed: AggValueSlot::IsDestructed_t(IsInit),
316 needsGC: AggValueSlot::DoesNotNeedGCBarriers,
317 isAliased: AggValueSlot::IsAliased_t(!IsInit),
318 mayOverlap: AggValueSlot::MayOverlap));
319 return;
320 }
321
322 case TEK_Scalar: {
323 RValue RV = RValue::get(V: EmitScalarExpr(E, /*Ignore*/ IgnoreResultAssign: false));
324 LValue LV = MakeAddrLValue(Addr: Location, T: E->getType());
325 EmitStoreThroughLValue(Src: RV, Dst: LV);
326 return;
327 }
328 }
329 llvm_unreachable("bad evaluation kind");
330}
331
332void CodeGenFunction::EmitInitializationToLValue(
333 const Expr *E, LValue LV, AggValueSlot::IsZeroed_t IsZeroed) {
334 QualType Type = LV.getType();
335 switch (getEvaluationKind(T: Type)) {
336 case TEK_Complex:
337 EmitComplexExprIntoLValue(E, dest: LV, /*isInit*/ true);
338 return;
339 case TEK_Aggregate:
340 EmitAggExpr(E, AS: AggValueSlot::forLValue(LV, isDestructed: AggValueSlot::IsDestructed,
341 needsGC: AggValueSlot::DoesNotNeedGCBarriers,
342 isAliased: AggValueSlot::IsNotAliased,
343 mayOverlap: AggValueSlot::MayOverlap, isZeroed: IsZeroed));
344 return;
345 case TEK_Scalar:
346 if (LV.isSimple())
347 EmitScalarInit(init: E, /*D=*/nullptr, lvalue: LV, /*Captured=*/capturedByInit: false);
348 else
349 EmitStoreThroughLValue(Src: RValue::get(V: EmitScalarExpr(E)), Dst: LV);
350 return;
351 }
352 llvm_unreachable("bad evaluation kind");
353}
354
355static void
356pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M,
357 const Expr *E, Address ReferenceTemporary) {
358 // Objective-C++ ARC:
359 // If we are binding a reference to a temporary that has ownership, we
360 // need to perform retain/release operations on the temporary.
361 //
362 // FIXME: This should be looking at E, not M.
363 if (auto Lifetime = M->getType().getObjCLifetime()) {
364 switch (Lifetime) {
365 case Qualifiers::OCL_None:
366 case Qualifiers::OCL_ExplicitNone:
367 // Carry on to normal cleanup handling.
368 break;
369
370 case Qualifiers::OCL_Autoreleasing:
371 // Nothing to do; cleaned up by an autorelease pool.
372 return;
373
374 case Qualifiers::OCL_Strong:
375 case Qualifiers::OCL_Weak:
376 switch (StorageDuration Duration = M->getStorageDuration()) {
377 case SD_Static:
378 // Note: we intentionally do not register a cleanup to release
379 // the object on program termination.
380 return;
381
382 case SD_Thread:
383 // FIXME: We should probably register a cleanup in this case.
384 return;
385
386 case SD_Automatic:
387 case SD_FullExpression:
388 CodeGenFunction::Destroyer *Destroy;
389 CleanupKind CleanupKind;
390 if (Lifetime == Qualifiers::OCL_Strong) {
391 const ValueDecl *VD = M->getExtendingDecl();
392 bool Precise = isa_and_nonnull<VarDecl>(Val: VD) &&
393 VD->hasAttr<ObjCPreciseLifetimeAttr>();
394 CleanupKind = CGF.getARCCleanupKind();
395 Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise
396 : &CodeGenFunction::destroyARCStrongImprecise;
397 } else {
398 // __weak objects always get EH cleanups; otherwise, exceptions
399 // could cause really nasty crashes instead of mere leaks.
400 CleanupKind = NormalAndEHCleanup;
401 Destroy = &CodeGenFunction::destroyARCWeak;
402 }
403 if (Duration == SD_FullExpression)
404 CGF.pushDestroy(kind: CleanupKind, addr: ReferenceTemporary,
405 type: M->getType(), destroyer: *Destroy,
406 useEHCleanupForArray: CleanupKind & EHCleanup);
407 else
408 CGF.pushLifetimeExtendedDestroy(kind: CleanupKind, addr: ReferenceTemporary,
409 type: M->getType(),
410 destroyer: *Destroy, useEHCleanupForArray: CleanupKind & EHCleanup);
411 return;
412
413 case SD_Dynamic:
414 llvm_unreachable("temporary cannot have dynamic storage duration");
415 }
416 llvm_unreachable("unknown storage duration");
417 }
418 }
419
420 QualType::DestructionKind DK = E->getType().isDestructedType();
421 if (DK != QualType::DK_none) {
422 switch (M->getStorageDuration()) {
423 case SD_Static:
424 case SD_Thread: {
425 CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
426 if (const auto *ClassDecl =
427 E->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
428 ClassDecl && !ClassDecl->hasTrivialDestructor())
429 // Get the destructor for the reference temporary.
430 ReferenceTemporaryDtor = ClassDecl->getDestructor();
431
432 if (!ReferenceTemporaryDtor)
433 return;
434
435 llvm::FunctionCallee CleanupFn;
436 llvm::Constant *CleanupArg;
437 if (E->getType()->isArrayType()) {
438 CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper(
439 addr: ReferenceTemporary, type: E->getType(), destroyer: CodeGenFunction::destroyCXXObject,
440 useEHCleanupForArray: CGF.getLangOpts().Exceptions,
441 VD: dyn_cast_or_null<VarDecl>(Val: M->getExtendingDecl()));
442 CleanupArg = llvm::Constant::getNullValue(Ty: CGF.Int8PtrTy);
443 } else {
444 CleanupFn = CGF.CGM.getAddrAndTypeOfCXXStructor(
445 GD: GlobalDecl(ReferenceTemporaryDtor, Dtor_Complete));
446 CleanupArg =
447 cast<llvm::Constant>(Val: ReferenceTemporary.emitRawPointer(CGF));
448 }
449 CGF.CGM.getCXXABI().registerGlobalDtor(
450 CGF, D: *cast<VarDecl>(Val: M->getExtendingDecl()), Dtor: CleanupFn, Addr: CleanupArg);
451 } break;
452 case SD_FullExpression:
453 CGF.pushDestroy(dtorKind: DK, addr: ReferenceTemporary, type: E->getType());
454 break;
455 case SD_Automatic:
456 CGF.pushLifetimeExtendedDestroy(dtorKind: DK, addr: ReferenceTemporary, type: E->getType());
457 break;
458 case SD_Dynamic:
459 llvm_unreachable("temporary cannot have dynamic storage duration");
460 }
461 }
462}
463
464static RawAddress createReferenceTemporary(CodeGenFunction &CGF,
465 const MaterializeTemporaryExpr *M,
466 const Expr *Inner,
467 RawAddress *Alloca = nullptr) {
468 switch (M->getStorageDuration()) {
469 case SD_FullExpression:
470 case SD_Automatic: {
471 // If we have a constant temporary array or record try to promote it into a
472 // constant global under the same rules a normal constant would've been
473 // promoted. This is easier on the optimizer and generally emits fewer
474 // instructions.
475 QualType Ty = Inner->getType();
476 if (CGF.CGM.getCodeGenOpts().MergeAllConstants &&
477 (Ty->isArrayType() || Ty->isRecordType()) &&
478 Ty.isConstantStorage(Ctx: CGF.getContext(), ExcludeCtor: true, ExcludeDtor: false))
479 if (auto Init = ConstantEmitter(CGF).tryEmitAbstract(E: Inner, T: Ty)) {
480 auto AS = CGF.CGM.GetGlobalConstantAddressSpace();
481 auto *GV = new llvm::GlobalVariable(
482 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
483 llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp", nullptr,
484 llvm::GlobalValue::NotThreadLocal,
485 CGF.getContext().getTargetAddressSpace(AS));
486 CharUnits alignment = CGF.getContext().getTypeAlignInChars(T: Ty);
487 GV->setAlignment(alignment.getAsAlign());
488 llvm::Constant *C = GV;
489 if (AS != LangAS::Default)
490 C = CGF.CGM.performAddrSpaceCast(
491 Src: GV, DestTy: llvm::PointerType::get(
492 C&: CGF.getLLVMContext(),
493 AddressSpace: CGF.getContext().getTargetAddressSpace(AS: LangAS::Default)));
494 // FIXME: Should we put the new global into a COMDAT?
495 return RawAddress(C, GV->getValueType(), alignment);
496 }
497 return CGF.CreateMemTemp(Ty, Name: "ref.tmp", Alloca);
498 }
499 case SD_Thread:
500 case SD_Static:
501 return CGF.CGM.GetAddrOfGlobalTemporary(E: M, Inner);
502
503 case SD_Dynamic:
504 llvm_unreachable("temporary can't have dynamic storage duration");
505 }
506 llvm_unreachable("unknown storage duration");
507}
508
509/// Helper method to check if the underlying ABI is AAPCS
510static bool isAAPCS(const TargetInfo &TargetInfo) {
511 return TargetInfo.getABI().starts_with(Prefix: "aapcs");
512}
513
514LValue CodeGenFunction::
515EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *M) {
516 const Expr *E = M->getSubExpr();
517
518 assert((!M->getExtendingDecl() || !isa<VarDecl>(M->getExtendingDecl()) ||
519 !cast<VarDecl>(M->getExtendingDecl())->isARCPseudoStrong()) &&
520 "Reference should never be pseudo-strong!");
521
522 // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
523 // as that will cause the lifetime adjustment to be lost for ARC
524 auto ownership = M->getType().getObjCLifetime();
525 if (ownership != Qualifiers::OCL_None &&
526 ownership != Qualifiers::OCL_ExplicitNone) {
527 RawAddress Object = createReferenceTemporary(CGF&: *this, M, Inner: E);
528 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Val: Object.getPointer())) {
529 llvm::Type *Ty = ConvertTypeForMem(T: E->getType());
530 Object = Object.withElementType(ElemTy: Ty);
531
532 // createReferenceTemporary will promote the temporary to a global with a
533 // constant initializer if it can. It can only do this to a value of
534 // ARC-manageable type if the value is global and therefore "immune" to
535 // ref-counting operations. Therefore we have no need to emit either a
536 // dynamic initialization or a cleanup and we can just return the address
537 // of the temporary.
538 if (Var->hasInitializer())
539 return MakeAddrLValue(Addr: Object, T: M->getType(), Source: AlignmentSource::Decl);
540
541 Var->setInitializer(CGM.EmitNullConstant(T: E->getType()));
542 }
543 LValue RefTempDst = MakeAddrLValue(Addr: Object, T: M->getType(),
544 Source: AlignmentSource::Decl);
545
546 switch (getEvaluationKind(T: E->getType())) {
547 default: llvm_unreachable("expected scalar or aggregate expression");
548 case TEK_Scalar:
549 EmitScalarInit(init: E, D: M->getExtendingDecl(), lvalue: RefTempDst, capturedByInit: false);
550 break;
551 case TEK_Aggregate: {
552 EmitAggExpr(E, AS: AggValueSlot::forAddr(addr: Object,
553 quals: E->getType().getQualifiers(),
554 isDestructed: AggValueSlot::IsDestructed,
555 needsGC: AggValueSlot::DoesNotNeedGCBarriers,
556 isAliased: AggValueSlot::IsNotAliased,
557 mayOverlap: AggValueSlot::DoesNotOverlap));
558 break;
559 }
560 }
561
562 pushTemporaryCleanup(CGF&: *this, M, E, ReferenceTemporary: Object);
563 return RefTempDst;
564 }
565
566 SmallVector<const Expr *, 2> CommaLHSs;
567 SmallVector<SubobjectAdjustment, 2> Adjustments;
568 E = E->skipRValueSubobjectAdjustments(CommaLHS&: CommaLHSs, Adjustments);
569
570 for (const auto &Ignored : CommaLHSs)
571 EmitIgnoredExpr(E: Ignored);
572
573 if (const auto *opaque = dyn_cast<OpaqueValueExpr>(Val: E)) {
574 if (opaque->getType()->isRecordType()) {
575 assert(Adjustments.empty());
576 return EmitOpaqueValueLValue(e: opaque);
577 }
578 }
579
580 // Create and initialize the reference temporary.
581 RawAddress Alloca = Address::invalid();
582 RawAddress Object = createReferenceTemporary(CGF&: *this, M, Inner: E, Alloca: &Alloca);
583 if (auto *Var = dyn_cast<llvm::GlobalVariable>(
584 Val: Object.getPointer()->stripPointerCasts())) {
585 llvm::Type *TemporaryType = ConvertTypeForMem(T: E->getType());
586 Object = Object.withElementType(ElemTy: TemporaryType);
587 // If the temporary is a global and has a constant initializer or is a
588 // constant temporary that we promoted to a global, we may have already
589 // initialized it.
590 if (!Var->hasInitializer()) {
591 Var->setInitializer(CGM.EmitNullConstant(T: E->getType()));
592 QualType RefType = M->getType().withoutLocalFastQualifiers();
593 if (RefType.getPointerAuth()) {
594 // Use the qualifier of the reference temporary to sign the pointer.
595 LValue LV = MakeRawAddrLValue(V: Object.getPointer(), T: RefType,
596 Alignment: Object.getAlignment());
597 EmitScalarInit(init: E, D: M->getExtendingDecl(), lvalue: LV, capturedByInit: false);
598 } else {
599 EmitAnyExprToMem(E, Location: Object, Quals: Qualifiers(), /*IsInit*/ true);
600 }
601 }
602 } else {
603 switch (M->getStorageDuration()) {
604 case SD_Automatic:
605 if (EmitLifetimeStart(Addr: Alloca.getPointer())) {
606 pushCleanupAfterFullExpr<CallLifetimeEnd>(Kind: NormalEHLifetimeMarker,
607 A: Alloca);
608 }
609 break;
610
611 case SD_FullExpression: {
612 if (!ShouldEmitLifetimeMarkers)
613 break;
614
615 // Avoid creating a conditional cleanup just to hold an llvm.lifetime.end
616 // marker. Instead, start the lifetime of a conditional temporary earlier
617 // so that it's unconditional. Don't do this with sanitizers which need
618 // more precise lifetime marks. However when inside an "await.suspend"
619 // block, we should always avoid conditional cleanup because it creates
620 // boolean marker that lives across await_suspend, which can destroy coro
621 // frame.
622 ConditionalEvaluation *OldConditional = nullptr;
623 CGBuilderTy::InsertPoint OldIP;
624 if (isInConditionalBranch() && !E->getType().isDestructedType() &&
625 ((!SanOpts.has(K: SanitizerKind::HWAddress) &&
626 !SanOpts.has(K: SanitizerKind::Memory) &&
627 !SanOpts.has(K: SanitizerKind::MemtagStack) &&
628 !CGM.getCodeGenOpts().SanitizeAddressUseAfterScope) ||
629 inSuspendBlock())) {
630 OldConditional = OutermostConditional;
631 OutermostConditional = nullptr;
632
633 OldIP = Builder.saveIP();
634 llvm::BasicBlock *Block = OldConditional->getStartingBlock();
635 Builder.restoreIP(IP: CGBuilderTy::InsertPoint(
636 Block, llvm::BasicBlock::iterator(Block->back())));
637 }
638
639 if (EmitLifetimeStart(Addr: Alloca.getPointer())) {
640 pushFullExprCleanup<CallLifetimeEnd>(kind: NormalEHLifetimeMarker, A: Alloca);
641 }
642
643 if (OldConditional) {
644 OutermostConditional = OldConditional;
645 Builder.restoreIP(IP: OldIP);
646 }
647 break;
648 }
649
650 default:
651 break;
652 }
653 EmitAnyExprToMem(E, Location: Object, Quals: Qualifiers(), /*IsInit*/true);
654 }
655 pushTemporaryCleanup(CGF&: *this, M, E, ReferenceTemporary: Object);
656
657 // Perform derived-to-base casts and/or field accesses, to get from the
658 // temporary object we created (and, potentially, for which we extended
659 // the lifetime) to the subobject we're binding the reference to.
660 for (SubobjectAdjustment &Adjustment : llvm::reverse(C&: Adjustments)) {
661 switch (Adjustment.Kind) {
662 case SubobjectAdjustment::DerivedToBaseAdjustment:
663 Object =
664 GetAddressOfBaseClass(Value: Object, Derived: Adjustment.DerivedToBase.DerivedClass,
665 PathBegin: Adjustment.DerivedToBase.BasePath->path_begin(),
666 PathEnd: Adjustment.DerivedToBase.BasePath->path_end(),
667 /*NullCheckValue=*/ false, Loc: E->getExprLoc());
668 break;
669
670 case SubobjectAdjustment::FieldAdjustment: {
671 LValue LV = MakeAddrLValue(Addr: Object, T: E->getType(), Source: AlignmentSource::Decl);
672 LV = EmitLValueForField(Base: LV, Field: Adjustment.Field);
673 assert(LV.isSimple() &&
674 "materialized temporary field is not a simple lvalue");
675 Object = LV.getAddress();
676 break;
677 }
678
679 case SubobjectAdjustment::MemberPointerAdjustment: {
680 llvm::Value *Ptr = EmitScalarExpr(E: Adjustment.Ptr.RHS);
681 Object = EmitCXXMemberDataPointerAddress(
682 E, base: Object, memberPtr: Ptr, memberPtrType: Adjustment.Ptr.MPT, /*IsInBounds=*/true);
683 break;
684 }
685 }
686 }
687
688 return MakeAddrLValue(Addr: Object, T: M->getType(), Source: AlignmentSource::Decl);
689}
690
691RValue
692CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) {
693 // Emit the expression as an lvalue.
694 LValue LV = EmitLValue(E);
695 assert(LV.isSimple());
696 llvm::Value *Value = LV.getPointer(CGF&: *this);
697
698 if (sanitizePerformTypeCheck() && !E->getType()->isFunctionType()) {
699 // C++11 [dcl.ref]p5 (as amended by core issue 453):
700 // If a glvalue to which a reference is directly bound designates neither
701 // an existing object or function of an appropriate type nor a region of
702 // storage of suitable size and alignment to contain an object of the
703 // reference's type, the behavior is undefined.
704 QualType Ty = E->getType();
705 EmitTypeCheck(TCK: TCK_ReferenceBinding, Loc: E->getExprLoc(), V: Value, Type: Ty);
706 }
707
708 return RValue::get(V: Value);
709}
710
711
712/// getAccessedFieldNo - Given an encoded value and a result number, return the
713/// input field number being accessed.
714unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
715 const llvm::Constant *Elts) {
716 return cast<llvm::ConstantInt>(Val: Elts->getAggregateElement(Elt: Idx))
717 ->getZExtValue();
718}
719
720static llvm::Value *emitHashMix(CGBuilderTy &Builder, llvm::Value *Acc,
721 llvm::Value *Ptr) {
722 llvm::Value *A0 =
723 Builder.CreateMul(LHS: Ptr, RHS: Builder.getInt64(C: 0xbf58476d1ce4e5b9u));
724 llvm::Value *A1 =
725 Builder.CreateXor(LHS: A0, RHS: Builder.CreateLShr(LHS: A0, RHS: Builder.getInt64(C: 31)));
726 return Builder.CreateXor(LHS: Acc, RHS: A1);
727}
728
729bool CodeGenFunction::isNullPointerAllowed(TypeCheckKind TCK) {
730 return TCK == TCK_DowncastPointer || TCK == TCK_Upcast ||
731 TCK == TCK_UpcastToVirtualBase || TCK == TCK_DynamicOperation;
732}
733
734bool CodeGenFunction::isVptrCheckRequired(TypeCheckKind TCK, QualType Ty) {
735 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
736 return (RD && RD->hasDefinition() && RD->isDynamicClass()) &&
737 (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
738 TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
739 TCK == TCK_UpcastToVirtualBase || TCK == TCK_DynamicOperation);
740}
741
742bool CodeGenFunction::sanitizePerformTypeCheck() const {
743 return SanOpts.has(K: SanitizerKind::Null) ||
744 SanOpts.has(K: SanitizerKind::Alignment) ||
745 SanOpts.has(K: SanitizerKind::ObjectSize) ||
746 SanOpts.has(K: SanitizerKind::Vptr);
747}
748
749void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
750 llvm::Value *Ptr, QualType Ty,
751 CharUnits Alignment,
752 SanitizerSet SkippedChecks,
753 llvm::Value *ArraySize) {
754 if (!sanitizePerformTypeCheck())
755 return;
756
757 // Don't check pointers outside the default address space. The null check
758 // isn't correct, the object-size check isn't supported by LLVM, and we can't
759 // communicate the addresses to the runtime handler for the vptr check.
760 if (Ptr->getType()->getPointerAddressSpace())
761 return;
762
763 // Don't check pointers to volatile data. The behavior here is implementation-
764 // defined.
765 if (Ty.isVolatileQualified())
766 return;
767
768 // Quickly determine whether we have a pointer to an alloca. It's possible
769 // to skip null checks, and some alignment checks, for these pointers. This
770 // can reduce compile-time significantly.
771 auto PtrToAlloca = dyn_cast<llvm::AllocaInst>(Val: Ptr->stripPointerCasts());
772
773 llvm::Value *IsNonNull = nullptr;
774 bool IsGuaranteedNonNull =
775 SkippedChecks.has(K: SanitizerKind::Null) || PtrToAlloca;
776
777 llvm::BasicBlock *Done = nullptr;
778 bool DoneViaNullSanitize = false;
779
780 {
781 auto CheckHandler = SanitizerHandler::TypeMismatch;
782 SanitizerDebugLocation SanScope(this,
783 {SanitizerKind::SO_Null,
784 SanitizerKind::SO_ObjectSize,
785 SanitizerKind::SO_Alignment},
786 CheckHandler);
787
788 SmallVector<std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>, 3>
789 Checks;
790
791 llvm::Value *True = llvm::ConstantInt::getTrue(Context&: getLLVMContext());
792 bool AllowNullPointers = isNullPointerAllowed(TCK);
793 if ((SanOpts.has(K: SanitizerKind::Null) || AllowNullPointers) &&
794 !IsGuaranteedNonNull) {
795 // The glvalue must not be an empty glvalue.
796 IsNonNull = Builder.CreateIsNotNull(Arg: Ptr);
797
798 // The IR builder can constant-fold the null check if the pointer points
799 // to a constant.
800 IsGuaranteedNonNull = IsNonNull == True;
801
802 // Skip the null check if the pointer is known to be non-null.
803 if (!IsGuaranteedNonNull) {
804 if (AllowNullPointers) {
805 // When performing pointer casts, it's OK if the value is null.
806 // Skip the remaining checks in that case.
807 Done = createBasicBlock(name: "null");
808 DoneViaNullSanitize = true;
809 llvm::BasicBlock *Rest = createBasicBlock(name: "not.null");
810 Builder.CreateCondBr(Cond: IsNonNull, True: Rest, False: Done);
811 EmitBlock(BB: Rest);
812 } else {
813 Checks.push_back(Elt: std::make_pair(x&: IsNonNull, y: SanitizerKind::SO_Null));
814 }
815 }
816 }
817
818 if (SanOpts.has(K: SanitizerKind::ObjectSize) &&
819 !SkippedChecks.has(K: SanitizerKind::ObjectSize) &&
820 !Ty->isIncompleteType()) {
821 uint64_t TySize = CGM.getMinimumObjectSize(Ty).getQuantity();
822 llvm::Value *Size = llvm::ConstantInt::get(Ty: IntPtrTy, V: TySize);
823 if (ArraySize)
824 Size = Builder.CreateMul(LHS: Size, RHS: ArraySize);
825
826 // Degenerate case: new X[0] does not need an objectsize check.
827 llvm::Constant *ConstantSize = dyn_cast<llvm::Constant>(Val: Size);
828 if (!ConstantSize || !ConstantSize->isNullValue()) {
829 // The glvalue must refer to a large enough storage region.
830 // FIXME: If Address Sanitizer is enabled, insert dynamic
831 // instrumentation
832 // to check this.
833 // FIXME: Get object address space
834 llvm::Type *Tys[2] = {IntPtrTy, Int8PtrTy};
835 llvm::Function *F = CGM.getIntrinsic(IID: llvm::Intrinsic::objectsize, Tys);
836 llvm::Value *Min = Builder.getFalse();
837 llvm::Value *NullIsUnknown = Builder.getFalse();
838 llvm::Value *Dynamic = Builder.getFalse();
839 llvm::Value *LargeEnough = Builder.CreateICmpUGE(
840 LHS: Builder.CreateCall(Callee: F, Args: {Ptr, Min, NullIsUnknown, Dynamic}), RHS: Size);
841 Checks.push_back(
842 Elt: std::make_pair(x&: LargeEnough, y: SanitizerKind::SO_ObjectSize));
843 }
844 }
845
846 llvm::MaybeAlign AlignVal;
847 llvm::Value *PtrAsInt = nullptr;
848
849 if (SanOpts.has(K: SanitizerKind::Alignment) &&
850 !SkippedChecks.has(K: SanitizerKind::Alignment)) {
851 AlignVal = Alignment.getAsMaybeAlign();
852 if (!Ty->isIncompleteType() && !AlignVal)
853 AlignVal = CGM.getNaturalTypeAlignment(T: Ty, BaseInfo: nullptr, TBAAInfo: nullptr,
854 /*ForPointeeType=*/forPointeeType: true)
855 .getAsMaybeAlign();
856
857 // The glvalue must be suitably aligned.
858 if (AlignVal && *AlignVal > llvm::Align(1) &&
859 (!PtrToAlloca || PtrToAlloca->getAlign() < *AlignVal)) {
860 PtrAsInt = Builder.CreatePtrToInt(V: Ptr, DestTy: IntPtrTy);
861 llvm::Value *Align = Builder.CreateAnd(
862 LHS: PtrAsInt, RHS: llvm::ConstantInt::get(Ty: IntPtrTy, V: AlignVal->value() - 1));
863 llvm::Value *Aligned =
864 Builder.CreateICmpEQ(LHS: Align, RHS: llvm::ConstantInt::get(Ty: IntPtrTy, V: 0));
865 if (Aligned != True)
866 Checks.push_back(
867 Elt: std::make_pair(x&: Aligned, y: SanitizerKind::SO_Alignment));
868 }
869 }
870
871 if (Checks.size() > 0) {
872 llvm::Constant *StaticData[] = {
873 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(T: Ty),
874 llvm::ConstantInt::get(Ty: Int8Ty, V: AlignVal ? llvm::Log2(A: *AlignVal) : 1),
875 llvm::ConstantInt::get(Ty: Int8Ty, V: TCK)};
876 EmitCheck(Checked: Checks, Check: CheckHandler, StaticArgs: StaticData, DynamicArgs: PtrAsInt ? PtrAsInt : Ptr);
877 }
878 }
879
880 // If possible, check that the vptr indicates that there is a subobject of
881 // type Ty at offset zero within this object.
882 //
883 // C++11 [basic.life]p5,6:
884 // [For storage which does not refer to an object within its lifetime]
885 // The program has undefined behavior if:
886 // -- the [pointer or glvalue] is used to access a non-static data member
887 // or call a non-static member function
888 if (SanOpts.has(K: SanitizerKind::Vptr) &&
889 !SkippedChecks.has(K: SanitizerKind::Vptr) && isVptrCheckRequired(TCK, Ty)) {
890 SanitizerDebugLocation SanScope(this, {SanitizerKind::SO_Vptr},
891 SanitizerHandler::DynamicTypeCacheMiss);
892
893 // Ensure that the pointer is non-null before loading it. If there is no
894 // compile-time guarantee, reuse the run-time null check or emit a new one.
895 if (!IsGuaranteedNonNull) {
896 if (!IsNonNull)
897 IsNonNull = Builder.CreateIsNotNull(Arg: Ptr);
898 if (!Done)
899 Done = createBasicBlock(name: "vptr.null");
900 llvm::BasicBlock *VptrNotNull = createBasicBlock(name: "vptr.not.null");
901 Builder.CreateCondBr(Cond: IsNonNull, True: VptrNotNull, False: Done);
902 EmitBlock(BB: VptrNotNull);
903 }
904
905 // Compute a deterministic hash of the mangled name of the type.
906 SmallString<64> MangledName;
907 llvm::raw_svector_ostream Out(MangledName);
908 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(T: Ty.getUnqualifiedType(),
909 Out);
910
911 // Contained in NoSanitizeList based on the mangled type.
912 if (!CGM.getContext().getNoSanitizeList().containsType(Mask: SanitizerKind::Vptr,
913 MangledTypeName: Out.str())) {
914 // Load the vptr, and mix it with TypeHash.
915 llvm::Value *TypeHash =
916 llvm::ConstantInt::get(Ty: Int64Ty, V: xxh3_64bits(data: Out.str()));
917
918 llvm::Type *VPtrTy = llvm::PointerType::get(C&: getLLVMContext(), AddressSpace: 0);
919 Address VPtrAddr(Ptr, IntPtrTy, getPointerAlign());
920 llvm::Value *VPtrVal = GetVTablePtr(This: VPtrAddr, VTableTy: VPtrTy,
921 VTableClass: Ty->getAsCXXRecordDecl(),
922 AuthMode: VTableAuthMode::UnsafeUbsanStrip);
923 VPtrVal = Builder.CreateBitOrPointerCast(V: VPtrVal, DestTy: IntPtrTy);
924
925 llvm::Value *Hash =
926 emitHashMix(Builder, Acc: TypeHash, Ptr: Builder.CreateZExt(V: VPtrVal, DestTy: Int64Ty));
927 Hash = Builder.CreateTrunc(V: Hash, DestTy: IntPtrTy);
928
929 // Look the hash up in our cache.
930 const int CacheSize = 128;
931 llvm::Type *HashTable = llvm::ArrayType::get(ElementType: IntPtrTy, NumElements: CacheSize);
932 llvm::Value *Cache = CGM.CreateRuntimeVariable(Ty: HashTable,
933 Name: "__ubsan_vptr_type_cache");
934 llvm::Value *Slot = Builder.CreateAnd(LHS: Hash,
935 RHS: llvm::ConstantInt::get(Ty: IntPtrTy,
936 V: CacheSize-1));
937 llvm::Value *Indices[] = { Builder.getInt32(C: 0), Slot };
938 llvm::Value *CacheVal = Builder.CreateAlignedLoad(
939 Ty: IntPtrTy, Addr: Builder.CreateInBoundsGEP(Ty: HashTable, Ptr: Cache, IdxList: Indices),
940 Align: getPointerAlign());
941
942 // If the hash isn't in the cache, call a runtime handler to perform the
943 // hard work of checking whether the vptr is for an object of the right
944 // type. This will either fill in the cache and return, or produce a
945 // diagnostic.
946 llvm::Value *EqualHash = Builder.CreateICmpEQ(LHS: CacheVal, RHS: Hash);
947 llvm::Constant *StaticData[] = {
948 EmitCheckSourceLocation(Loc),
949 EmitCheckTypeDescriptor(T: Ty),
950 CGM.GetAddrOfRTTIDescriptor(Ty: Ty.getUnqualifiedType()),
951 llvm::ConstantInt::get(Ty: Int8Ty, V: TCK)
952 };
953 llvm::Value *DynamicData[] = { Ptr, Hash };
954 EmitCheck(Checked: std::make_pair(x&: EqualHash, y: SanitizerKind::SO_Vptr),
955 Check: SanitizerHandler::DynamicTypeCacheMiss, StaticArgs: StaticData,
956 DynamicArgs: DynamicData);
957 }
958 }
959
960 if (Done) {
961 SanitizerDebugLocation SanScope(
962 this,
963 {DoneViaNullSanitize ? SanitizerKind::SO_Null : SanitizerKind::SO_Vptr},
964 DoneViaNullSanitize ? SanitizerHandler::TypeMismatch
965 : SanitizerHandler::DynamicTypeCacheMiss);
966 Builder.CreateBr(Dest: Done);
967 EmitBlock(BB: Done);
968 }
969}
970
971llvm::Value *CodeGenFunction::LoadPassedObjectSize(const Expr *E,
972 QualType EltTy) {
973 ASTContext &C = getContext();
974 uint64_t EltSize = C.getTypeSizeInChars(T: EltTy).getQuantity();
975 if (!EltSize)
976 return nullptr;
977
978 auto *ArrayDeclRef = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenImpCasts());
979 if (!ArrayDeclRef)
980 return nullptr;
981
982 auto *ParamDecl = dyn_cast<ParmVarDecl>(Val: ArrayDeclRef->getDecl());
983 if (!ParamDecl)
984 return nullptr;
985
986 auto *POSAttr = ParamDecl->getAttr<PassObjectSizeAttr>();
987 if (!POSAttr)
988 return nullptr;
989
990 // Don't load the size if it's a lower bound.
991 int POSType = POSAttr->getType();
992 if (POSType != 0 && POSType != 1)
993 return nullptr;
994
995 // Find the implicit size parameter.
996 auto PassedSizeIt = SizeArguments.find(Val: ParamDecl);
997 if (PassedSizeIt == SizeArguments.end())
998 return nullptr;
999
1000 const ImplicitParamDecl *PassedSizeDecl = PassedSizeIt->second;
1001 assert(LocalDeclMap.count(PassedSizeDecl) && "Passed size not loadable");
1002 Address AddrOfSize = LocalDeclMap.find(Val: PassedSizeDecl)->second;
1003 llvm::Value *SizeInBytes = EmitLoadOfScalar(Addr: AddrOfSize, /*Volatile=*/false,
1004 Ty: C.getSizeType(), Loc: E->getExprLoc());
1005 llvm::Value *SizeOfElement =
1006 llvm::ConstantInt::get(Ty: SizeInBytes->getType(), V: EltSize);
1007 return Builder.CreateUDiv(LHS: SizeInBytes, RHS: SizeOfElement);
1008}
1009
1010/// If Base is known to point to the start of an array, return the length of
1011/// that array. Return 0 if the length cannot be determined.
1012static llvm::Value *getArrayIndexingBound(CodeGenFunction &CGF,
1013 const Expr *Base,
1014 QualType &IndexedType,
1015 LangOptions::StrictFlexArraysLevelKind
1016 StrictFlexArraysLevel) {
1017 // For the vector indexing extension, the bound is the number of elements.
1018 if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
1019 IndexedType = Base->getType();
1020 return CGF.Builder.getInt32(C: VT->getNumElements());
1021 }
1022
1023 Base = Base->IgnoreParens();
1024
1025 if (const auto *CE = dyn_cast<CastExpr>(Val: Base)) {
1026 if (CE->getCastKind() == CK_ArrayToPointerDecay &&
1027 !CE->getSubExpr()->isFlexibleArrayMemberLike(Context: CGF.getContext(),
1028 StrictFlexArraysLevel)) {
1029 CodeGenFunction::SanitizerScope SanScope(&CGF);
1030
1031 IndexedType = CE->getSubExpr()->getType();
1032 const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
1033 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: AT))
1034 return CGF.Builder.getInt(AI: CAT->getSize());
1035
1036 if (const auto *VAT = dyn_cast<VariableArrayType>(Val: AT))
1037 return CGF.getVLASize(vla: VAT).NumElts;
1038 // Ignore pass_object_size here. It's not applicable on decayed pointers.
1039 }
1040 }
1041
1042 CodeGenFunction::SanitizerScope SanScope(&CGF);
1043
1044 QualType EltTy{Base->getType()->getPointeeOrArrayElementType(), 0};
1045 if (llvm::Value *POS = CGF.LoadPassedObjectSize(E: Base, EltTy)) {
1046 IndexedType = Base->getType();
1047 return POS;
1048 }
1049
1050 return nullptr;
1051}
1052
1053namespace {
1054
1055/// \p StructAccessBase returns the base \p Expr of a field access. It returns
1056/// either a \p DeclRefExpr, representing the base pointer to the struct, i.e.:
1057///
1058/// p in p-> a.b.c
1059///
1060/// or a \p MemberExpr, if the \p MemberExpr has the \p RecordDecl we're
1061/// looking for:
1062///
1063/// struct s {
1064/// struct s *ptr;
1065/// int count;
1066/// char array[] __attribute__((counted_by(count)));
1067/// };
1068///
1069/// If we have an expression like \p p->ptr->array[index], we want the
1070/// \p MemberExpr for \p p->ptr instead of \p p.
1071class StructAccessBase
1072 : public ConstStmtVisitor<StructAccessBase, const Expr *> {
1073 const RecordDecl *ExpectedRD;
1074
1075 bool IsExpectedRecordDecl(const Expr *E) const {
1076 QualType Ty = E->getType();
1077 if (Ty->isPointerType())
1078 Ty = Ty->getPointeeType();
1079 return ExpectedRD == Ty->getAsRecordDecl();
1080 }
1081
1082public:
1083 StructAccessBase(const RecordDecl *ExpectedRD) : ExpectedRD(ExpectedRD) {}
1084
1085 //===--------------------------------------------------------------------===//
1086 // Visitor Methods
1087 //===--------------------------------------------------------------------===//
1088
1089 // NOTE: If we build C++ support for counted_by, then we'll have to handle
1090 // horrors like this:
1091 //
1092 // struct S {
1093 // int x, y;
1094 // int blah[] __attribute__((counted_by(x)));
1095 // } s;
1096 //
1097 // int foo(int index, int val) {
1098 // int (S::*IHatePMDs)[] = &S::blah;
1099 // (s.*IHatePMDs)[index] = val;
1100 // }
1101
1102 const Expr *Visit(const Expr *E) {
1103 return ConstStmtVisitor<StructAccessBase, const Expr *>::Visit(S: E);
1104 }
1105
1106 const Expr *VisitStmt(const Stmt *S) { return nullptr; }
1107
1108 // These are the types we expect to return (in order of most to least
1109 // likely):
1110 //
1111 // 1. DeclRefExpr - This is the expression for the base of the structure.
1112 // It's exactly what we want to build an access to the \p counted_by
1113 // field.
1114 // 2. MemberExpr - This is the expression that has the same \p RecordDecl
1115 // as the flexble array member's lexical enclosing \p RecordDecl. This
1116 // allows us to catch things like: "p->p->array"
1117 // 3. CompoundLiteralExpr - This is for people who create something
1118 // heretical like (struct foo has a flexible array member):
1119 //
1120 // (struct foo){ 1, 2 }.blah[idx];
1121 const Expr *VisitDeclRefExpr(const DeclRefExpr *E) {
1122 return IsExpectedRecordDecl(E) ? E : nullptr;
1123 }
1124 const Expr *VisitMemberExpr(const MemberExpr *E) {
1125 if (IsExpectedRecordDecl(E) && E->isArrow())
1126 return E;
1127 const Expr *Res = Visit(E: E->getBase());
1128 return !Res && IsExpectedRecordDecl(E) ? E : Res;
1129 }
1130 const Expr *VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
1131 return IsExpectedRecordDecl(E) ? E : nullptr;
1132 }
1133 const Expr *VisitCallExpr(const CallExpr *E) {
1134 return IsExpectedRecordDecl(E) ? E : nullptr;
1135 }
1136
1137 const Expr *VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
1138 if (IsExpectedRecordDecl(E))
1139 return E;
1140 return Visit(E: E->getBase());
1141 }
1142 const Expr *VisitCastExpr(const CastExpr *E) {
1143 if (E->getCastKind() == CK_LValueToRValue)
1144 return IsExpectedRecordDecl(E) ? E : nullptr;
1145 return Visit(E: E->getSubExpr());
1146 }
1147 const Expr *VisitParenExpr(const ParenExpr *E) {
1148 return Visit(E: E->getSubExpr());
1149 }
1150 const Expr *VisitUnaryAddrOf(const UnaryOperator *E) {
1151 return Visit(E: E->getSubExpr());
1152 }
1153 const Expr *VisitUnaryDeref(const UnaryOperator *E) {
1154 return Visit(E: E->getSubExpr());
1155 }
1156};
1157
1158} // end anonymous namespace
1159
1160using RecIndicesTy = SmallVector<llvm::Value *, 8>;
1161
1162static bool getGEPIndicesToField(CodeGenFunction &CGF, const RecordDecl *RD,
1163 const FieldDecl *Field,
1164 RecIndicesTy &Indices) {
1165 const CGRecordLayout &Layout = CGF.CGM.getTypes().getCGRecordLayout(RD);
1166 int64_t FieldNo = -1;
1167 for (const FieldDecl *FD : RD->fields()) {
1168 if (!Layout.containsFieldDecl(FD))
1169 // This could happen if the field has a struct type that's empty. I don't
1170 // know why either.
1171 continue;
1172
1173 FieldNo = Layout.getLLVMFieldNo(FD);
1174 if (FD == Field) {
1175 Indices.emplace_back(Args: CGF.Builder.getInt32(C: FieldNo));
1176 return true;
1177 }
1178
1179 QualType Ty = FD->getType();
1180 if (Ty->isRecordType()) {
1181 if (getGEPIndicesToField(CGF, RD: Ty->getAsRecordDecl(), Field, Indices)) {
1182 if (RD->isUnion())
1183 FieldNo = 0;
1184 Indices.emplace_back(Args: CGF.Builder.getInt32(C: FieldNo));
1185 return true;
1186 }
1187 }
1188 }
1189
1190 return false;
1191}
1192
1193llvm::Value *CodeGenFunction::GetCountedByFieldExprGEP(
1194 const Expr *Base, const FieldDecl *FAMDecl, const FieldDecl *CountDecl) {
1195 // Find the record containing the count field. Walk up through anonymous
1196 // structs/unions (which are transparent in C) but stop at named records.
1197 // Using getOuterLexicalRecordContext() here would be wrong because it walks
1198 // past named nested structs to the outermost record, causing a crash when a
1199 // struct with a counted_by FAM is defined nested inside another struct.
1200 const RecordDecl *RD = CountDecl->getParent();
1201 while (RD->isAnonymousStructOrUnion()) {
1202 const auto *Parent = dyn_cast<RecordDecl>(Val: RD->getLexicalParent());
1203 if (!Parent)
1204 break;
1205 RD = Parent;
1206 }
1207
1208 // Find the base struct expr (i.e. p in p->a.b.c.d).
1209 const Expr *StructBase = StructAccessBase(RD).Visit(E: Base);
1210 if (!StructBase || StructBase->HasSideEffects(Ctx: getContext()))
1211 return nullptr;
1212
1213 llvm::Value *Res = nullptr;
1214 if (StructBase->getType()->isPointerType()) {
1215 LValueBaseInfo BaseInfo;
1216 TBAAAccessInfo TBAAInfo;
1217 Address Addr = EmitPointerWithAlignment(Addr: StructBase, BaseInfo: &BaseInfo, TBAAInfo: &TBAAInfo);
1218 Res = Addr.emitRawPointer(CGF&: *this);
1219 } else if (StructBase->isLValue()) {
1220 LValue LV = EmitLValue(E: StructBase);
1221 Address Addr = LV.getAddress();
1222 Res = Addr.emitRawPointer(CGF&: *this);
1223 } else {
1224 return nullptr;
1225 }
1226
1227 RecIndicesTy Indices;
1228 getGEPIndicesToField(CGF&: *this, RD, Field: CountDecl, Indices);
1229 if (Indices.empty())
1230 return nullptr;
1231
1232 Indices.push_back(Elt: Builder.getInt32(C: 0));
1233 CanQualType T = CGM.getContext().getCanonicalTagType(TD: RD);
1234 return Builder.CreateInBoundsGEP(Ty: ConvertType(T), Ptr: Res,
1235 IdxList: RecIndicesTy(llvm::reverse(C&: Indices)),
1236 Name: "counted_by.gep");
1237}
1238
1239/// This method is typically called in contexts where we can't generate
1240/// side-effects, like in __builtin_dynamic_object_size. When finding
1241/// expressions, only choose those that have either already been emitted or can
1242/// be loaded without side-effects.
1243///
1244/// - \p FAMDecl: the \p Decl for the flexible array member. It may not be
1245/// within the top-level struct.
1246/// - \p CountDecl: must be within the same non-anonymous struct as \p FAMDecl.
1247llvm::Value *CodeGenFunction::EmitLoadOfCountedByField(
1248 const Expr *Base, const FieldDecl *FAMDecl, const FieldDecl *CountDecl) {
1249 if (llvm::Value *GEP = GetCountedByFieldExprGEP(Base, FAMDecl, CountDecl))
1250 return Builder.CreateAlignedLoad(Ty: ConvertType(T: CountDecl->getType()), Addr: GEP,
1251 Align: getIntAlign(), Name: "counted_by.load");
1252 return nullptr;
1253}
1254
1255void CodeGenFunction::EmitBoundsCheck(const Expr *ArrayExpr,
1256 const Expr *ArrayExprBase,
1257 llvm::Value *IndexVal, QualType IndexType,
1258 bool Accessed) {
1259 assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
1260 "should not be called unless adding bounds checks");
1261 const LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
1262 getLangOpts().getStrictFlexArraysLevel();
1263 QualType ArrayExprBaseType;
1264 llvm::Value *BoundsVal = getArrayIndexingBound(
1265 CGF&: *this, Base: ArrayExprBase, IndexedType&: ArrayExprBaseType, StrictFlexArraysLevel);
1266
1267 EmitBoundsCheckImpl(ArrayExpr, ArrayBaseType: ArrayExprBaseType, IndexVal, IndexType,
1268 BoundsVal, BoundsType: getContext().getSizeType(), Accessed);
1269}
1270
1271void CodeGenFunction::EmitBoundsCheckImpl(const Expr *ArrayExpr,
1272 QualType ArrayBaseType,
1273 llvm::Value *IndexVal,
1274 QualType IndexType,
1275 llvm::Value *BoundsVal,
1276 QualType BoundsType, bool Accessed) {
1277 if (!BoundsVal)
1278 return;
1279
1280 auto CheckKind = SanitizerKind::SO_ArrayBounds;
1281 auto CheckHandler = SanitizerHandler::OutOfBounds;
1282 SanitizerDebugLocation SanScope(this, {CheckKind}, CheckHandler);
1283
1284 // All hail the C implicit type conversion rules!!!
1285 bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
1286 bool BoundsSigned = BoundsType->isSignedIntegerOrEnumerationType();
1287
1288 const ASTContext &Ctx = getContext();
1289 llvm::Type *Ty = ConvertType(
1290 T: Ctx.getTypeSize(T: IndexType) >= Ctx.getTypeSize(T: BoundsType) ? IndexType
1291 : BoundsType);
1292
1293 llvm::Value *IndexInst = Builder.CreateIntCast(V: IndexVal, DestTy: Ty, isSigned: IndexSigned);
1294 llvm::Value *BoundsInst = Builder.CreateIntCast(V: BoundsVal, DestTy: Ty, isSigned: false);
1295
1296 llvm::Constant *StaticData[] = {
1297 EmitCheckSourceLocation(Loc: ArrayExpr->getExprLoc()),
1298 EmitCheckTypeDescriptor(T: ArrayBaseType),
1299 EmitCheckTypeDescriptor(T: IndexType),
1300 };
1301
1302 llvm::Value *Check = Accessed ? Builder.CreateICmpULT(LHS: IndexInst, RHS: BoundsInst)
1303 : Builder.CreateICmpULE(LHS: IndexInst, RHS: BoundsInst);
1304
1305 if (BoundsSigned) {
1306 // Don't allow a negative bounds.
1307 llvm::Value *Cmp = Builder.CreateICmpSGT(
1308 LHS: BoundsVal, RHS: llvm::ConstantInt::get(Ty: BoundsVal->getType(), V: 0));
1309 Check = Builder.CreateAnd(LHS: Cmp, RHS: Check);
1310 }
1311
1312 EmitCheck(Checked: std::make_pair(x&: Check, y&: CheckKind), Check: CheckHandler, StaticArgs: StaticData,
1313 DynamicArgs: IndexInst);
1314}
1315
1316llvm::MDNode *CodeGenFunction::buildAllocToken(QualType AllocType) {
1317 auto ATMD = infer_alloc::getAllocTokenMetadata(T: AllocType, Ctx: getContext());
1318 if (!ATMD)
1319 return nullptr;
1320
1321 llvm::MDBuilder MDB(getLLVMContext());
1322 auto *TypeNameMD = MDB.createString(Str: ATMD->TypeName);
1323 auto *ContainsPtrC = Builder.getInt1(V: ATMD->ContainsPointer);
1324 auto *ContainsPtrMD = MDB.createConstant(C: ContainsPtrC);
1325
1326 // Format: !{<type-name>, <contains-pointer>}
1327 return llvm::MDNode::get(Context&: CGM.getLLVMContext(), MDs: {TypeNameMD, ContainsPtrMD});
1328}
1329
1330void CodeGenFunction::EmitAllocToken(llvm::CallBase *CB, QualType AllocType) {
1331 assert(SanOpts.has(SanitizerKind::AllocToken) &&
1332 "Only needed with -fsanitize=alloc-token");
1333 CB->setMetadata(KindID: llvm::LLVMContext::MD_alloc_token,
1334 Node: buildAllocToken(AllocType));
1335}
1336
1337llvm::MDNode *CodeGenFunction::buildAllocToken(const CallExpr *E) {
1338 QualType AllocType = infer_alloc::inferPossibleType(E, Ctx: getContext(), CastE: CurCast);
1339 if (!AllocType.isNull())
1340 return buildAllocToken(AllocType);
1341 return nullptr;
1342}
1343
1344void CodeGenFunction::EmitAllocToken(llvm::CallBase *CB, const CallExpr *E) {
1345 assert(SanOpts.has(SanitizerKind::AllocToken) &&
1346 "Only needed with -fsanitize=alloc-token");
1347 if (llvm::MDNode *MDN = buildAllocToken(E))
1348 CB->setMetadata(KindID: llvm::LLVMContext::MD_alloc_token, Node: MDN);
1349}
1350
1351CodeGenFunction::ComplexPairTy CodeGenFunction::
1352EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
1353 bool isInc, bool isPre) {
1354 ComplexPairTy InVal = EmitLoadOfComplex(src: LV, loc: E->getExprLoc());
1355
1356 llvm::Value *NextVal;
1357 if (isa<llvm::IntegerType>(Val: InVal.first->getType())) {
1358 uint64_t AmountVal = isInc ? 1 : -1;
1359 NextVal = llvm::ConstantInt::get(Ty: InVal.first->getType(), V: AmountVal, IsSigned: true);
1360
1361 // Add the inc/dec to the real part.
1362 NextVal = Builder.CreateAdd(LHS: InVal.first, RHS: NextVal, Name: isInc ? "inc" : "dec");
1363 } else {
1364 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
1365 llvm::APFloat FVal(getContext().getFloatTypeSemantics(T: ElemTy), 1);
1366 if (!isInc)
1367 FVal.changeSign();
1368 NextVal = llvm::ConstantFP::get(Context&: getLLVMContext(), V: FVal);
1369
1370 // Add the inc/dec to the real part.
1371 NextVal = Builder.CreateFAdd(L: InVal.first, R: NextVal, Name: isInc ? "inc" : "dec");
1372 }
1373
1374 ComplexPairTy IncVal(NextVal, InVal.second);
1375
1376 // Store the updated result through the lvalue.
1377 EmitStoreOfComplex(V: IncVal, dest: LV, /*init*/ isInit: false);
1378 if (getLangOpts().OpenMP)
1379 CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF&: *this,
1380 LHS: E->getSubExpr());
1381
1382 // If this is a postinc, return the value read from memory, otherwise use the
1383 // updated value.
1384 return isPre ? IncVal : InVal;
1385}
1386
1387void CodeGenModule::EmitExplicitCastExprType(const ExplicitCastExpr *E,
1388 CodeGenFunction *CGF) {
1389 // Bind VLAs in the cast type.
1390 if (CGF && E->getType()->isVariablyModifiedType())
1391 CGF->EmitVariablyModifiedType(Ty: E->getType());
1392
1393 if (CGDebugInfo *DI = getModuleDebugInfo())
1394 DI->EmitExplicitCastType(Ty: E->getType());
1395}
1396
1397//===----------------------------------------------------------------------===//
1398// LValue Expression Emission
1399//===----------------------------------------------------------------------===//
1400
1401static CharUnits getArrayElementAlign(CharUnits arrayAlign, llvm::Value *idx,
1402 CharUnits eltSize) {
1403 // If we have a constant index, we can use the exact offset of the
1404 // element we're accessing.
1405 if (auto *constantIdx = dyn_cast<llvm::ConstantInt>(Val: idx)) {
1406 CharUnits offset = constantIdx->getZExtValue() * eltSize;
1407 return arrayAlign.alignmentAtOffset(offset);
1408 }
1409
1410 // Otherwise, use the worst-case alignment for any element.
1411 return arrayAlign.alignmentOfArrayElement(elementSize: eltSize);
1412}
1413
1414/// Emit pointer + index arithmetic.
1415static Address emitPointerArithmetic(CodeGenFunction &CGF,
1416 const BinaryOperator *BO,
1417 LValueBaseInfo *BaseInfo,
1418 TBAAAccessInfo *TBAAInfo,
1419 KnownNonNull_t IsKnownNonNull) {
1420 assert(BO->isAdditiveOp() && "Expect an addition or subtraction.");
1421 Expr *pointerOperand = BO->getLHS();
1422 Expr *indexOperand = BO->getRHS();
1423 bool isSubtraction = BO->getOpcode() == BO_Sub;
1424
1425 Address BaseAddr = Address::invalid();
1426 llvm::Value *index = nullptr;
1427 // In a subtraction, the LHS is always the pointer.
1428 // Note: do not change the evaluation order.
1429 if (!isSubtraction && !pointerOperand->getType()->isAnyPointerType()) {
1430 std::swap(a&: pointerOperand, b&: indexOperand);
1431 index = CGF.EmitScalarExpr(E: indexOperand);
1432 BaseAddr = CGF.EmitPointerWithAlignment(Addr: pointerOperand, BaseInfo, TBAAInfo,
1433 IsKnownNonNull: NotKnownNonNull);
1434 } else {
1435 BaseAddr = CGF.EmitPointerWithAlignment(Addr: pointerOperand, BaseInfo, TBAAInfo,
1436 IsKnownNonNull: NotKnownNonNull);
1437 index = CGF.EmitScalarExpr(E: indexOperand);
1438 }
1439
1440 llvm::Value *pointer = BaseAddr.getBasePointer();
1441 llvm::Value *Res = CGF.EmitPointerArithmetic(
1442 BO, pointerOperand, pointer, indexOperand, index, isSubtraction);
1443 QualType PointeeTy = BO->getType()->getPointeeType();
1444 CharUnits Align =
1445 getArrayElementAlign(arrayAlign: BaseAddr.getAlignment(), idx: index,
1446 eltSize: CGF.getContext().getTypeSizeInChars(T: PointeeTy));
1447 return Address(Res, CGF.ConvertTypeForMem(T: PointeeTy), Align,
1448 CGF.CGM.getPointerAuthInfoForPointeeType(type: PointeeTy),
1449 /*Offset=*/nullptr, IsKnownNonNull);
1450}
1451
1452static Address EmitPointerWithAlignment(const Expr *E, LValueBaseInfo *BaseInfo,
1453 TBAAAccessInfo *TBAAInfo,
1454 KnownNonNull_t IsKnownNonNull,
1455 CodeGenFunction &CGF) {
1456 // We allow this with ObjC object pointers because of fragile ABIs.
1457 assert(E->getType()->isPointerType() ||
1458 E->getType()->isObjCObjectPointerType());
1459 E = E->IgnoreParens();
1460
1461 // Casts:
1462 if (const CastExpr *CE = dyn_cast<CastExpr>(Val: E)) {
1463 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(Val: CE))
1464 CGF.CGM.EmitExplicitCastExprType(E: ECE, CGF: &CGF);
1465
1466 switch (CE->getCastKind()) {
1467 // Non-converting casts (but not C's implicit conversion from void*).
1468 case CK_BitCast:
1469 case CK_NoOp:
1470 case CK_AddressSpaceConversion:
1471 if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) {
1472 if (PtrTy->getPointeeType()->isVoidType())
1473 break;
1474
1475 LValueBaseInfo InnerBaseInfo;
1476 TBAAAccessInfo InnerTBAAInfo;
1477 Address Addr = CGF.EmitPointerWithAlignment(
1478 Addr: CE->getSubExpr(), BaseInfo: &InnerBaseInfo, TBAAInfo: &InnerTBAAInfo, IsKnownNonNull);
1479 if (BaseInfo) *BaseInfo = InnerBaseInfo;
1480 if (TBAAInfo) *TBAAInfo = InnerTBAAInfo;
1481
1482 if (isa<ExplicitCastExpr>(Val: CE)) {
1483 LValueBaseInfo TargetTypeBaseInfo;
1484 TBAAAccessInfo TargetTypeTBAAInfo;
1485 CharUnits Align = CGF.CGM.getNaturalPointeeTypeAlignment(
1486 T: E->getType(), BaseInfo: &TargetTypeBaseInfo, TBAAInfo: &TargetTypeTBAAInfo);
1487 if (TBAAInfo)
1488 *TBAAInfo =
1489 CGF.CGM.mergeTBAAInfoForCast(SourceInfo: *TBAAInfo, TargetInfo: TargetTypeTBAAInfo);
1490 // If the source l-value is opaque, honor the alignment of the
1491 // casted-to type.
1492 if (InnerBaseInfo.getAlignmentSource() != AlignmentSource::Decl) {
1493 if (BaseInfo)
1494 BaseInfo->mergeForCast(Info: TargetTypeBaseInfo);
1495 Addr.setAlignment(Align);
1496 }
1497 }
1498
1499 if (CGF.SanOpts.has(K: SanitizerKind::CFIUnrelatedCast) &&
1500 CE->getCastKind() == CK_BitCast) {
1501 if (auto PT = E->getType()->getAs<PointerType>())
1502 CGF.EmitVTablePtrCheckForCast(T: PT->getPointeeType(), Derived: Addr,
1503 /*MayBeNull=*/true,
1504 TCK: CodeGenFunction::CFITCK_UnrelatedCast,
1505 Loc: CE->getBeginLoc());
1506 }
1507
1508 llvm::Type *ElemTy =
1509 CGF.ConvertTypeForMem(T: E->getType()->getPointeeType());
1510 Addr = Addr.withElementType(ElemTy);
1511 if (CE->getCastKind() == CK_AddressSpaceConversion)
1512 Addr = CGF.Builder.CreateAddrSpaceCast(
1513 Addr, Ty: CGF.ConvertType(T: E->getType()), ElementTy: ElemTy);
1514
1515 return CGF.authPointerToPointerCast(Ptr: Addr, SourceType: CE->getSubExpr()->getType(),
1516 DestType: CE->getType());
1517 }
1518 break;
1519
1520 // Array-to-pointer decay.
1521 case CK_ArrayToPointerDecay:
1522 return CGF.EmitArrayToPointerDecay(Array: CE->getSubExpr(), BaseInfo, TBAAInfo);
1523
1524 // Derived-to-base conversions.
1525 case CK_UncheckedDerivedToBase:
1526 case CK_DerivedToBase: {
1527 // TODO: Support accesses to members of base classes in TBAA. For now, we
1528 // conservatively pretend that the complete object is of the base class
1529 // type.
1530 if (TBAAInfo)
1531 *TBAAInfo = CGF.CGM.getTBAAAccessInfo(AccessType: E->getType());
1532 Address Addr = CGF.EmitPointerWithAlignment(
1533 Addr: CE->getSubExpr(), BaseInfo, TBAAInfo: nullptr,
1534 IsKnownNonNull: (KnownNonNull_t)(IsKnownNonNull ||
1535 CE->getCastKind() == CK_UncheckedDerivedToBase));
1536 auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
1537 return CGF.GetAddressOfBaseClass(
1538 Value: Addr, Derived, PathBegin: CE->path_begin(), PathEnd: CE->path_end(),
1539 NullCheckValue: CGF.ShouldNullCheckClassCastValue(Cast: CE), Loc: CE->getExprLoc());
1540 }
1541
1542 // TODO: Is there any reason to treat base-to-derived conversions
1543 // specially?
1544 default:
1545 break;
1546 }
1547 }
1548
1549 // Unary &.
1550 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: E)) {
1551 if (UO->getOpcode() == UO_AddrOf) {
1552 LValue LV = CGF.EmitLValue(E: UO->getSubExpr(), IsKnownNonNull);
1553 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
1554 if (TBAAInfo) *TBAAInfo = LV.getTBAAInfo();
1555 return LV.getAddress();
1556 }
1557 }
1558
1559 // std::addressof and variants.
1560 if (auto *Call = dyn_cast<CallExpr>(Val: E)) {
1561 switch (Call->getBuiltinCallee()) {
1562 default:
1563 break;
1564 case Builtin::BIaddressof:
1565 case Builtin::BI__addressof:
1566 case Builtin::BI__builtin_addressof: {
1567 LValue LV = CGF.EmitLValue(E: Call->getArg(Arg: 0), IsKnownNonNull);
1568 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
1569 if (TBAAInfo) *TBAAInfo = LV.getTBAAInfo();
1570 return LV.getAddress();
1571 }
1572 }
1573 }
1574
1575 // Pointer arithmetic: pointer +/- index.
1576 if (auto *BO = dyn_cast<BinaryOperator>(Val: E)) {
1577 if (BO->isAdditiveOp())
1578 return emitPointerArithmetic(CGF, BO, BaseInfo, TBAAInfo, IsKnownNonNull);
1579 }
1580
1581 // TODO: conditional operators, comma.
1582
1583 // Otherwise, use the alignment of the type.
1584 return CGF.makeNaturalAddressForPointer(
1585 Ptr: CGF.EmitScalarExpr(E), T: E->getType()->getPointeeType(), Alignment: CharUnits(),
1586 /*ForPointeeType=*/true, BaseInfo, TBAAInfo, IsKnownNonNull);
1587}
1588
1589/// EmitPointerWithAlignment - Given an expression of pointer type, try to
1590/// derive a more accurate bound on the alignment of the pointer.
1591Address CodeGenFunction::EmitPointerWithAlignment(
1592 const Expr *E, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo,
1593 KnownNonNull_t IsKnownNonNull) {
1594 Address Addr =
1595 ::EmitPointerWithAlignment(E, BaseInfo, TBAAInfo, IsKnownNonNull, CGF&: *this);
1596 if (IsKnownNonNull && !Addr.isKnownNonNull())
1597 Addr.setKnownNonNull();
1598 return Addr;
1599}
1600
1601llvm::Value *CodeGenFunction::EmitNonNullRValueCheck(RValue RV, QualType T) {
1602 llvm::Value *V = RV.getScalarVal();
1603 if (auto MPT = T->getAs<MemberPointerType>())
1604 return CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF&: *this, MemPtr: V, MPT);
1605 return Builder.CreateICmpNE(LHS: V, RHS: llvm::Constant::getNullValue(Ty: V->getType()));
1606}
1607
1608RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
1609 if (Ty->isVoidType())
1610 return RValue::get(V: nullptr);
1611
1612 switch (getEvaluationKind(T: Ty)) {
1613 case TEK_Complex: {
1614 llvm::Type *EltTy =
1615 ConvertType(T: Ty->castAs<ComplexType>()->getElementType());
1616 llvm::Value *U = llvm::UndefValue::get(T: EltTy);
1617 return RValue::getComplex(C: std::make_pair(x&: U, y&: U));
1618 }
1619
1620 // If this is a use of an undefined aggregate type, the aggregate must have an
1621 // identifiable address. Just because the contents of the value are undefined
1622 // doesn't mean that the address can't be taken and compared.
1623 case TEK_Aggregate: {
1624 Address DestPtr = CreateMemTemp(Ty, Name: "undef.agg.tmp");
1625 return RValue::getAggregate(addr: DestPtr);
1626 }
1627
1628 case TEK_Scalar:
1629 return RValue::get(V: llvm::UndefValue::get(T: ConvertType(T: Ty)));
1630 }
1631 llvm_unreachable("bad evaluation kind");
1632}
1633
1634RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
1635 const char *Name) {
1636 ErrorUnsupported(S: E, Type: Name);
1637 return GetUndefRValue(Ty: E->getType());
1638}
1639
1640LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
1641 const char *Name) {
1642 ErrorUnsupported(S: E, Type: Name);
1643 llvm::Type *ElTy = ConvertType(T: E->getType());
1644 llvm::Type *Ty = DefaultPtrTy;
1645 return MakeAddrLValue(
1646 Addr: Address(llvm::UndefValue::get(T: Ty), ElTy, CharUnits::One()), T: E->getType());
1647}
1648
1649bool CodeGenFunction::IsWrappedCXXThis(const Expr *Obj) {
1650 const Expr *Base = Obj;
1651 while (!isa<CXXThisExpr>(Val: Base)) {
1652 // The result of a dynamic_cast can be null.
1653 if (isa<CXXDynamicCastExpr>(Val: Base))
1654 return false;
1655
1656 if (const auto *CE = dyn_cast<CastExpr>(Val: Base)) {
1657 Base = CE->getSubExpr();
1658 } else if (const auto *PE = dyn_cast<ParenExpr>(Val: Base)) {
1659 Base = PE->getSubExpr();
1660 } else if (const auto *UO = dyn_cast<UnaryOperator>(Val: Base)) {
1661 if (UO->getOpcode() == UO_Extension)
1662 Base = UO->getSubExpr();
1663 else
1664 return false;
1665 } else {
1666 return false;
1667 }
1668 }
1669 return true;
1670}
1671
1672LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
1673 LValue LV;
1674 if (SanOpts.has(K: SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(Val: E))
1675 LV = EmitArraySubscriptExpr(E: cast<ArraySubscriptExpr>(Val: E), /*Accessed*/true);
1676 else
1677 LV = EmitLValue(E);
1678 if (!isa<DeclRefExpr>(Val: E) && !LV.isBitField() && LV.isSimple()) {
1679 SanitizerSet SkippedChecks;
1680 if (const auto *ME = dyn_cast<MemberExpr>(Val: E)) {
1681 bool IsBaseCXXThis = IsWrappedCXXThis(Obj: ME->getBase());
1682 if (IsBaseCXXThis)
1683 SkippedChecks.set(K: SanitizerKind::Alignment, Value: true);
1684 if (IsBaseCXXThis || isa<DeclRefExpr>(Val: ME->getBase()))
1685 SkippedChecks.set(K: SanitizerKind::Null, Value: true);
1686 }
1687 EmitTypeCheck(TCK, Loc: E->getExprLoc(), LV, Type: E->getType(), SkippedChecks);
1688 }
1689 return LV;
1690}
1691
1692/// EmitLValue - Emit code to compute a designator that specifies the location
1693/// of the expression.
1694///
1695/// This can return one of two things: a simple address or a bitfield reference.
1696/// In either case, the LLVM Value* in the LValue structure is guaranteed to be
1697/// an LLVM pointer type.
1698///
1699/// If this returns a bitfield reference, nothing about the pointee type of the
1700/// LLVM value is known: For example, it may not be a pointer to an integer.
1701///
1702/// If this returns a normal address, and if the lvalue's C type is fixed size,
1703/// this method guarantees that the returned pointer type will point to an LLVM
1704/// type of the same size of the lvalue's type. If the lvalue has a variable
1705/// length type, this is not possible.
1706///
1707LValue CodeGenFunction::EmitLValue(const Expr *E,
1708 KnownNonNull_t IsKnownNonNull) {
1709 // Running with sufficient stack space to avoid deeply nested expressions
1710 // cause a stack overflow.
1711 LValue LV;
1712 CGM.runWithSufficientStackSpace(
1713 Loc: E->getExprLoc(), Fn: [&] { LV = EmitLValueHelper(E, IsKnownNonNull); });
1714
1715 if (IsKnownNonNull && !LV.isKnownNonNull())
1716 LV.setKnownNonNull();
1717 return LV;
1718}
1719
1720LValue CodeGenFunction::EmitLValueHelper(const Expr *E,
1721 KnownNonNull_t IsKnownNonNull) {
1722 ApplyDebugLocation DL(*this, E);
1723 switch (E->getStmtClass()) {
1724 default: return EmitUnsupportedLValue(E, Name: "l-value expression");
1725
1726 case Expr::ObjCPropertyRefExprClass:
1727 llvm_unreachable("cannot emit a property reference directly");
1728
1729 case Expr::ObjCSelectorExprClass:
1730 return EmitObjCSelectorLValue(E: cast<ObjCSelectorExpr>(Val: E));
1731 case Expr::ObjCIsaExprClass:
1732 return EmitObjCIsaExpr(E: cast<ObjCIsaExpr>(Val: E));
1733 case Expr::BinaryOperatorClass:
1734 return EmitBinaryOperatorLValue(E: cast<BinaryOperator>(Val: E));
1735 case Expr::CompoundAssignOperatorClass: {
1736 QualType Ty = E->getType();
1737 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1738 Ty = AT->getValueType();
1739 if (!Ty->isAnyComplexType())
1740 return EmitCompoundAssignmentLValue(E: cast<CompoundAssignOperator>(Val: E));
1741 return EmitComplexCompoundAssignmentLValue(E: cast<CompoundAssignOperator>(Val: E));
1742 }
1743 case Expr::CallExprClass:
1744 case Expr::CXXMemberCallExprClass:
1745 case Expr::CXXOperatorCallExprClass:
1746 case Expr::UserDefinedLiteralClass:
1747 return EmitCallExprLValue(E: cast<CallExpr>(Val: E));
1748 case Expr::CXXRewrittenBinaryOperatorClass:
1749 return EmitLValue(E: cast<CXXRewrittenBinaryOperator>(Val: E)->getSemanticForm(),
1750 IsKnownNonNull);
1751 case Expr::VAArgExprClass:
1752 return EmitVAArgExprLValue(E: cast<VAArgExpr>(Val: E));
1753 case Expr::DeclRefExprClass:
1754 return EmitDeclRefLValue(E: cast<DeclRefExpr>(Val: E));
1755 case Expr::ConstantExprClass: {
1756 const ConstantExpr *CE = cast<ConstantExpr>(Val: E);
1757 if (llvm::Value *Result = ConstantEmitter(*this).tryEmitConstantExpr(CE))
1758 return MakeNaturalAlignPointeeAddrLValue(V: Result, T: CE->getType());
1759 return EmitLValue(E: cast<ConstantExpr>(Val: E)->getSubExpr(), IsKnownNonNull);
1760 }
1761 case Expr::ParenExprClass:
1762 return EmitLValue(E: cast<ParenExpr>(Val: E)->getSubExpr(), IsKnownNonNull);
1763 case Expr::GenericSelectionExprClass:
1764 return EmitLValue(E: cast<GenericSelectionExpr>(Val: E)->getResultExpr(),
1765 IsKnownNonNull);
1766 case Expr::PredefinedExprClass:
1767 return EmitPredefinedLValue(E: cast<PredefinedExpr>(Val: E));
1768 case Expr::StringLiteralClass:
1769 return EmitStringLiteralLValue(E: cast<StringLiteral>(Val: E));
1770 case Expr::ObjCEncodeExprClass:
1771 return EmitObjCEncodeExprLValue(E: cast<ObjCEncodeExpr>(Val: E));
1772 case Expr::PseudoObjectExprClass:
1773 return EmitPseudoObjectLValue(e: cast<PseudoObjectExpr>(Val: E));
1774 case Expr::InitListExprClass:
1775 return EmitInitListLValue(E: cast<InitListExpr>(Val: E));
1776 case Expr::CXXTemporaryObjectExprClass:
1777 case Expr::CXXConstructExprClass:
1778 return EmitCXXConstructLValue(E: cast<CXXConstructExpr>(Val: E));
1779 case Expr::CXXBindTemporaryExprClass:
1780 return EmitCXXBindTemporaryLValue(E: cast<CXXBindTemporaryExpr>(Val: E));
1781 case Expr::CXXUuidofExprClass:
1782 return EmitCXXUuidofLValue(E: cast<CXXUuidofExpr>(Val: E));
1783 case Expr::LambdaExprClass:
1784 return EmitAggExprToLValue(E);
1785
1786 case Expr::ExprWithCleanupsClass: {
1787 const auto *cleanups = cast<ExprWithCleanups>(Val: E);
1788 RunCleanupsScope Scope(*this);
1789 LValue LV = EmitLValue(E: cleanups->getSubExpr(), IsKnownNonNull);
1790 if (LV.isSimple()) {
1791 // Defend against branches out of gnu statement expressions surrounded by
1792 // cleanups.
1793 Address Addr = LV.getAddress();
1794 llvm::Value *V = Addr.getBasePointer();
1795 Scope.ForceCleanup(ValuesToReload: {&V});
1796 Addr.replaceBasePointer(P: V);
1797 return LValue::MakeAddr(Addr, type: LV.getType(), Context&: getContext(),
1798 BaseInfo: LV.getBaseInfo(), TBAAInfo: LV.getTBAAInfo());
1799 }
1800 // FIXME: Is it possible to create an ExprWithCleanups that produces a
1801 // bitfield lvalue or some other non-simple lvalue?
1802 return LV;
1803 }
1804
1805 case Expr::CXXDefaultArgExprClass: {
1806 auto *DAE = cast<CXXDefaultArgExpr>(Val: E);
1807 CXXDefaultArgExprScope Scope(*this, DAE);
1808 return EmitLValue(E: DAE->getExpr(), IsKnownNonNull);
1809 }
1810 case Expr::CXXDefaultInitExprClass: {
1811 auto *DIE = cast<CXXDefaultInitExpr>(Val: E);
1812 CXXDefaultInitExprScope Scope(*this, DIE);
1813 return EmitLValue(E: DIE->getExpr(), IsKnownNonNull);
1814 }
1815 case Expr::CXXTypeidExprClass:
1816 return EmitCXXTypeidLValue(E: cast<CXXTypeidExpr>(Val: E));
1817
1818 case Expr::ObjCMessageExprClass:
1819 return EmitObjCMessageExprLValue(E: cast<ObjCMessageExpr>(Val: E));
1820 case Expr::ObjCIvarRefExprClass:
1821 return EmitObjCIvarRefLValue(E: cast<ObjCIvarRefExpr>(Val: E));
1822 case Expr::StmtExprClass:
1823 return EmitStmtExprLValue(E: cast<StmtExpr>(Val: E));
1824 case Expr::UnaryOperatorClass:
1825 return EmitUnaryOpLValue(E: cast<UnaryOperator>(Val: E));
1826 case Expr::ArraySubscriptExprClass:
1827 return EmitArraySubscriptExpr(E: cast<ArraySubscriptExpr>(Val: E));
1828 case Expr::MatrixSingleSubscriptExprClass:
1829 return EmitMatrixSingleSubscriptExpr(E: cast<MatrixSingleSubscriptExpr>(Val: E));
1830 case Expr::MatrixSubscriptExprClass:
1831 return EmitMatrixSubscriptExpr(E: cast<MatrixSubscriptExpr>(Val: E));
1832 case Expr::ArraySectionExprClass:
1833 return EmitArraySectionExpr(E: cast<ArraySectionExpr>(Val: E));
1834 case Expr::ExtVectorElementExprClass:
1835 return EmitExtVectorElementExpr(E: cast<ExtVectorElementExpr>(Val: E));
1836 case Expr::MatrixElementExprClass:
1837 return EmitMatrixElementExpr(E: cast<MatrixElementExpr>(Val: E));
1838 case Expr::CXXThisExprClass:
1839 return MakeAddrLValue(Addr: LoadCXXThisAddress(), T: E->getType());
1840 case Expr::MemberExprClass:
1841 return EmitMemberExpr(E: cast<MemberExpr>(Val: E));
1842 case Expr::CompoundLiteralExprClass:
1843 return EmitCompoundLiteralLValue(E: cast<CompoundLiteralExpr>(Val: E));
1844 case Expr::ConditionalOperatorClass:
1845 return EmitConditionalOperatorLValue(E: cast<ConditionalOperator>(Val: E));
1846 case Expr::BinaryConditionalOperatorClass:
1847 return EmitConditionalOperatorLValue(E: cast<BinaryConditionalOperator>(Val: E));
1848 case Expr::ChooseExprClass:
1849 return EmitLValue(E: cast<ChooseExpr>(Val: E)->getChosenSubExpr(), IsKnownNonNull);
1850 case Expr::OpaqueValueExprClass:
1851 return EmitOpaqueValueLValue(e: cast<OpaqueValueExpr>(Val: E));
1852 case Expr::SubstNonTypeTemplateParmExprClass:
1853 return EmitLValue(E: cast<SubstNonTypeTemplateParmExpr>(Val: E)->getReplacement(),
1854 IsKnownNonNull);
1855 case Expr::ImplicitCastExprClass:
1856 case Expr::CStyleCastExprClass:
1857 case Expr::CXXFunctionalCastExprClass:
1858 case Expr::CXXStaticCastExprClass:
1859 case Expr::CXXDynamicCastExprClass:
1860 case Expr::CXXReinterpretCastExprClass:
1861 case Expr::CXXConstCastExprClass:
1862 case Expr::CXXAddrspaceCastExprClass:
1863 case Expr::ObjCBridgedCastExprClass:
1864 return EmitCastLValue(E: cast<CastExpr>(Val: E));
1865
1866 case Expr::MaterializeTemporaryExprClass:
1867 return EmitMaterializeTemporaryExpr(M: cast<MaterializeTemporaryExpr>(Val: E));
1868
1869 case Expr::CoawaitExprClass:
1870 return EmitCoawaitLValue(E: cast<CoawaitExpr>(Val: E));
1871 case Expr::CoyieldExprClass:
1872 return EmitCoyieldLValue(E: cast<CoyieldExpr>(Val: E));
1873 case Expr::PackIndexingExprClass:
1874 return EmitLValue(E: cast<PackIndexingExpr>(Val: E)->getSelectedExpr());
1875 case Expr::HLSLOutArgExprClass:
1876 llvm_unreachable("cannot emit a HLSL out argument directly");
1877 }
1878}
1879
1880/// Given an object of the given canonical type, can we safely copy a
1881/// value out of it based on its initializer?
1882static bool isConstantEmittableObjectType(QualType type) {
1883 assert(type.isCanonical());
1884 assert(!type->isReferenceType());
1885
1886 // Must be const-qualified but non-volatile.
1887 Qualifiers qs = type.getLocalQualifiers();
1888 if (!qs.hasConst() || qs.hasVolatile()) return false;
1889
1890 // Otherwise, all object types satisfy this except C++ classes with
1891 // mutable subobjects or non-trivial copy/destroy behavior.
1892 if (const auto *RT = dyn_cast<RecordType>(Val&: type))
1893 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: RT->getDecl())) {
1894 RD = RD->getDefinitionOrSelf();
1895 if (RD->hasMutableFields() || !RD->isTrivial())
1896 return false;
1897 }
1898
1899 return true;
1900}
1901
1902/// Can we constant-emit a load of a reference to a variable of the
1903/// given type? This is different from predicates like
1904/// Decl::mightBeUsableInConstantExpressions because we do want it to apply
1905/// in situations that don't necessarily satisfy the language's rules
1906/// for this (e.g. C++'s ODR-use rules). For example, we want to able
1907/// to do this with const float variables even if those variables
1908/// aren't marked 'constexpr'.
1909enum ConstantEmissionKind {
1910 CEK_None,
1911 CEK_AsReferenceOnly,
1912 CEK_AsValueOrReference,
1913 CEK_AsValueOnly
1914};
1915static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
1916 type = type.getCanonicalType();
1917 if (const auto *ref = dyn_cast<ReferenceType>(Val&: type)) {
1918 if (isConstantEmittableObjectType(type: ref->getPointeeType()))
1919 return CEK_AsValueOrReference;
1920 return CEK_AsReferenceOnly;
1921 }
1922 if (isConstantEmittableObjectType(type))
1923 return CEK_AsValueOnly;
1924 return CEK_None;
1925}
1926
1927/// Try to emit a reference to the given value without producing it as
1928/// an l-value. This is just an optimization, but it avoids us needing
1929/// to emit global copies of variables if they're named without triggering
1930/// a formal use in a context where we can't emit a direct reference to them,
1931/// for instance if a block or lambda or a member of a local class uses a
1932/// const int variable or constexpr variable from an enclosing function.
1933CodeGenFunction::ConstantEmission
1934CodeGenFunction::tryEmitAsConstant(const DeclRefExpr *RefExpr) {
1935 const ValueDecl *Value = RefExpr->getDecl();
1936
1937 // The value needs to be an enum constant or a constant variable.
1938 ConstantEmissionKind CEK;
1939 if (isa<ParmVarDecl>(Val: Value)) {
1940 CEK = CEK_None;
1941 } else if (const auto *var = dyn_cast<VarDecl>(Val: Value)) {
1942 CEK = checkVarTypeForConstantEmission(type: var->getType());
1943 } else if (isa<EnumConstantDecl>(Val: Value)) {
1944 CEK = CEK_AsValueOnly;
1945 } else {
1946 CEK = CEK_None;
1947 }
1948 if (CEK == CEK_None) return ConstantEmission();
1949
1950 Expr::EvalResult result;
1951 bool resultIsReference;
1952 QualType resultType;
1953
1954 // It's best to evaluate all the way as an r-value if that's permitted.
1955 if (CEK != CEK_AsReferenceOnly &&
1956 RefExpr->EvaluateAsRValue(Result&: result, Ctx: getContext())) {
1957 resultIsReference = false;
1958 resultType = RefExpr->getType().getUnqualifiedType();
1959
1960 // Otherwise, try to evaluate as an l-value.
1961 } else if (CEK != CEK_AsValueOnly &&
1962 RefExpr->EvaluateAsLValue(Result&: result, Ctx: getContext())) {
1963 resultIsReference = true;
1964 resultType = Value->getType();
1965
1966 // Failure.
1967 } else {
1968 return ConstantEmission();
1969 }
1970
1971 // In any case, if the initializer has side-effects, abandon ship.
1972 if (result.HasSideEffects)
1973 return ConstantEmission();
1974
1975 // In CUDA/HIP device compilation, a lambda may capture a reference variable
1976 // referencing a global host variable by copy. In this case the lambda should
1977 // make a copy of the value of the global host variable. The DRE of the
1978 // captured reference variable cannot be emitted as load from the host
1979 // global variable as compile time constant, since the host variable is not
1980 // accessible on device. The DRE of the captured reference variable has to be
1981 // loaded from captures.
1982 if (CGM.getLangOpts().CUDAIsDevice && result.Val.isLValue() &&
1983 RefExpr->refersToEnclosingVariableOrCapture()) {
1984 auto *MD = dyn_cast_or_null<CXXMethodDecl>(Val: CurCodeDecl);
1985 if (isLambdaMethod(DC: MD) && MD->getOverloadedOperator() == OO_Call) {
1986 const APValue::LValueBase &base = result.Val.getLValueBase();
1987 if (const ValueDecl *D = base.dyn_cast<const ValueDecl *>()) {
1988 if (const VarDecl *VD = dyn_cast<const VarDecl>(Val: D)) {
1989 if (!VD->hasAttr<CUDADeviceAttr>()) {
1990 return ConstantEmission();
1991 }
1992 }
1993 }
1994 }
1995 }
1996
1997 // Emit as a constant.
1998 llvm::Constant *C = ConstantEmitter(*this).emitAbstract(
1999 loc: RefExpr->getLocation(), value: result.Val, T: resultType);
2000
2001 // Make sure we emit a debug reference to the global variable.
2002 // This should probably fire even for
2003 if (isa<VarDecl>(Val: Value)) {
2004 if (!getContext().DeclMustBeEmitted(D: cast<VarDecl>(Val: Value)))
2005 EmitDeclRefExprDbgValue(E: RefExpr, Init: result.Val);
2006 } else {
2007 assert(isa<EnumConstantDecl>(Value));
2008 EmitDeclRefExprDbgValue(E: RefExpr, Init: result.Val);
2009 }
2010
2011 // If we emitted a reference constant, we need to dereference that.
2012 if (resultIsReference)
2013 return ConstantEmission::forReference(C);
2014
2015 return ConstantEmission::forValue(C);
2016}
2017
2018static DeclRefExpr *tryToConvertMemberExprToDeclRefExpr(CodeGenFunction &CGF,
2019 const MemberExpr *ME) {
2020 if (auto *VD = dyn_cast<VarDecl>(Val: ME->getMemberDecl())) {
2021 // Try to emit static variable member expressions as DREs.
2022 return DeclRefExpr::Create(
2023 Context: CGF.getContext(), QualifierLoc: NestedNameSpecifierLoc(), TemplateKWLoc: SourceLocation(), D: VD,
2024 /*RefersToEnclosingVariableOrCapture=*/false, NameLoc: ME->getExprLoc(),
2025 T: ME->getType(), VK: ME->getValueKind(), FoundD: nullptr, TemplateArgs: nullptr, NOUR: ME->isNonOdrUse());
2026 }
2027 return nullptr;
2028}
2029
2030CodeGenFunction::ConstantEmission
2031CodeGenFunction::tryEmitAsConstant(const MemberExpr *ME) {
2032 if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(CGF&: *this, ME))
2033 return tryEmitAsConstant(RefExpr: DRE);
2034 return ConstantEmission();
2035}
2036
2037llvm::Value *CodeGenFunction::emitScalarConstant(
2038 const CodeGenFunction::ConstantEmission &Constant, Expr *E) {
2039 assert(Constant && "not a constant");
2040 if (Constant.isReference())
2041 return EmitLoadOfLValue(V: Constant.getReferenceLValue(CGF&: *this, RefExpr: E),
2042 Loc: E->getExprLoc())
2043 .getScalarVal();
2044 return Constant.getValue();
2045}
2046
2047llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
2048 SourceLocation Loc) {
2049 return EmitLoadOfScalar(Addr: lvalue.getAddress(), Volatile: lvalue.isVolatile(),
2050 Ty: lvalue.getType(), Loc, BaseInfo: lvalue.getBaseInfo(),
2051 TBAAInfo: lvalue.getTBAAInfo(), isNontemporal: lvalue.isNontemporal());
2052}
2053
2054static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
2055 llvm::APInt &Min, llvm::APInt &End,
2056 bool StrictEnums, bool IsBool) {
2057 const auto *ED = Ty->getAsEnumDecl();
2058 bool IsRegularCPlusPlusEnum =
2059 CGF.getLangOpts().CPlusPlus && StrictEnums && ED && !ED->isFixed();
2060 if (!IsBool && !IsRegularCPlusPlusEnum)
2061 return false;
2062
2063 if (IsBool) {
2064 Min = llvm::APInt(CGF.getContext().getTypeSize(T: Ty), 0);
2065 End = llvm::APInt(CGF.getContext().getTypeSize(T: Ty), 2);
2066 } else {
2067 ED->getValueRange(Max&: End, Min);
2068 }
2069 return true;
2070}
2071
2072llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
2073 llvm::APInt Min, End;
2074 if (!getRangeForType(CGF&: *this, Ty, Min, End, StrictEnums: CGM.getCodeGenOpts().StrictEnums,
2075 IsBool: Ty->hasBooleanRepresentation() && !Ty->isVectorType()))
2076 return nullptr;
2077
2078 llvm::MDBuilder MDHelper(getLLVMContext());
2079 return MDHelper.createRange(Lo: Min, Hi: End);
2080}
2081
2082void CodeGenFunction::maybeAttachRangeForLoad(llvm::LoadInst *Load, QualType Ty,
2083 SourceLocation Loc) {
2084 if (EmitScalarRangeCheck(Value: Load, Ty, Loc)) {
2085 // In order to prevent the optimizer from throwing away the check, don't
2086 // attach range metadata to the load.
2087 } else if (CGM.getCodeGenOpts().OptimizationLevel > 0) {
2088 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty)) {
2089 Load->setMetadata(KindID: llvm::LLVMContext::MD_range, Node: RangeInfo);
2090 Load->setMetadata(KindID: llvm::LLVMContext::MD_noundef,
2091 Node: llvm::MDNode::get(Context&: CGM.getLLVMContext(), MDs: {}));
2092 }
2093 }
2094}
2095
2096bool CodeGenFunction::EmitScalarRangeCheck(llvm::Value *Value, QualType Ty,
2097 SourceLocation Loc) {
2098 bool HasBoolCheck = SanOpts.has(K: SanitizerKind::Bool);
2099 bool HasEnumCheck = SanOpts.has(K: SanitizerKind::Enum);
2100 if (!HasBoolCheck && !HasEnumCheck)
2101 return false;
2102
2103 bool IsBool = (Ty->hasBooleanRepresentation() && !Ty->isVectorType()) ||
2104 NSAPI(CGM.getContext()).isObjCBOOLType(T: Ty);
2105 bool NeedsBoolCheck = HasBoolCheck && IsBool;
2106 bool NeedsEnumCheck = HasEnumCheck && Ty->isEnumeralType();
2107 if (!NeedsBoolCheck && !NeedsEnumCheck)
2108 return false;
2109
2110 // Single-bit booleans don't need to be checked. Special-case this to avoid
2111 // a bit width mismatch when handling bitfield values. This is handled by
2112 // EmitFromMemory for the non-bitfield case.
2113 if (IsBool &&
2114 cast<llvm::IntegerType>(Val: Value->getType())->getBitWidth() == 1)
2115 return false;
2116
2117 if (NeedsEnumCheck &&
2118 getContext().isTypeIgnoredBySanitizer(Mask: SanitizerKind::Enum, Ty))
2119 return false;
2120
2121 llvm::APInt Min, End;
2122 if (!getRangeForType(CGF&: *this, Ty, Min, End, /*StrictEnums=*/true, IsBool))
2123 return true;
2124
2125 SanitizerKind::SanitizerOrdinal Kind =
2126 NeedsEnumCheck ? SanitizerKind::SO_Enum : SanitizerKind::SO_Bool;
2127
2128 auto &Ctx = getLLVMContext();
2129 auto CheckHandler = SanitizerHandler::LoadInvalidValue;
2130 SanitizerDebugLocation SanScope(this, {Kind}, CheckHandler);
2131 llvm::Value *Check;
2132 --End;
2133 if (!Min) {
2134 Check = Builder.CreateICmpULE(LHS: Value, RHS: llvm::ConstantInt::get(Context&: Ctx, V: End));
2135 } else {
2136 llvm::Value *Upper =
2137 Builder.CreateICmpSLE(LHS: Value, RHS: llvm::ConstantInt::get(Context&: Ctx, V: End));
2138 llvm::Value *Lower =
2139 Builder.CreateICmpSGE(LHS: Value, RHS: llvm::ConstantInt::get(Context&: Ctx, V: Min));
2140 Check = Builder.CreateAnd(LHS: Upper, RHS: Lower);
2141 }
2142 llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc),
2143 EmitCheckTypeDescriptor(T: Ty)};
2144 EmitCheck(Checked: std::make_pair(x&: Check, y&: Kind), Check: CheckHandler, StaticArgs, DynamicArgs: Value);
2145 return true;
2146}
2147
2148llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile,
2149 QualType Ty,
2150 SourceLocation Loc,
2151 LValueBaseInfo BaseInfo,
2152 TBAAAccessInfo TBAAInfo,
2153 bool isNontemporal) {
2154 if (auto *GV = dyn_cast<llvm::GlobalValue>(Val: Addr.getBasePointer()))
2155 if (GV->isThreadLocal())
2156 Addr = Addr.withPointer(NewPointer: Builder.CreateThreadLocalAddress(Ptr: GV),
2157 IsKnownNonNull: NotKnownNonNull);
2158
2159 if (const auto *ClangVecTy = Ty->getAs<VectorType>()) {
2160 // Boolean vectors use `iN` as storage type.
2161 if (ClangVecTy->isPackedVectorBoolType(ctx: getContext())) {
2162 llvm::Type *ValTy = ConvertType(T: Ty);
2163 unsigned ValNumElems =
2164 cast<llvm::FixedVectorType>(Val: ValTy)->getNumElements();
2165 // Load the `iP` storage object (P is the padded vector size).
2166 auto *RawIntV = Builder.CreateLoad(Addr, IsVolatile: Volatile, Name: "load_bits");
2167 const auto *RawIntTy = RawIntV->getType();
2168 assert(RawIntTy->isIntegerTy() && "compressed iN storage for bitvectors");
2169 // Bitcast iP --> <P x i1>.
2170 auto *PaddedVecTy = llvm::FixedVectorType::get(
2171 ElementType: Builder.getInt1Ty(), NumElts: RawIntTy->getPrimitiveSizeInBits());
2172 llvm::Value *V = Builder.CreateBitCast(V: RawIntV, DestTy: PaddedVecTy);
2173 // Shuffle <P x i1> --> <N x i1> (N is the actual bit size).
2174 V = emitBoolVecConversion(SrcVec: V, NumElementsDst: ValNumElems, Name: "extractvec");
2175
2176 return EmitFromMemory(Value: V, Ty);
2177 }
2178
2179 // Handles vectors of sizes that are likely to be expanded to a larger size
2180 // to optimize performance.
2181 auto *VTy = cast<llvm::FixedVectorType>(Val: Addr.getElementType());
2182 auto *NewVecTy =
2183 CGM.getABIInfo().getOptimalVectorMemoryType(T: VTy, Opt: getLangOpts());
2184
2185 if (VTy != NewVecTy) {
2186 Address Cast = Addr.withElementType(ElemTy: NewVecTy);
2187 llvm::Value *V = Builder.CreateLoad(Addr: Cast, IsVolatile: Volatile, Name: "loadVecN");
2188 unsigned OldNumElements = VTy->getNumElements();
2189 SmallVector<int, 16> Mask(OldNumElements);
2190 std::iota(first: Mask.begin(), last: Mask.end(), value: 0);
2191 V = Builder.CreateShuffleVector(V, Mask, Name: "extractVec");
2192 return EmitFromMemory(Value: V, Ty);
2193 }
2194 }
2195
2196 // Atomic operations have to be done on integral types.
2197 LValue AtomicLValue =
2198 LValue::MakeAddr(Addr, type: Ty, Context&: getContext(), BaseInfo, TBAAInfo);
2199 if (Ty->isAtomicType() || LValueIsSuitableForInlineAtomic(Src: AtomicLValue)) {
2200 return EmitAtomicLoad(LV: AtomicLValue, SL: Loc).getScalarVal();
2201 }
2202
2203 Addr =
2204 Addr.withElementType(ElemTy: convertTypeForLoadStore(ASTTy: Ty, LLVMTy: Addr.getElementType()));
2205
2206 llvm::LoadInst *Load = Builder.CreateLoad(Addr, IsVolatile: Volatile);
2207 if (isNontemporal) {
2208 llvm::MDNode *Node = llvm::MDNode::get(
2209 Context&: Load->getContext(), MDs: llvm::ConstantAsMetadata::get(C: Builder.getInt32(C: 1)));
2210 Load->setMetadata(KindID: llvm::LLVMContext::MD_nontemporal, Node);
2211 }
2212
2213 CGM.DecorateInstructionWithTBAA(Inst: Load, TBAAInfo);
2214
2215 maybeAttachRangeForLoad(Load, Ty, Loc);
2216
2217 return EmitFromMemory(Value: Load, Ty);
2218}
2219
2220/// Converts a scalar value from its primary IR type (as returned
2221/// by ConvertType) to its load/store type (as returned by
2222/// convertTypeForLoadStore).
2223llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
2224 if (auto *AtomicTy = Ty->getAs<AtomicType>())
2225 Ty = AtomicTy->getValueType();
2226
2227 if (Ty->isExtVectorBoolType() || Ty->isConstantMatrixBoolType()) {
2228 llvm::Type *StoreTy = convertTypeForLoadStore(ASTTy: Ty, LLVMTy: Value->getType());
2229
2230 if (Value->getType() == StoreTy)
2231 return Value;
2232
2233 if (StoreTy->isVectorTy() && StoreTy->getScalarSizeInBits() >
2234 Value->getType()->getScalarSizeInBits())
2235 return Builder.CreateZExt(V: Value, DestTy: StoreTy);
2236
2237 // Expand to the memory bit width.
2238 unsigned MemNumElems = StoreTy->getPrimitiveSizeInBits();
2239 // <N x i1> --> <P x i1>.
2240 Value = emitBoolVecConversion(SrcVec: Value, NumElementsDst: MemNumElems, Name: "insertvec");
2241 // <P x i1> --> iP.
2242 Value = Builder.CreateBitCast(V: Value, DestTy: StoreTy);
2243 }
2244
2245 if (Ty->hasBooleanRepresentation() || Ty->isBitIntType()) {
2246 llvm::Type *StoreTy = convertTypeForLoadStore(ASTTy: Ty, LLVMTy: Value->getType());
2247 bool Signed = Ty->isSignedIntegerOrEnumerationType();
2248 return Builder.CreateIntCast(V: Value, DestTy: StoreTy, isSigned: Signed, Name: "storedv");
2249 }
2250
2251 return Value;
2252}
2253
2254/// Converts a scalar value from its load/store type (as returned
2255/// by convertTypeForLoadStore) to its primary IR type (as returned
2256/// by ConvertType).
2257llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
2258 if (auto *AtomicTy = Ty->getAs<AtomicType>())
2259 Ty = AtomicTy->getValueType();
2260
2261 if (Ty->isPackedVectorBoolType(ctx: getContext())) {
2262 const auto *RawIntTy = Value->getType();
2263
2264 // Bitcast iP --> <P x i1>.
2265 auto *PaddedVecTy = llvm::FixedVectorType::get(
2266 ElementType: Builder.getInt1Ty(), NumElts: RawIntTy->getPrimitiveSizeInBits());
2267 auto *V = Builder.CreateBitCast(V: Value, DestTy: PaddedVecTy);
2268 // Shuffle <P x i1> --> <N x i1> (N is the actual bit size).
2269 llvm::Type *ValTy = ConvertType(T: Ty);
2270 unsigned ValNumElems = cast<llvm::FixedVectorType>(Val: ValTy)->getNumElements();
2271 return emitBoolVecConversion(SrcVec: V, NumElementsDst: ValNumElems, Name: "extractvec");
2272 }
2273
2274 llvm::Type *ResTy = ConvertType(T: Ty);
2275 if (Ty->hasBooleanRepresentation() || Ty->isBitIntType() ||
2276 Ty->isExtVectorBoolType())
2277 return Builder.CreateTrunc(V: Value, DestTy: ResTy, Name: "loadedv");
2278
2279 return Value;
2280}
2281
2282// Convert the pointer of \p Addr to a pointer to a vector (the value type of
2283// MatrixType), if it points to a array (the memory type of MatrixType).
2284static RawAddress MaybeConvertMatrixAddress(RawAddress Addr,
2285 CodeGenFunction &CGF,
2286 bool IsVector = true) {
2287 auto *ArrayTy = dyn_cast<llvm::ArrayType>(Val: Addr.getElementType());
2288 if (ArrayTy && IsVector) {
2289 auto ArrayElements = ArrayTy->getNumElements();
2290 auto *ArrayElementTy = ArrayTy->getElementType();
2291 if (CGF.getContext().getLangOpts().HLSL) {
2292 auto *VectorTy = cast<llvm::FixedVectorType>(Val: ArrayElementTy);
2293 ArrayElementTy = VectorTy->getElementType();
2294 ArrayElements *= VectorTy->getNumElements();
2295 }
2296 auto *VectorTy = llvm::FixedVectorType::get(ElementType: ArrayElementTy, NumElts: ArrayElements);
2297
2298 return Addr.withElementType(ElemTy: VectorTy);
2299 }
2300 auto *VectorTy = dyn_cast<llvm::VectorType>(Val: Addr.getElementType());
2301 if (VectorTy && !IsVector) {
2302 auto *ArrayTy = llvm::ArrayType::get(
2303 ElementType: VectorTy->getElementType(),
2304 NumElements: cast<llvm::FixedVectorType>(Val: VectorTy)->getNumElements());
2305
2306 return Addr.withElementType(ElemTy: ArrayTy);
2307 }
2308
2309 return Addr;
2310}
2311
2312LValue CodeGenFunction::EmitMatrixElementExpr(const MatrixElementExpr *E) {
2313 LValue Base;
2314 if (E->getBase()->isGLValue())
2315 Base = EmitLValue(E: E->getBase());
2316 else {
2317 assert(E->getBase()->getType()->isConstantMatrixType() &&
2318 "Result must be a Constant Matrix");
2319 llvm::Value *Mat = EmitScalarExpr(E: E->getBase());
2320 Address MatMem = CreateMemTemp(Ty: E->getBase()->getType());
2321 QualType Ty = E->getBase()->getType();
2322 llvm::Type *LTy = convertTypeForLoadStore(ASTTy: Ty, LLVMTy: Mat->getType());
2323 if (LTy->getScalarSizeInBits() > Mat->getType()->getScalarSizeInBits())
2324 Mat = Builder.CreateZExt(V: Mat, DestTy: LTy);
2325 Builder.CreateStore(Val: Mat, Addr: MatMem);
2326 Base = MakeAddrLValue(Addr: MatMem, T: Ty, Source: AlignmentSource::Decl);
2327 }
2328 QualType ResultType =
2329 E->getType().withCVRQualifiers(CVR: Base.getQuals().getCVRQualifiers());
2330
2331 // Encode the element access list into a vector of unsigned indices.
2332 SmallVector<uint32_t, 4> Indices;
2333 E->getEncodedElementAccess(Elts&: Indices);
2334
2335 if (Base.isSimple()) {
2336 llvm::Constant *CV =
2337 llvm::ConstantDataVector::get(Context&: getLLVMContext(), Elts: Indices);
2338 return LValue::MakeExtVectorElt(
2339 Addr: MaybeConvertMatrixAddress(Addr: Base.getAddress(), CGF&: *this), Elts: CV, type: ResultType,
2340 BaseInfo: Base.getBaseInfo(), TBAAInfo: TBAAAccessInfo());
2341 }
2342 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
2343
2344 llvm::Constant *BaseElts = Base.getExtVectorElts();
2345 SmallVector<llvm::Constant *, 4> CElts;
2346
2347 for (unsigned Index : Indices)
2348 CElts.push_back(Elt: BaseElts->getAggregateElement(Elt: Index));
2349 llvm::Constant *CV = llvm::ConstantVector::get(V: CElts);
2350 return LValue::MakeExtVectorElt(
2351 Addr: MaybeConvertMatrixAddress(Addr: Base.getExtVectorAddress(), CGF&: *this), Elts: CV,
2352 type: ResultType, BaseInfo: Base.getBaseInfo(), TBAAInfo: TBAAAccessInfo());
2353}
2354
2355// Emit a store of a matrix LValue. This may require casting the original
2356// pointer to memory address (ArrayType) to a pointer to the value type
2357// (VectorType).
2358static void EmitStoreOfMatrixScalar(llvm::Value *value, LValue lvalue,
2359 bool isInit, CodeGenFunction &CGF) {
2360 Address Addr = MaybeConvertMatrixAddress(Addr: lvalue.getAddress(), CGF,
2361 IsVector: value->getType()->isVectorTy());
2362 CGF.EmitStoreOfScalar(Value: value, Addr, Volatile: lvalue.isVolatile(), Ty: lvalue.getType(),
2363 BaseInfo: lvalue.getBaseInfo(), TBAAInfo: lvalue.getTBAAInfo(), isInit,
2364 isNontemporal: lvalue.isNontemporal());
2365}
2366
2367void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr,
2368 bool Volatile, QualType Ty,
2369 LValueBaseInfo BaseInfo,
2370 TBAAAccessInfo TBAAInfo,
2371 bool isInit, bool isNontemporal) {
2372 if (auto *GV = dyn_cast<llvm::GlobalValue>(Val: Addr.getBasePointer()))
2373 if (GV->isThreadLocal())
2374 Addr = Addr.withPointer(NewPointer: Builder.CreateThreadLocalAddress(Ptr: GV),
2375 IsKnownNonNull: NotKnownNonNull);
2376
2377 // Handles vectors of sizes that are likely to be expanded to a larger size
2378 // to optimize performance.
2379 llvm::Type *SrcTy = Value->getType();
2380 if (const auto *ClangVecTy = Ty->getAs<VectorType>()) {
2381 if (auto *VecTy = dyn_cast<llvm::FixedVectorType>(Val: SrcTy)) {
2382 auto *NewVecTy =
2383 CGM.getABIInfo().getOptimalVectorMemoryType(T: VecTy, Opt: getLangOpts());
2384 if (!ClangVecTy->isPackedVectorBoolType(ctx: getContext()) &&
2385 VecTy != NewVecTy) {
2386 SmallVector<int, 16> Mask(NewVecTy->getNumElements(),
2387 VecTy->getNumElements());
2388 std::iota(first: Mask.begin(), last: Mask.begin() + VecTy->getNumElements(), value: 0);
2389 // Use undef instead of poison for the padding lanes, to make sure no
2390 // padding bits are poisoned, which may break coercion.
2391 Value = Builder.CreateShuffleVector(V1: Value, V2: llvm::UndefValue::get(T: VecTy),
2392 Mask, Name: "extractVec");
2393 SrcTy = NewVecTy;
2394 }
2395 if (Addr.getElementType() != SrcTy)
2396 Addr = Addr.withElementType(ElemTy: SrcTy);
2397 }
2398 }
2399
2400 Value = EmitToMemory(Value, Ty);
2401
2402 LValue AtomicLValue =
2403 LValue::MakeAddr(Addr, type: Ty, Context&: getContext(), BaseInfo, TBAAInfo);
2404 if (Ty->isAtomicType() ||
2405 (!isInit && LValueIsSuitableForInlineAtomic(Src: AtomicLValue))) {
2406 EmitAtomicStore(rvalue: RValue::get(V: Value), lvalue: AtomicLValue, isInit);
2407 return;
2408 }
2409
2410 llvm::StoreInst *Store = Builder.CreateStore(Val: Value, Addr, IsVolatile: Volatile);
2411 addInstToCurrentSourceAtom(KeyInstruction: Store, Backup: Value);
2412
2413 if (isNontemporal) {
2414 llvm::MDNode *Node =
2415 llvm::MDNode::get(Context&: Store->getContext(),
2416 MDs: llvm::ConstantAsMetadata::get(C: Builder.getInt32(C: 1)));
2417 Store->setMetadata(KindID: llvm::LLVMContext::MD_nontemporal, Node);
2418 }
2419
2420 CGM.DecorateInstructionWithTBAA(Inst: Store, TBAAInfo);
2421}
2422
2423void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
2424 bool isInit) {
2425 if (lvalue.getType()->isConstantMatrixType()) {
2426 EmitStoreOfMatrixScalar(value, lvalue, isInit, CGF&: *this);
2427 return;
2428 }
2429
2430 EmitStoreOfScalar(Value: value, Addr: lvalue.getAddress(), Volatile: lvalue.isVolatile(),
2431 Ty: lvalue.getType(), BaseInfo: lvalue.getBaseInfo(),
2432 TBAAInfo: lvalue.getTBAAInfo(), isInit, isNontemporal: lvalue.isNontemporal());
2433}
2434
2435// Emit a load of a LValue of matrix type. This may require casting the pointer
2436// to memory address (ArrayType) to a pointer to the value type (VectorType).
2437static RValue EmitLoadOfMatrixLValue(LValue LV, SourceLocation Loc,
2438 CodeGenFunction &CGF) {
2439 assert(LV.getType()->isConstantMatrixType());
2440 RawAddress DestAddr = LV.getAddress();
2441
2442 // HLSL constant buffers may pad matrix layouts, so copy elements into a
2443 // non-padded local alloca before loading.
2444 if (CGF.getLangOpts().HLSL &&
2445 LV.getType().getAddressSpace() == LangAS::hlsl_constant)
2446 DestAddr =
2447 CGF.CGM.getHLSLRuntime().createBufferMatrixTempAddress(LV, Loc, CGF);
2448
2449 Address Addr = MaybeConvertMatrixAddress(Addr: DestAddr, CGF);
2450 LV.setAddress(Addr);
2451 return RValue::get(V: CGF.EmitLoadOfScalar(lvalue: LV, Loc));
2452}
2453
2454RValue CodeGenFunction::EmitLoadOfAnyValue(LValue LV, AggValueSlot Slot,
2455 SourceLocation Loc) {
2456 QualType Ty = LV.getType();
2457 switch (getEvaluationKind(T: Ty)) {
2458 case TEK_Scalar:
2459 return EmitLoadOfLValue(V: LV, Loc);
2460 case TEK_Complex:
2461 return RValue::getComplex(C: EmitLoadOfComplex(src: LV, loc: Loc));
2462 case TEK_Aggregate:
2463 EmitAggFinalDestCopy(Type: Ty, Dest: Slot, Src: LV, SrcKind: EVK_NonRValue);
2464 return Slot.asRValue();
2465 }
2466 llvm_unreachable("bad evaluation kind");
2467}
2468
2469/// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
2470/// method emits the address of the lvalue, then loads the result as an rvalue,
2471/// returning the rvalue.
2472RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
2473 // Load from __ptrauth.
2474 if (PointerAuthQualifier PtrAuth = LV.getQuals().getPointerAuth()) {
2475 LV.getQuals().removePointerAuth();
2476 llvm::Value *Value = EmitLoadOfLValue(LV, Loc).getScalarVal();
2477 return RValue::get(V: EmitPointerAuthUnqualify(Qualifier: PtrAuth, Pointer: Value, PointerType: LV.getType(),
2478 StorageAddress: LV.getAddress(),
2479 /*known nonnull*/ IsKnownNonNull: false));
2480 }
2481
2482 if (LV.isObjCWeak()) {
2483 // load of a __weak object.
2484 Address AddrWeakObj = LV.getAddress();
2485 return RValue::get(V: CGM.getObjCRuntime().EmitObjCWeakRead(CGF&: *this,
2486 AddrWeakObj));
2487 }
2488 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
2489 // In MRC mode, we do a load+autorelease.
2490 if (!getLangOpts().ObjCAutoRefCount) {
2491 return RValue::get(V: EmitARCLoadWeak(addr: LV.getAddress()));
2492 }
2493
2494 // In ARC mode, we load retained and then consume the value.
2495 llvm::Value *Object = EmitARCLoadWeakRetained(addr: LV.getAddress());
2496 Object = EmitObjCConsumeObject(T: LV.getType(), Ptr: Object);
2497 return RValue::get(V: Object);
2498 }
2499
2500 if (LV.isSimple()) {
2501 assert(!LV.getType()->isFunctionType());
2502
2503 if (LV.getType()->isConstantMatrixType())
2504 return EmitLoadOfMatrixLValue(LV, Loc, CGF&: *this);
2505
2506 // Everything needs a load.
2507 return RValue::get(V: EmitLoadOfScalar(lvalue: LV, Loc));
2508 }
2509
2510 if (LV.isVectorElt()) {
2511 llvm::LoadInst *Load = Builder.CreateLoad(Addr: LV.getVectorAddress(),
2512 IsVolatile: LV.isVolatileQualified());
2513 llvm::Value *Elt =
2514 Builder.CreateExtractElement(Vec: Load, Idx: LV.getVectorIdx(), Name: "vecext");
2515 return RValue::get(V: EmitFromMemory(Value: Elt, Ty: LV.getType()));
2516 }
2517
2518 // If this is a reference to a subset of the elements of a vector, either
2519 // shuffle the input or extract/insert them as appropriate.
2520 if (LV.isExtVectorElt()) {
2521 return EmitLoadOfExtVectorElementLValue(V: LV);
2522 }
2523
2524 // Global Register variables always invoke intrinsics
2525 if (LV.isGlobalReg())
2526 return EmitLoadOfGlobalRegLValue(LV);
2527
2528 if (LV.isMatrixElt()) {
2529 llvm::Value *Idx = LV.getMatrixIdx();
2530 QualType EltTy = LV.getType();
2531 if (const auto *MatTy = EltTy->getAs<ConstantMatrixType>()) {
2532 EltTy = MatTy->getElementType();
2533 if (CGM.getCodeGenOpts().OptimizationLevel > 0) {
2534 llvm::MatrixBuilder MB(Builder);
2535 MB.CreateIndexAssumption(Idx, NumElements: MatTy->getNumElementsFlattened());
2536 }
2537 }
2538 llvm::LoadInst *Load =
2539 Builder.CreateLoad(Addr: LV.getMatrixAddress(), IsVolatile: LV.isVolatileQualified());
2540 llvm::Value *Elt = Builder.CreateExtractElement(Vec: Load, Idx, Name: "matrixext");
2541 return RValue::get(V: EmitFromMemory(Value: Elt, Ty: EltTy));
2542 }
2543 if (LV.isMatrixRow()) {
2544 QualType MatTy = LV.getType();
2545 const ConstantMatrixType *MT = MatTy->castAs<ConstantMatrixType>();
2546
2547 unsigned NumRows = MT->getNumRows();
2548 unsigned NumCols = MT->getNumColumns();
2549 unsigned NumLanes = NumCols;
2550 llvm::Value *MatrixVec = EmitLoadOfScalar(lvalue: LV, Loc);
2551 llvm::Value *Row = LV.getMatrixRowIdx();
2552 llvm::Type *ElemTy = ConvertType(T: MT->getElementType());
2553 llvm::Constant *ColConstsIndices = nullptr;
2554 llvm::MatrixBuilder MB(Builder);
2555
2556 if (LV.isMatrixRowSwizzle()) {
2557 ColConstsIndices = LV.getMatrixRowElts();
2558 NumLanes = llvm::cast<llvm::FixedVectorType>(Val: ColConstsIndices->getType())
2559 ->getNumElements();
2560 }
2561
2562 llvm::Type *RowTy = llvm::FixedVectorType::get(ElementType: ElemTy, NumElts: NumLanes);
2563 llvm::Value *Result = llvm::PoisonValue::get(T: RowTy); // <NumLanes x T>
2564
2565 for (unsigned Col = 0; Col < NumLanes; ++Col) {
2566 llvm::Value *ColIdx;
2567 if (ColConstsIndices)
2568 ColIdx = ColConstsIndices->getAggregateElement(Elt: Col);
2569 else
2570 ColIdx = llvm::ConstantInt::get(Ty: Row->getType(), V: Col);
2571 bool IsMatrixRowMajor = getLangOpts().getDefaultMatrixMemoryLayout() ==
2572 LangOptions::MatrixMemoryLayout::MatrixRowMajor;
2573 llvm::Value *EltIndex =
2574 MB.CreateIndex(RowIdx: Row, ColumnIdx: ColIdx, NumRows, NumCols, IsMatrixRowMajor);
2575 llvm::Value *Elt = Builder.CreateExtractElement(Vec: MatrixVec, Idx: EltIndex);
2576 llvm::Value *Lane = llvm::ConstantInt::get(Ty: Builder.getInt32Ty(), V: Col);
2577 Result = Builder.CreateInsertElement(Vec: Result, NewElt: Elt, Idx: Lane);
2578 }
2579
2580 return RValue::get(V: Result);
2581 }
2582
2583 assert(LV.isBitField() && "Unknown LValue type!");
2584 return EmitLoadOfBitfieldLValue(LV, Loc);
2585}
2586
2587RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
2588 SourceLocation Loc) {
2589 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
2590
2591 // Get the output type.
2592 llvm::Type *ResLTy = ConvertType(T: LV.getType());
2593
2594 Address Ptr = LV.getBitFieldAddress();
2595 llvm::Value *Val =
2596 Builder.CreateLoad(Addr: Ptr, IsVolatile: LV.isVolatileQualified(), Name: "bf.load");
2597
2598 bool UseVolatile = LV.isVolatileQualified() &&
2599 Info.VolatileStorageSize != 0 && isAAPCS(TargetInfo: CGM.getTarget());
2600 const unsigned Offset = UseVolatile ? Info.VolatileOffset : Info.Offset;
2601 const unsigned StorageSize =
2602 UseVolatile ? Info.VolatileStorageSize : Info.StorageSize;
2603 if (Info.IsSigned) {
2604 assert(static_cast<unsigned>(Offset + Info.Size) <= StorageSize);
2605 unsigned HighBits = StorageSize - Offset - Info.Size;
2606 if (HighBits)
2607 Val = Builder.CreateShl(LHS: Val, RHS: HighBits, Name: "bf.shl");
2608 if (Offset + HighBits)
2609 Val = Builder.CreateAShr(LHS: Val, RHS: Offset + HighBits, Name: "bf.ashr");
2610 } else {
2611 if (Offset)
2612 Val = Builder.CreateLShr(LHS: Val, RHS: Offset, Name: "bf.lshr");
2613 if (static_cast<unsigned>(Offset) + Info.Size < StorageSize)
2614 Val = Builder.CreateAnd(
2615 LHS: Val, RHS: llvm::APInt::getLowBitsSet(numBits: StorageSize, loBitsSet: Info.Size), Name: "bf.clear");
2616 }
2617 Val = Builder.CreateIntCast(V: Val, DestTy: ResLTy, isSigned: Info.IsSigned, Name: "bf.cast");
2618 EmitScalarRangeCheck(Value: Val, Ty: LV.getType(), Loc);
2619 return RValue::get(V: Val);
2620}
2621
2622// If this is a reference to a subset of the elements of a vector, create an
2623// appropriate shufflevector.
2624RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
2625 llvm::Value *Vec = Builder.CreateLoad(Addr: LV.getExtVectorAddress(),
2626 IsVolatile: LV.isVolatileQualified());
2627
2628 // HLSL allows treating scalars as one-element vectors. Converting the scalar
2629 // IR value to a vector here allows the rest of codegen to behave as normal.
2630 if (getLangOpts().HLSL && !Vec->getType()->isVectorTy()) {
2631 llvm::Type *DstTy = llvm::FixedVectorType::get(ElementType: Vec->getType(), NumElts: 1);
2632 llvm::Value *Zero = llvm::Constant::getNullValue(Ty: CGM.Int64Ty);
2633 Vec = Builder.CreateInsertElement(VecTy: DstTy, NewElt: Vec, Idx: Zero, Name: "cast.splat");
2634 }
2635
2636 const llvm::Constant *Elts = LV.getExtVectorElts();
2637
2638 // If the result of the expression is a non-vector type, we must be extracting
2639 // a single element. Just codegen as an extractelement.
2640 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
2641 if (!ExprVT) {
2642 unsigned InIdx = getAccessedFieldNo(Idx: 0, Elts);
2643 llvm::Value *Elt = llvm::ConstantInt::get(Ty: SizeTy, V: InIdx);
2644
2645 llvm::Value *Element = Builder.CreateExtractElement(Vec, Idx: Elt);
2646
2647 llvm::Type *LVTy = ConvertType(T: LV.getType());
2648 if (Element->getType()->getPrimitiveSizeInBits() >
2649 LVTy->getPrimitiveSizeInBits())
2650 Element = Builder.CreateTrunc(V: Element, DestTy: LVTy);
2651
2652 return RValue::get(V: Element);
2653 }
2654
2655 // Always use shuffle vector to try to retain the original program structure
2656 unsigned NumResultElts = ExprVT->getNumElements();
2657
2658 SmallVector<int, 4> Mask;
2659 for (unsigned i = 0; i != NumResultElts; ++i)
2660 Mask.push_back(Elt: getAccessedFieldNo(Idx: i, Elts));
2661
2662 Vec = Builder.CreateShuffleVector(V: Vec, Mask);
2663
2664 if (LV.getType()->isExtVectorBoolType())
2665 Vec = Builder.CreateTrunc(V: Vec, DestTy: ConvertType(T: LV.getType()), Name: "truncv");
2666
2667 return RValue::get(V: Vec);
2668}
2669
2670/// Generates lvalue for partial ext_vector access.
2671Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
2672 Address VectorAddress = LV.getExtVectorAddress();
2673 QualType EQT = LV.getType()->castAs<VectorType>()->getElementType();
2674 llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(T: EQT);
2675
2676 Address CastToPointerElement = VectorAddress.withElementType(ElemTy: VectorElementTy);
2677
2678 const llvm::Constant *Elts = LV.getExtVectorElts();
2679 unsigned ix = getAccessedFieldNo(Idx: 0, Elts);
2680
2681 Address VectorBasePtrPlusIx =
2682 Builder.CreateConstInBoundsGEP(Addr: CastToPointerElement, Index: ix,
2683 Name: "vector.elt");
2684
2685 return VectorBasePtrPlusIx;
2686}
2687
2688/// Load of global named registers are always calls to intrinsics.
2689RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
2690 assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
2691 "Bad type for register variable");
2692 llvm::MDNode *RegName = cast<llvm::MDNode>(
2693 Val: cast<llvm::MetadataAsValue>(Val: LV.getGlobalReg())->getMetadata());
2694
2695 // We accept integer and pointer types only
2696 llvm::Type *OrigTy = CGM.getTypes().ConvertType(T: LV.getType());
2697 llvm::Type *Ty = OrigTy;
2698 if (OrigTy->isPointerTy())
2699 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
2700 llvm::Type *Types[] = { Ty };
2701
2702 llvm::Function *F = CGM.getIntrinsic(IID: llvm::Intrinsic::read_register, Tys: Types);
2703 llvm::Value *Call = Builder.CreateCall(
2704 Callee: F, Args: llvm::MetadataAsValue::get(Context&: Ty->getContext(), MD: RegName));
2705 if (OrigTy->isPointerTy())
2706 Call = Builder.CreateIntToPtr(V: Call, DestTy: OrigTy);
2707 return RValue::get(V: Call);
2708}
2709
2710/// EmitStoreThroughLValue - Store the specified rvalue into the specified
2711/// lvalue, where both are guaranteed to the have the same type, and that type
2712/// is 'Ty'.
2713void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
2714 bool isInit) {
2715 if (!Dst.isSimple()) {
2716 if (Dst.isVectorElt()) {
2717 if (getLangOpts().HLSL) {
2718 // HLSL allows direct access to vector elements, so storing to
2719 // individual elements of a vector through VectorElt is handled as
2720 // separate store instructions.
2721 Address DstAddr = Dst.getVectorAddress();
2722 llvm::Type *DestAddrTy = DstAddr.getElementType();
2723 llvm::Type *ElemTy = DestAddrTy->getScalarType();
2724 CharUnits ElemAlign = CharUnits::fromQuantity(
2725 Quantity: CGM.getDataLayout().getPrefTypeAlign(Ty: ElemTy));
2726
2727 assert(ElemTy->getScalarSizeInBits() >= 8 &&
2728 "vector element type must be at least byte-sized");
2729
2730 llvm::Value *Val = Src.getScalarVal();
2731 if (Val->getType()->getPrimitiveSizeInBits() <
2732 ElemTy->getScalarSizeInBits())
2733 Val = Builder.CreateZExt(V: Val, DestTy: ElemTy->getScalarType());
2734
2735 llvm::Value *Idx = Dst.getVectorIdx();
2736 llvm::Value *Zero = llvm::ConstantInt::get(Ty: Int32Ty, V: 0);
2737 Address DstElemAddr =
2738 Builder.CreateGEP(Addr: DstAddr, IdxList: {Zero, Idx}, ElementType: DestAddrTy, Align: ElemAlign);
2739 Builder.CreateStore(Val, Addr: DstElemAddr, IsVolatile: Dst.isVolatileQualified());
2740 return;
2741 }
2742
2743 // Read/modify/write the vector, inserting the new element.
2744 llvm::Value *Vec = Builder.CreateLoad(Addr: Dst.getVectorAddress(),
2745 IsVolatile: Dst.isVolatileQualified());
2746 llvm::Type *VecTy = Vec->getType();
2747 llvm::Value *SrcVal = Src.getScalarVal();
2748
2749 if (SrcVal->getType()->getPrimitiveSizeInBits() <
2750 VecTy->getScalarSizeInBits())
2751 SrcVal = Builder.CreateZExt(V: SrcVal, DestTy: VecTy->getScalarType());
2752
2753 auto *IRStoreTy = dyn_cast<llvm::IntegerType>(Val: Vec->getType());
2754 if (IRStoreTy) {
2755 auto *IRVecTy = llvm::FixedVectorType::get(
2756 ElementType: Builder.getInt1Ty(), NumElts: IRStoreTy->getPrimitiveSizeInBits());
2757 Vec = Builder.CreateBitCast(V: Vec, DestTy: IRVecTy);
2758 // iN --> <N x i1>.
2759 }
2760
2761 // Allow inserting `<1 x T>` into an `<N x T>`. It can happen with scalar
2762 // types which are mapped to vector LLVM IR types (e.g. for implementing
2763 // an ABI).
2764 if (auto *EltTy = dyn_cast<llvm::FixedVectorType>(Val: SrcVal->getType());
2765 EltTy && EltTy->getNumElements() == 1)
2766 SrcVal = Builder.CreateBitCast(V: SrcVal, DestTy: EltTy->getElementType());
2767
2768 Vec = Builder.CreateInsertElement(Vec, NewElt: SrcVal, Idx: Dst.getVectorIdx(),
2769 Name: "vecins");
2770 if (IRStoreTy) {
2771 // <N x i1> --> <iN>.
2772 Vec = Builder.CreateBitCast(V: Vec, DestTy: IRStoreTy);
2773 }
2774
2775 auto *I = Builder.CreateStore(Val: Vec, Addr: Dst.getVectorAddress(),
2776 IsVolatile: Dst.isVolatileQualified());
2777 addInstToCurrentSourceAtom(KeyInstruction: I, Backup: Vec);
2778 return;
2779 }
2780
2781 // If this is an update of extended vector elements, insert them as
2782 // appropriate.
2783 if (Dst.isExtVectorElt())
2784 return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
2785
2786 if (Dst.isGlobalReg())
2787 return EmitStoreThroughGlobalRegLValue(Src, Dst);
2788
2789 if (Dst.isMatrixElt()) {
2790 if (getLangOpts().HLSL) {
2791 // HLSL allows direct access to matrix elements, so storing to
2792 // individual elements of a matrix through MatrixElt is handled as
2793 // separate store instructions.
2794 Address DstAddr = Dst.getMatrixAddress();
2795 llvm::Type *DestAddrTy = DstAddr.getElementType();
2796 llvm::Type *ElemTy = DestAddrTy->getScalarType();
2797 CharUnits ElemAlign = CharUnits::fromQuantity(
2798 Quantity: CGM.getDataLayout().getPrefTypeAlign(Ty: ElemTy));
2799
2800 assert(ElemTy->getScalarSizeInBits() >= 8 &&
2801 "matrix element type must be at least byte-sized");
2802
2803 llvm::Value *Val = Src.getScalarVal();
2804 if (Val->getType()->getPrimitiveSizeInBits() <
2805 ElemTy->getScalarSizeInBits())
2806 Val = Builder.CreateZExt(V: Val, DestTy: ElemTy->getScalarType());
2807
2808 llvm::Value *Idx = Dst.getMatrixIdx();
2809 llvm::Value *Zero = llvm::ConstantInt::get(Ty: Int32Ty, V: 0);
2810 Address DstElemAddr =
2811 Builder.CreateGEP(Addr: DstAddr, IdxList: {Zero, Idx}, ElementType: DestAddrTy, Align: ElemAlign);
2812 Builder.CreateStore(Val, Addr: DstElemAddr, IsVolatile: Dst.isVolatileQualified());
2813 return;
2814 }
2815
2816 llvm::Value *Idx = Dst.getMatrixIdx();
2817 if (CGM.getCodeGenOpts().OptimizationLevel > 0) {
2818 const auto *const MatTy = Dst.getType()->castAs<ConstantMatrixType>();
2819 llvm::MatrixBuilder MB(Builder);
2820 MB.CreateIndexAssumption(Idx, NumElements: MatTy->getNumElementsFlattened());
2821 }
2822 llvm::Instruction *Load = Builder.CreateLoad(Addr: Dst.getMatrixAddress());
2823 llvm::Value *InsertVal = Src.getScalarVal();
2824 llvm::Value *Vec =
2825 Builder.CreateInsertElement(Vec: Load, NewElt: InsertVal, Idx, Name: "matins");
2826 auto *I = Builder.CreateStore(Val: Vec, Addr: Dst.getMatrixAddress(),
2827 IsVolatile: Dst.isVolatileQualified());
2828 addInstToCurrentSourceAtom(KeyInstruction: I, Backup: Vec);
2829 return;
2830 }
2831 if (Dst.isMatrixRow()) {
2832 // NOTE: Since there are no other languages that implement matrix single
2833 // subscripting, the logic here is specific to HLSL which allows
2834 // per-element stores to rows of matrices.
2835 assert(getLangOpts().HLSL &&
2836 "Store through matrix row LValues is only implemented for HLSL!");
2837 QualType MatTy = Dst.getType();
2838 const ConstantMatrixType *MT = MatTy->castAs<ConstantMatrixType>();
2839
2840 unsigned NumRows = MT->getNumRows();
2841 unsigned NumCols = MT->getNumColumns();
2842 unsigned NumLanes = NumCols;
2843
2844 Address DstAddr = Dst.getMatrixAddress();
2845 llvm::Type *DestAddrTy = DstAddr.getElementType();
2846 llvm::Type *ElemTy = DestAddrTy->getScalarType();
2847 CharUnits ElemAlign =
2848 CharUnits::fromQuantity(Quantity: CGM.getDataLayout().getPrefTypeAlign(Ty: ElemTy));
2849
2850 assert(ElemTy->getScalarSizeInBits() >= 8 &&
2851 "matrix element type must be at least byte-sized");
2852
2853 llvm::Value *RowVal = Src.getScalarVal();
2854 if (RowVal->getType()->getScalarType()->getPrimitiveSizeInBits() <
2855 ElemTy->getScalarSizeInBits()) {
2856 auto *RowValVecTy = cast<llvm::FixedVectorType>(Val: RowVal->getType());
2857 llvm::Type *StorageElmTy = llvm::FixedVectorType::get(
2858 ElementType: ElemTy->getScalarType(), NumElts: RowValVecTy->getNumElements());
2859 RowVal = Builder.CreateZExt(V: RowVal, DestTy: StorageElmTy);
2860 }
2861
2862 llvm::MatrixBuilder MB(Builder);
2863
2864 llvm::Constant *ColConstsIndices = nullptr;
2865 if (Dst.isMatrixRowSwizzle()) {
2866 ColConstsIndices = Dst.getMatrixRowElts();
2867 NumLanes =
2868 llvm::cast<llvm::FixedVectorType>(Val: ColConstsIndices->getType())
2869 ->getNumElements();
2870 }
2871
2872 llvm::Value *Row = Dst.getMatrixRowIdx();
2873 for (unsigned Col = 0; Col < NumLanes; ++Col) {
2874 llvm::Value *ColIdx;
2875 if (ColConstsIndices)
2876 ColIdx = ColConstsIndices->getAggregateElement(Elt: Col);
2877 else
2878 ColIdx = llvm::ConstantInt::get(Ty: Row->getType(), V: Col);
2879 bool IsMatrixRowMajor = getLangOpts().getDefaultMatrixMemoryLayout() ==
2880 LangOptions::MatrixMemoryLayout::MatrixRowMajor;
2881 llvm::Value *EltIndex =
2882 MB.CreateIndex(RowIdx: Row, ColumnIdx: ColIdx, NumRows, NumCols, IsMatrixRowMajor);
2883 llvm::Value *Lane = llvm::ConstantInt::get(Ty: Builder.getInt32Ty(), V: Col);
2884 llvm::Value *Zero = llvm::ConstantInt::get(Ty: Int32Ty, V: 0);
2885 llvm::Value *NewElt = Builder.CreateExtractElement(Vec: RowVal, Idx: Lane);
2886 Address DstElemAddr =
2887 Builder.CreateGEP(Addr: DstAddr, IdxList: {Zero, EltIndex}, ElementType: DestAddrTy, Align: ElemAlign);
2888 Builder.CreateStore(Val: NewElt, Addr: DstElemAddr, IsVolatile: Dst.isVolatileQualified());
2889 }
2890
2891 return;
2892 }
2893
2894 assert(Dst.isBitField() && "Unknown LValue type");
2895 return EmitStoreThroughBitfieldLValue(Src, Dst);
2896 }
2897
2898 // Handle __ptrauth qualification by re-signing the value.
2899 if (PointerAuthQualifier PointerAuth = Dst.getQuals().getPointerAuth()) {
2900 Src = RValue::get(V: EmitPointerAuthQualify(Qualifier: PointerAuth, Pointer: Src.getScalarVal(),
2901 ValueType: Dst.getType(), StorageAddress: Dst.getAddress(),
2902 /*known nonnull*/ IsKnownNonNull: false));
2903 }
2904
2905 // There's special magic for assigning into an ARC-qualified l-value.
2906 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
2907 switch (Lifetime) {
2908 case Qualifiers::OCL_None:
2909 llvm_unreachable("present but none");
2910
2911 case Qualifiers::OCL_ExplicitNone:
2912 // nothing special
2913 break;
2914
2915 case Qualifiers::OCL_Strong:
2916 if (isInit) {
2917 Src = RValue::get(V: EmitARCRetain(type: Dst.getType(), value: Src.getScalarVal()));
2918 break;
2919 }
2920 EmitARCStoreStrong(lvalue: Dst, value: Src.getScalarVal(), /*ignore*/ resultIgnored: true);
2921 return;
2922
2923 case Qualifiers::OCL_Weak:
2924 if (isInit)
2925 // Initialize and then skip the primitive store.
2926 EmitARCInitWeak(addr: Dst.getAddress(), value: Src.getScalarVal());
2927 else
2928 EmitARCStoreWeak(addr: Dst.getAddress(), value: Src.getScalarVal(),
2929 /*ignore*/ ignored: true);
2930 return;
2931
2932 case Qualifiers::OCL_Autoreleasing:
2933 Src = RValue::get(V: EmitObjCExtendObjectLifetime(T: Dst.getType(),
2934 Ptr: Src.getScalarVal()));
2935 // fall into the normal path
2936 break;
2937 }
2938 }
2939
2940 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
2941 // load of a __weak object.
2942 Address LvalueDst = Dst.getAddress();
2943 llvm::Value *src = Src.getScalarVal();
2944 CGM.getObjCRuntime().EmitObjCWeakAssign(CGF&: *this, src, dest: LvalueDst);
2945 return;
2946 }
2947
2948 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
2949 // load of a __strong object.
2950 Address LvalueDst = Dst.getAddress();
2951 llvm::Value *src = Src.getScalarVal();
2952 if (Dst.isObjCIvar()) {
2953 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
2954 llvm::Type *ResultType = IntPtrTy;
2955 Address dst = EmitPointerWithAlignment(E: Dst.getBaseIvarExp());
2956 llvm::Value *RHS = dst.emitRawPointer(CGF&: *this);
2957 RHS = Builder.CreatePtrToInt(V: RHS, DestTy: ResultType, Name: "sub.ptr.rhs.cast");
2958 llvm::Value *LHS = Builder.CreatePtrToInt(V: LvalueDst.emitRawPointer(CGF&: *this),
2959 DestTy: ResultType, Name: "sub.ptr.lhs.cast");
2960 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, Name: "ivar.offset");
2961 CGM.getObjCRuntime().EmitObjCIvarAssign(CGF&: *this, src, dest: dst, ivarOffset: BytesBetween);
2962 } else if (Dst.isGlobalObjCRef()) {
2963 CGM.getObjCRuntime().EmitObjCGlobalAssign(CGF&: *this, src, dest: LvalueDst,
2964 threadlocal: Dst.isThreadLocalRef());
2965 }
2966 else
2967 CGM.getObjCRuntime().EmitObjCStrongCastAssign(CGF&: *this, src, dest: LvalueDst);
2968 return;
2969 }
2970
2971 assert(Src.isScalar() && "Can't emit an agg store with this method");
2972 EmitStoreOfScalar(value: Src.getScalarVal(), lvalue: Dst, isInit);
2973}
2974
2975void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
2976 llvm::Value **Result) {
2977 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
2978 llvm::Type *ResLTy = convertTypeForLoadStore(ASTTy: Dst.getType());
2979 Address Ptr = Dst.getBitFieldAddress();
2980
2981 // Get the source value, truncated to the width of the bit-field.
2982 llvm::Value *SrcVal = Src.getScalarVal();
2983
2984 // Cast the source to the storage type and shift it into place.
2985 SrcVal = Builder.CreateIntCast(V: SrcVal, DestTy: Ptr.getElementType(),
2986 /*isSigned=*/false);
2987 llvm::Value *MaskedVal = SrcVal;
2988
2989 const bool UseVolatile =
2990 CGM.getCodeGenOpts().AAPCSBitfieldWidth && Dst.isVolatileQualified() &&
2991 Info.VolatileStorageSize != 0 && isAAPCS(TargetInfo: CGM.getTarget());
2992 const unsigned StorageSize =
2993 UseVolatile ? Info.VolatileStorageSize : Info.StorageSize;
2994 const unsigned Offset = UseVolatile ? Info.VolatileOffset : Info.Offset;
2995 // See if there are other bits in the bitfield's storage we'll need to load
2996 // and mask together with source before storing.
2997 if (StorageSize != Info.Size) {
2998 assert(StorageSize > Info.Size && "Invalid bitfield size.");
2999 llvm::Value *Val =
3000 Builder.CreateLoad(Addr: Ptr, IsVolatile: Dst.isVolatileQualified(), Name: "bf.load");
3001
3002 // Mask the source value as needed.
3003 if (!Dst.getType()->hasBooleanRepresentation())
3004 SrcVal = Builder.CreateAnd(
3005 LHS: SrcVal, RHS: llvm::APInt::getLowBitsSet(numBits: StorageSize, loBitsSet: Info.Size),
3006 Name: "bf.value");
3007 MaskedVal = SrcVal;
3008 if (Offset)
3009 SrcVal = Builder.CreateShl(LHS: SrcVal, RHS: Offset, Name: "bf.shl");
3010
3011 // Mask out the original value.
3012 Val = Builder.CreateAnd(
3013 LHS: Val, RHS: ~llvm::APInt::getBitsSet(numBits: StorageSize, loBit: Offset, hiBit: Offset + Info.Size),
3014 Name: "bf.clear");
3015
3016 // Or together the unchanged values and the source value.
3017 SrcVal = Builder.CreateOr(LHS: Val, RHS: SrcVal, Name: "bf.set");
3018 } else {
3019 assert(Offset == 0);
3020 // According to the AACPS:
3021 // When a volatile bit-field is written, and its container does not overlap
3022 // with any non-bit-field member, its container must be read exactly once
3023 // and written exactly once using the access width appropriate to the type
3024 // of the container. The two accesses are not atomic.
3025 if (Dst.isVolatileQualified() && isAAPCS(TargetInfo: CGM.getTarget()) &&
3026 CGM.getCodeGenOpts().ForceAAPCSBitfieldLoad)
3027 Builder.CreateLoad(Addr: Ptr, IsVolatile: true, Name: "bf.load");
3028 }
3029
3030 // Write the new value back out.
3031 auto *I = Builder.CreateStore(Val: SrcVal, Addr: Ptr, IsVolatile: Dst.isVolatileQualified());
3032 addInstToCurrentSourceAtom(KeyInstruction: I, Backup: SrcVal);
3033
3034 // Return the new value of the bit-field, if requested.
3035 if (Result) {
3036 llvm::Value *ResultVal = MaskedVal;
3037
3038 // Sign extend the value if needed.
3039 if (Info.IsSigned) {
3040 assert(Info.Size <= StorageSize);
3041 unsigned HighBits = StorageSize - Info.Size;
3042 if (HighBits) {
3043 ResultVal = Builder.CreateShl(LHS: ResultVal, RHS: HighBits, Name: "bf.result.shl");
3044 ResultVal = Builder.CreateAShr(LHS: ResultVal, RHS: HighBits, Name: "bf.result.ashr");
3045 }
3046 }
3047
3048 ResultVal = Builder.CreateIntCast(V: ResultVal, DestTy: ResLTy, isSigned: Info.IsSigned,
3049 Name: "bf.result.cast");
3050 *Result = EmitFromMemory(Value: ResultVal, Ty: Dst.getType());
3051 }
3052}
3053
3054void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
3055 LValue Dst) {
3056 llvm::Value *SrcVal = Src.getScalarVal();
3057 Address DstAddr = Dst.getExtVectorAddress();
3058 const llvm::Constant *Elts = Dst.getExtVectorElts();
3059 if (DstAddr.getElementType()->getScalarSizeInBits() >
3060 SrcVal->getType()->getScalarSizeInBits())
3061 SrcVal = Builder.CreateZExt(
3062 V: SrcVal, DestTy: convertTypeForLoadStore(ASTTy: Dst.getType(), LLVMTy: SrcVal->getType()));
3063
3064 if (getLangOpts().HLSL) {
3065 llvm::Type *DestAddrTy = DstAddr.getElementType();
3066 // HLSL allows storing to scalar values through ExtVector component LValues.
3067 // To support this we need to handle the case where the destination address
3068 // is a scalar.
3069 if (!DestAddrTy->isVectorTy()) {
3070 assert(!Dst.getType()->isVectorType() &&
3071 "this should only occur for non-vector l-values");
3072 Builder.CreateStore(Val: SrcVal, Addr: DstAddr, IsVolatile: Dst.isVolatileQualified());
3073 return;
3074 }
3075
3076 // HLSL allows direct access to vector elements, so storing to individual
3077 // elements of a vector through ExtVector is handled as separate store
3078 // instructions.
3079 // If we are updating multiple elements, Dst and Src are vectors; for
3080 // a single element update they are scalars.
3081 const VectorType *VTy = Dst.getType()->getAs<VectorType>();
3082 unsigned NumSrcElts = VTy ? VTy->getNumElements() : 1;
3083 CharUnits ElemAlign = CharUnits::fromQuantity(
3084 Quantity: CGM.getDataLayout().getPrefTypeAlign(Ty: DestAddrTy->getScalarType()));
3085 llvm::Value *Zero = llvm::ConstantInt::get(Ty: Int32Ty, V: 0);
3086
3087 for (unsigned I = 0; I != NumSrcElts; ++I) {
3088 llvm::Value *Val = VTy ? Builder.CreateExtractElement(
3089 Vec: SrcVal, Idx: llvm::ConstantInt::get(Ty: Int32Ty, V: I))
3090 : SrcVal;
3091 unsigned FieldNo = getAccessedFieldNo(Idx: I, Elts);
3092 Address DstElemAddr = Address::invalid();
3093 if (FieldNo == 0)
3094 DstElemAddr = DstAddr.withAlignment(NewAlignment: ElemAlign);
3095 else
3096 DstElemAddr = Builder.CreateGEP(
3097 Addr: DstAddr, IdxList: {Zero, llvm::ConstantInt::get(Ty: Int32Ty, V: FieldNo)},
3098 ElementType: DestAddrTy, Align: ElemAlign);
3099 Builder.CreateStore(Val, Addr: DstElemAddr, IsVolatile: Dst.isVolatileQualified());
3100 }
3101 return;
3102 }
3103
3104 // This access turns into a read/modify/write of the vector. Load the input
3105 // value now.
3106 llvm::Value *Vec = Builder.CreateLoad(Addr: DstAddr, IsVolatile: Dst.isVolatileQualified());
3107 llvm::Type *VecTy = Vec->getType();
3108
3109 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
3110 unsigned NumSrcElts = VTy->getNumElements();
3111 unsigned NumDstElts = cast<llvm::FixedVectorType>(Val: VecTy)->getNumElements();
3112 if (NumDstElts == NumSrcElts) {
3113 // Use shuffle vector is the src and destination are the same number of
3114 // elements and restore the vector mask since it is on the side it will be
3115 // stored.
3116 SmallVector<int, 4> Mask(NumDstElts);
3117 for (unsigned i = 0; i != NumSrcElts; ++i)
3118 Mask[getAccessedFieldNo(Idx: i, Elts)] = i;
3119
3120 Vec = Builder.CreateShuffleVector(V: SrcVal, Mask);
3121 } else if (NumDstElts > NumSrcElts) {
3122 // Extended the source vector to the same length and then shuffle it
3123 // into the destination.
3124 // FIXME: since we're shuffling with undef, can we just use the indices
3125 // into that? This could be simpler.
3126 SmallVector<int, 4> ExtMask;
3127 for (unsigned i = 0; i != NumSrcElts; ++i)
3128 ExtMask.push_back(Elt: i);
3129 ExtMask.resize(N: NumDstElts, NV: -1);
3130 llvm::Value *ExtSrcVal = Builder.CreateShuffleVector(V: SrcVal, Mask: ExtMask);
3131 // build identity
3132 SmallVector<int, 4> Mask;
3133 for (unsigned i = 0; i != NumDstElts; ++i)
3134 Mask.push_back(Elt: i);
3135
3136 // When the vector size is odd and .odd or .hi is used, the last element
3137 // of the Elts constant array will be one past the size of the vector.
3138 // Ignore the last element here, if it is greater than the mask size.
3139 if (getAccessedFieldNo(Idx: NumSrcElts - 1, Elts) == Mask.size())
3140 NumSrcElts--;
3141
3142 // modify when what gets shuffled in
3143 for (unsigned i = 0; i != NumSrcElts; ++i)
3144 Mask[getAccessedFieldNo(Idx: i, Elts)] = i + NumDstElts;
3145 Vec = Builder.CreateShuffleVector(V1: Vec, V2: ExtSrcVal, Mask);
3146 } else {
3147 // We should never shorten the vector
3148 llvm_unreachable("unexpected shorten vector length");
3149 }
3150 } else {
3151 // If the Src is a scalar (not a vector), and the target is a vector it must
3152 // be updating one element.
3153 unsigned InIdx = getAccessedFieldNo(Idx: 0, Elts);
3154 llvm::Value *Elt = llvm::ConstantInt::get(Ty: SizeTy, V: InIdx);
3155
3156 Vec = Builder.CreateInsertElement(Vec, NewElt: SrcVal, Idx: Elt);
3157 }
3158
3159 Builder.CreateStore(Val: Vec, Addr: Dst.getExtVectorAddress(),
3160 IsVolatile: Dst.isVolatileQualified());
3161}
3162
3163/// Store of global named registers are always calls to intrinsics.
3164void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
3165 assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
3166 "Bad type for register variable");
3167 llvm::MDNode *RegName = cast<llvm::MDNode>(
3168 Val: cast<llvm::MetadataAsValue>(Val: Dst.getGlobalReg())->getMetadata());
3169 assert(RegName && "Register LValue is not metadata");
3170
3171 // We accept integer and pointer types only
3172 llvm::Type *OrigTy = CGM.getTypes().ConvertType(T: Dst.getType());
3173 llvm::Type *Ty = OrigTy;
3174 if (OrigTy->isPointerTy())
3175 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
3176 llvm::Type *Types[] = { Ty };
3177
3178 llvm::Function *F = CGM.getIntrinsic(IID: llvm::Intrinsic::write_register, Tys: Types);
3179 llvm::Value *Value = Src.getScalarVal();
3180 if (OrigTy->isPointerTy())
3181 Value = Builder.CreatePtrToInt(V: Value, DestTy: Ty);
3182 Builder.CreateCall(
3183 Callee: F, Args: {llvm::MetadataAsValue::get(Context&: Ty->getContext(), MD: RegName), Value});
3184}
3185
3186// setObjCGCLValueClass - sets class of the lvalue for the purpose of
3187// generating write-barries API. It is currently a global, ivar,
3188// or neither.
3189static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
3190 LValue &LV,
3191 bool IsMemberAccess=false) {
3192 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
3193 return;
3194
3195 if (isa<ObjCIvarRefExpr>(Val: E)) {
3196 QualType ExpTy = E->getType();
3197 if (IsMemberAccess && ExpTy->isPointerType()) {
3198 // If ivar is a structure pointer, assigning to field of
3199 // this struct follows gcc's behavior and makes it a non-ivar
3200 // writer-barrier conservatively.
3201 ExpTy = ExpTy->castAs<PointerType>()->getPointeeType();
3202 if (ExpTy->isRecordType()) {
3203 LV.setObjCIvar(false);
3204 return;
3205 }
3206 }
3207 LV.setObjCIvar(true);
3208 auto *Exp = cast<ObjCIvarRefExpr>(Val: const_cast<Expr *>(E));
3209 LV.setBaseIvarExp(Exp->getBase());
3210 LV.setObjCArray(E->getType()->isArrayType());
3211 return;
3212 }
3213
3214 if (const auto *Exp = dyn_cast<DeclRefExpr>(Val: E)) {
3215 if (const auto *VD = dyn_cast<VarDecl>(Val: Exp->getDecl())) {
3216 if (VD->hasGlobalStorage()) {
3217 LV.setGlobalObjCRef(true);
3218 LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
3219 }
3220 }
3221 LV.setObjCArray(E->getType()->isArrayType());
3222 return;
3223 }
3224
3225 if (const auto *Exp = dyn_cast<UnaryOperator>(Val: E)) {
3226 setObjCGCLValueClass(Ctx, E: Exp->getSubExpr(), LV, IsMemberAccess);
3227 return;
3228 }
3229
3230 if (const auto *Exp = dyn_cast<ParenExpr>(Val: E)) {
3231 setObjCGCLValueClass(Ctx, E: Exp->getSubExpr(), LV, IsMemberAccess);
3232 if (LV.isObjCIvar()) {
3233 // If cast is to a structure pointer, follow gcc's behavior and make it
3234 // a non-ivar write-barrier.
3235 QualType ExpTy = E->getType();
3236 if (ExpTy->isPointerType())
3237 ExpTy = ExpTy->castAs<PointerType>()->getPointeeType();
3238 if (ExpTy->isRecordType())
3239 LV.setObjCIvar(false);
3240 }
3241 return;
3242 }
3243
3244 if (const auto *Exp = dyn_cast<GenericSelectionExpr>(Val: E)) {
3245 setObjCGCLValueClass(Ctx, E: Exp->getResultExpr(), LV);
3246 return;
3247 }
3248
3249 if (const auto *Exp = dyn_cast<ImplicitCastExpr>(Val: E)) {
3250 setObjCGCLValueClass(Ctx, E: Exp->getSubExpr(), LV, IsMemberAccess);
3251 return;
3252 }
3253
3254 if (const auto *Exp = dyn_cast<CStyleCastExpr>(Val: E)) {
3255 setObjCGCLValueClass(Ctx, E: Exp->getSubExpr(), LV, IsMemberAccess);
3256 return;
3257 }
3258
3259 if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(Val: E)) {
3260 setObjCGCLValueClass(Ctx, E: Exp->getSubExpr(), LV, IsMemberAccess);
3261 return;
3262 }
3263
3264 if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(Val: E)) {
3265 setObjCGCLValueClass(Ctx, E: Exp->getBase(), LV);
3266 if (LV.isObjCIvar() && !LV.isObjCArray())
3267 // Using array syntax to assigning to what an ivar points to is not
3268 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
3269 LV.setObjCIvar(false);
3270 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
3271 // Using array syntax to assigning to what global points to is not
3272 // same as assigning to the global itself. {id *G;} G[i] = 0;
3273 LV.setGlobalObjCRef(false);
3274 return;
3275 }
3276
3277 if (const auto *Exp = dyn_cast<MemberExpr>(Val: E)) {
3278 setObjCGCLValueClass(Ctx, E: Exp->getBase(), LV, IsMemberAccess: true);
3279 // We don't know if member is an 'ivar', but this flag is looked at
3280 // only in the context of LV.isObjCIvar().
3281 LV.setObjCArray(E->getType()->isArrayType());
3282 return;
3283 }
3284}
3285
3286static LValue EmitThreadPrivateVarDeclLValue(
3287 CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
3288 llvm::Type *RealVarTy, SourceLocation Loc) {
3289 if (CGF.CGM.getLangOpts().OpenMPIRBuilder)
3290 Addr = CodeGenFunction::OMPBuilderCBHelpers::getAddrOfThreadPrivate(
3291 CGF, VD, VDAddr: Addr, Loc);
3292 else
3293 Addr =
3294 CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, VDAddr: Addr, Loc);
3295
3296 Addr = Addr.withElementType(ElemTy: RealVarTy);
3297 return CGF.MakeAddrLValue(Addr, T, Source: AlignmentSource::Decl);
3298}
3299
3300static Address emitDeclTargetVarDeclLValue(CodeGenFunction &CGF,
3301 const VarDecl *VD, QualType T) {
3302 std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
3303 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
3304 // Return an invalid address if variable is MT_To (or MT_Enter starting with
3305 // OpenMP 5.2) and unified memory is not enabled. For all other cases: MT_Link
3306 // and MT_To (or MT_Enter) with unified memory, return a valid address.
3307 if (!Res || ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
3308 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
3309 !CGF.CGM.getOpenMPRuntime().hasRequiresUnifiedSharedMemory()))
3310 return Address::invalid();
3311 assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
3312 ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
3313 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
3314 CGF.CGM.getOpenMPRuntime().hasRequiresUnifiedSharedMemory())) &&
3315 "Expected link clause OR to clause with unified memory enabled.");
3316 QualType PtrTy = CGF.getContext().getPointerType(T: VD->getType());
3317 Address Addr = CGF.CGM.getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
3318 return CGF.EmitLoadOfPointer(Ptr: Addr, PtrTy: PtrTy->castAs<PointerType>());
3319}
3320
3321Address
3322CodeGenFunction::EmitLoadOfReference(LValue RefLVal,
3323 LValueBaseInfo *PointeeBaseInfo,
3324 TBAAAccessInfo *PointeeTBAAInfo) {
3325 llvm::LoadInst *Load =
3326 Builder.CreateLoad(Addr: RefLVal.getAddress(), IsVolatile: RefLVal.isVolatile());
3327 CGM.DecorateInstructionWithTBAA(Inst: Load, TBAAInfo: RefLVal.getTBAAInfo());
3328 QualType PTy = RefLVal.getType()->getPointeeType();
3329 CharUnits Align = CGM.getNaturalTypeAlignment(
3330 T: PTy, BaseInfo: PointeeBaseInfo, TBAAInfo: PointeeTBAAInfo, /*ForPointeeType=*/forPointeeType: true);
3331 if (!PTy->isIncompleteType()) {
3332 llvm::LLVMContext &Ctx = getLLVMContext();
3333 llvm::MDBuilder MDB(Ctx);
3334 // Emit !nonnull metadata
3335 if (CGM.getTypes().getTargetAddressSpace(T: PTy) == 0 &&
3336 !CGM.getCodeGenOpts().NullPointerIsValid)
3337 Load->setMetadata(KindID: llvm::LLVMContext::MD_nonnull,
3338 Node: llvm::MDNode::get(Context&: Ctx, MDs: {}));
3339 // Emit !align metadata
3340 if (PTy->isObjectType()) {
3341 auto AlignVal = Align.getQuantity();
3342 if (AlignVal > 1) {
3343 Load->setMetadata(
3344 KindID: llvm::LLVMContext::MD_align,
3345 Node: llvm::MDNode::get(Context&: Ctx, MDs: MDB.createConstant(C: llvm::ConstantInt::get(
3346 Ty: Builder.getInt64Ty(), V: AlignVal))));
3347 }
3348 }
3349 }
3350 return makeNaturalAddressForPointer(Ptr: Load, T: PTy, Alignment: Align,
3351 /*ForPointeeType=*/true, BaseInfo: PointeeBaseInfo,
3352 TBAAInfo: PointeeTBAAInfo);
3353}
3354
3355LValue CodeGenFunction::EmitLoadOfReferenceLValue(LValue RefLVal) {
3356 LValueBaseInfo PointeeBaseInfo;
3357 TBAAAccessInfo PointeeTBAAInfo;
3358 Address PointeeAddr = EmitLoadOfReference(RefLVal, PointeeBaseInfo: &PointeeBaseInfo,
3359 PointeeTBAAInfo: &PointeeTBAAInfo);
3360 return MakeAddrLValue(Addr: PointeeAddr, T: RefLVal.getType()->getPointeeType(),
3361 BaseInfo: PointeeBaseInfo, TBAAInfo: PointeeTBAAInfo);
3362}
3363
3364Address CodeGenFunction::EmitLoadOfPointer(Address Ptr,
3365 const PointerType *PtrTy,
3366 LValueBaseInfo *BaseInfo,
3367 TBAAAccessInfo *TBAAInfo) {
3368 llvm::Value *Addr = Builder.CreateLoad(Addr: Ptr);
3369 return makeNaturalAddressForPointer(Ptr: Addr, T: PtrTy->getPointeeType(),
3370 Alignment: CharUnits(), /*ForPointeeType=*/true,
3371 BaseInfo, TBAAInfo);
3372}
3373
3374LValue CodeGenFunction::EmitLoadOfPointerLValue(Address PtrAddr,
3375 const PointerType *PtrTy) {
3376 LValueBaseInfo BaseInfo;
3377 TBAAAccessInfo TBAAInfo;
3378 Address Addr = EmitLoadOfPointer(Ptr: PtrAddr, PtrTy, BaseInfo: &BaseInfo, TBAAInfo: &TBAAInfo);
3379 return MakeAddrLValue(Addr, T: PtrTy->getPointeeType(), BaseInfo, TBAAInfo);
3380}
3381
3382static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
3383 const Expr *E, const VarDecl *VD) {
3384 QualType T = E->getType();
3385
3386 // If it's thread_local, emit a call to its wrapper function instead.
3387 if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
3388 CGF.CGM.getCXXABI().usesThreadWrapperFunction(VD))
3389 return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, LValType: T);
3390 // Check if the variable is marked as declare target with link clause in
3391 // device codegen.
3392 if (CGF.getLangOpts().OpenMPIsTargetDevice) {
3393 Address Addr = emitDeclTargetVarDeclLValue(CGF, VD, T);
3394 if (Addr.isValid())
3395 return CGF.MakeAddrLValue(Addr, T, Source: AlignmentSource::Decl);
3396 }
3397
3398 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(D: VD);
3399
3400 if (VD->getTLSKind() != VarDecl::TLS_None)
3401 V = CGF.Builder.CreateThreadLocalAddress(Ptr: V);
3402
3403 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(T: VD->getType());
3404 CharUnits Alignment = CGF.getContext().getDeclAlign(D: VD);
3405 Address Addr(V, RealVarTy, Alignment);
3406 // Emit reference to the private copy of the variable if it is an OpenMP
3407 // threadprivate variable.
3408 if (CGF.getLangOpts().OpenMP && !CGF.getLangOpts().OpenMPSimd &&
3409 VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
3410 return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
3411 Loc: E->getExprLoc());
3412 }
3413 LValue LV = VD->getType()->isReferenceType() ?
3414 CGF.EmitLoadOfReferenceLValue(RefAddr: Addr, RefTy: VD->getType(),
3415 Source: AlignmentSource::Decl) :
3416 CGF.MakeAddrLValue(Addr, T, Source: AlignmentSource::Decl);
3417 setObjCGCLValueClass(Ctx: CGF.getContext(), E, LV);
3418 return LV;
3419}
3420
3421llvm::Constant *CodeGenModule::getRawFunctionPointer(GlobalDecl GD,
3422 llvm::Type *Ty) {
3423 const FunctionDecl *FD = cast<FunctionDecl>(Val: GD.getDecl());
3424 if (FD->hasAttr<WeakRefAttr>()) {
3425 ConstantAddress aliasee = GetWeakRefReference(VD: FD);
3426 return aliasee.getPointer();
3427 }
3428
3429 llvm::Constant *V = GetAddrOfFunction(GD, Ty);
3430 return V;
3431}
3432
3433static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF, const Expr *E,
3434 GlobalDecl GD) {
3435 const FunctionDecl *FD = cast<FunctionDecl>(Val: GD.getDecl());
3436 llvm::Constant *V = CGF.CGM.getFunctionPointer(GD);
3437 QualType ETy = E->getType();
3438 if (ETy->isCFIUncheckedCalleeFunctionType()) {
3439 if (auto *GV = dyn_cast<llvm::GlobalValue>(Val: V))
3440 V = llvm::NoCFIValue::get(GV);
3441 }
3442 CharUnits Alignment = CGF.getContext().getDeclAlign(D: FD);
3443 return CGF.MakeAddrLValue(V, T: ETy, Alignment, Source: AlignmentSource::Decl);
3444}
3445
3446static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
3447 llvm::Value *ThisValue) {
3448
3449 return CGF.EmitLValueForLambdaField(Field: FD, ThisValue);
3450}
3451
3452/// Named Registers are named metadata pointing to the register name
3453/// which will be read from/written to as an argument to the intrinsic
3454/// @llvm.read/write_register.
3455/// So far, only the name is being passed down, but other options such as
3456/// register type, allocation type or even optimization options could be
3457/// passed down via the metadata node.
3458static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
3459 SmallString<64> Name("llvm.named.register.");
3460 AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
3461 assert(Asm->getLabel().size() < 64-Name.size() &&
3462 "Register name too big");
3463 Name.append(RHS: Asm->getLabel());
3464 llvm::NamedMDNode *M =
3465 CGM.getModule().getOrInsertNamedMetadata(Name);
3466 if (M->getNumOperands() == 0) {
3467 llvm::MDString *Str = llvm::MDString::get(Context&: CGM.getLLVMContext(),
3468 Str: Asm->getLabel());
3469 llvm::Metadata *Ops[] = {Str};
3470 M->addOperand(M: llvm::MDNode::get(Context&: CGM.getLLVMContext(), MDs: Ops));
3471 }
3472
3473 CharUnits Alignment = CGM.getContext().getDeclAlign(D: VD);
3474
3475 llvm::Value *Ptr =
3476 llvm::MetadataAsValue::get(Context&: CGM.getLLVMContext(), MD: M->getOperand(i: 0));
3477 return LValue::MakeGlobalReg(V: Ptr, alignment: Alignment, type: VD->getType());
3478}
3479
3480/// Determine whether we can emit a reference to \p VD from the current
3481/// context, despite not necessarily having seen an odr-use of the variable in
3482/// this context.
3483static bool canEmitSpuriousReferenceToVariable(CodeGenFunction &CGF,
3484 const DeclRefExpr *E,
3485 const VarDecl *VD) {
3486 // For a variable declared in an enclosing scope, do not emit a spurious
3487 // reference even if we have a capture, as that will emit an unwarranted
3488 // reference to our capture state, and will likely generate worse code than
3489 // emitting a local copy.
3490 if (E->refersToEnclosingVariableOrCapture())
3491 return false;
3492
3493 // For a local declaration declared in this function, we can always reference
3494 // it even if we don't have an odr-use.
3495 if (VD->hasLocalStorage()) {
3496 return VD->getDeclContext() ==
3497 dyn_cast_or_null<DeclContext>(Val: CGF.CurCodeDecl);
3498 }
3499
3500 // For a global declaration, we can emit a reference to it if we know
3501 // for sure that we are able to emit a definition of it.
3502 VD = VD->getDefinition(C&: CGF.getContext());
3503 if (!VD)
3504 return false;
3505
3506 // Don't emit a spurious reference if it might be to a variable that only
3507 // exists on a different device / target.
3508 // FIXME: This is unnecessarily broad. Check whether this would actually be a
3509 // cross-target reference.
3510 if (CGF.getLangOpts().OpenMP || CGF.getLangOpts().CUDA ||
3511 CGF.getLangOpts().OpenCL) {
3512 return false;
3513 }
3514
3515 // We can emit a spurious reference only if the linkage implies that we'll
3516 // be emitting a non-interposable symbol that will be retained until link
3517 // time.
3518 switch (CGF.CGM.getLLVMLinkageVarDefinition(VD)) {
3519 case llvm::GlobalValue::ExternalLinkage:
3520 case llvm::GlobalValue::LinkOnceODRLinkage:
3521 case llvm::GlobalValue::WeakODRLinkage:
3522 case llvm::GlobalValue::InternalLinkage:
3523 case llvm::GlobalValue::PrivateLinkage:
3524 return true;
3525 default:
3526 return false;
3527 }
3528}
3529
3530LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
3531 const NamedDecl *ND = E->getDecl();
3532 QualType T = E->getType();
3533
3534 assert(E->isNonOdrUse() != NOUR_Unevaluated &&
3535 "should not emit an unevaluated operand");
3536
3537 if (const auto *VD = dyn_cast<VarDecl>(Val: ND)) {
3538 // Global Named registers access via intrinsics only
3539 if (VD->getStorageClass() == SC_Register &&
3540 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
3541 return EmitGlobalNamedRegister(VD, CGM);
3542
3543 // If this DeclRefExpr does not constitute an odr-use of the variable,
3544 // we're not permitted to emit a reference to it in general, and it might
3545 // not be captured if capture would be necessary for a use. Emit the
3546 // constant value directly instead.
3547 if (E->isNonOdrUse() == NOUR_Constant &&
3548 (VD->getType()->isReferenceType() ||
3549 !canEmitSpuriousReferenceToVariable(CGF&: *this, E, VD))) {
3550 VD->getAnyInitializer(D&: VD);
3551 llvm::Constant *Val = ConstantEmitter(*this).emitAbstract(
3552 loc: E->getLocation(), value: *VD->evaluateValue(), T: VD->getType());
3553 assert(Val && "failed to emit constant expression");
3554
3555 Address Addr = Address::invalid();
3556 if (!VD->getType()->isReferenceType()) {
3557 // Spill the constant value to a global.
3558 Addr = CGM.createUnnamedGlobalFrom(D: *VD, Constant: Val,
3559 Align: getContext().getDeclAlign(D: VD));
3560 llvm::Type *VarTy = getTypes().ConvertTypeForMem(T: VD->getType());
3561 auto *PTy = llvm::PointerType::get(
3562 C&: getLLVMContext(), AddressSpace: getTypes().getTargetAddressSpace(T: VD->getType()));
3563 Addr = Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty: PTy, ElementTy: VarTy);
3564 } else {
3565 // Should we be using the alignment of the constant pointer we emitted?
3566 CharUnits Alignment =
3567 CGM.getNaturalTypeAlignment(T: E->getType(),
3568 /* BaseInfo= */ nullptr,
3569 /* TBAAInfo= */ nullptr,
3570 /* forPointeeType= */ true);
3571 Addr = makeNaturalAddressForPointer(Ptr: Val, T, Alignment);
3572 }
3573 return MakeAddrLValue(Addr, T, Source: AlignmentSource::Decl);
3574 }
3575
3576 // FIXME: Handle other kinds of non-odr-use DeclRefExprs.
3577
3578 // Check for captured variables.
3579 if (E->refersToEnclosingVariableOrCapture()) {
3580 VD = VD->getCanonicalDecl();
3581 if (auto *FD = LambdaCaptureFields.lookup(Val: VD))
3582 return EmitCapturedFieldLValue(CGF&: *this, FD, ThisValue: CXXABIThisValue);
3583 if (CapturedStmtInfo) {
3584 auto I = LocalDeclMap.find(Val: VD);
3585 if (I != LocalDeclMap.end()) {
3586 LValue CapLVal;
3587 if (VD->getType()->isReferenceType())
3588 CapLVal = EmitLoadOfReferenceLValue(RefAddr: I->second, RefTy: VD->getType(),
3589 Source: AlignmentSource::Decl);
3590 else
3591 CapLVal = MakeAddrLValue(Addr: I->second, T);
3592 // Mark lvalue as nontemporal if the variable is marked as nontemporal
3593 // in simd context.
3594 if (getLangOpts().OpenMP &&
3595 CGM.getOpenMPRuntime().isNontemporalDecl(VD))
3596 CapLVal.setNontemporal(/*Value=*/true);
3597 return CapLVal;
3598 }
3599 LValue CapLVal =
3600 EmitCapturedFieldLValue(CGF&: *this, FD: CapturedStmtInfo->lookup(VD),
3601 ThisValue: CapturedStmtInfo->getContextValue());
3602 Address LValueAddress = CapLVal.getAddress();
3603 CapLVal = MakeAddrLValue(Addr: Address(LValueAddress.emitRawPointer(CGF&: *this),
3604 LValueAddress.getElementType(),
3605 getContext().getDeclAlign(D: VD)),
3606 T: CapLVal.getType(),
3607 BaseInfo: LValueBaseInfo(AlignmentSource::Decl),
3608 TBAAInfo: CapLVal.getTBAAInfo());
3609 // Mark lvalue as nontemporal if the variable is marked as nontemporal
3610 // in simd context.
3611 if (getLangOpts().OpenMP &&
3612 CGM.getOpenMPRuntime().isNontemporalDecl(VD))
3613 CapLVal.setNontemporal(/*Value=*/true);
3614 return CapLVal;
3615 }
3616
3617 assert(isa<BlockDecl>(CurCodeDecl));
3618 Address addr = GetAddrOfBlockDecl(var: VD);
3619 return MakeAddrLValue(Addr: addr, T, Source: AlignmentSource::Decl);
3620 }
3621 }
3622
3623 // FIXME: We should be able to assert this for FunctionDecls as well!
3624 // FIXME: We should be able to assert this for all DeclRefExprs, not just
3625 // those with a valid source location.
3626 assert((ND->isUsed(false) || !isa<VarDecl>(ND) || E->isNonOdrUse() ||
3627 !E->getLocation().isValid()) &&
3628 "Should not use decl without marking it used!");
3629
3630 if (ND->hasAttr<WeakRefAttr>()) {
3631 const auto *VD = cast<ValueDecl>(Val: ND);
3632 ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
3633 return MakeAddrLValue(Addr: Aliasee, T, Source: AlignmentSource::Decl);
3634 }
3635
3636 if (const auto *VD = dyn_cast<VarDecl>(Val: ND)) {
3637 // Check if this is a global variable.
3638 if (VD->hasLinkage() || VD->isStaticDataMember())
3639 return EmitGlobalVarDeclLValue(CGF&: *this, E, VD);
3640
3641 Address addr = Address::invalid();
3642
3643 // The variable should generally be present in the local decl map.
3644 auto iter = LocalDeclMap.find(Val: VD);
3645 if (iter != LocalDeclMap.end()) {
3646 addr = iter->second;
3647
3648 // Otherwise, it might be static local we haven't emitted yet for
3649 // some reason; most likely, because it's in an outer function.
3650 } else if (VD->isStaticLocal()) {
3651 llvm::Constant *var = CGM.getOrCreateStaticVarDecl(
3652 D: *VD, Linkage: CGM.getLLVMLinkageVarDefinition(VD));
3653 addr = Address(
3654 var, ConvertTypeForMem(T: VD->getType()), getContext().getDeclAlign(D: VD));
3655
3656 // No other cases for now.
3657 } else {
3658 llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
3659 }
3660
3661 // Handle threadlocal function locals.
3662 if (VD->getTLSKind() != VarDecl::TLS_None)
3663 addr = addr.withPointer(
3664 NewPointer: Builder.CreateThreadLocalAddress(Ptr: addr.getBasePointer()),
3665 IsKnownNonNull: NotKnownNonNull);
3666
3667 // Check for OpenMP threadprivate variables.
3668 if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd &&
3669 VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
3670 return EmitThreadPrivateVarDeclLValue(
3671 CGF&: *this, VD, T, Addr: addr, RealVarTy: getTypes().ConvertTypeForMem(T: VD->getType()),
3672 Loc: E->getExprLoc());
3673 }
3674
3675 // Drill into block byref variables.
3676 bool isBlockByref = VD->isEscapingByref();
3677 if (isBlockByref) {
3678 addr = emitBlockByrefAddress(baseAddr: addr, V: VD);
3679 }
3680
3681 // Drill into reference types.
3682 LValue LV = VD->getType()->isReferenceType() ?
3683 EmitLoadOfReferenceLValue(RefAddr: addr, RefTy: VD->getType(), Source: AlignmentSource::Decl) :
3684 MakeAddrLValue(Addr: addr, T, Source: AlignmentSource::Decl);
3685
3686 bool isLocalStorage = VD->hasLocalStorage();
3687
3688 bool NonGCable = isLocalStorage &&
3689 !VD->getType()->isReferenceType() &&
3690 !isBlockByref;
3691 if (NonGCable) {
3692 LV.getQuals().removeObjCGCAttr();
3693 LV.setNonGC(true);
3694 }
3695
3696 bool isImpreciseLifetime =
3697 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
3698 if (isImpreciseLifetime)
3699 LV.setARCPreciseLifetime(ARCImpreciseLifetime);
3700 setObjCGCLValueClass(Ctx: getContext(), E, LV);
3701 return LV;
3702 }
3703
3704 if (const auto *FD = dyn_cast<FunctionDecl>(Val: ND))
3705 return EmitFunctionDeclLValue(CGF&: *this, E, GD: FD);
3706
3707 // FIXME: While we're emitting a binding from an enclosing scope, all other
3708 // DeclRefExprs we see should be implicitly treated as if they also refer to
3709 // an enclosing scope.
3710 if (const auto *BD = dyn_cast<BindingDecl>(Val: ND)) {
3711 if (E->refersToEnclosingVariableOrCapture()) {
3712 auto *FD = LambdaCaptureFields.lookup(Val: BD);
3713 return EmitCapturedFieldLValue(CGF&: *this, FD, ThisValue: CXXABIThisValue);
3714 }
3715 // Suppress debug location updates when visiting the binding, since the
3716 // binding may emit instructions that would otherwise be associated with the
3717 // binding itself, rather than the expression referencing the binding. (this
3718 // leads to jumpy debug stepping behavior where the location/debugger jump
3719 // back to the binding declaration, then back to the expression referencing
3720 // the binding)
3721 DisableDebugLocationUpdates D(*this);
3722 return EmitLValue(E: BD->getBinding(), IsKnownNonNull: NotKnownNonNull);
3723 }
3724
3725 // We can form DeclRefExprs naming GUID declarations when reconstituting
3726 // non-type template parameters into expressions.
3727 if (const auto *GD = dyn_cast<MSGuidDecl>(Val: ND))
3728 return MakeAddrLValue(Addr: CGM.GetAddrOfMSGuidDecl(GD), T,
3729 Source: AlignmentSource::Decl);
3730
3731 if (const auto *TPO = dyn_cast<TemplateParamObjectDecl>(Val: ND)) {
3732 ConstantAddress ATPO = CGM.GetAddrOfTemplateParamObject(TPO);
3733 auto AS = getLangASFromTargetAS(TargetAS: ATPO.getAddressSpace());
3734
3735 if (AS != T.getAddressSpace()) {
3736 auto TargetAS = getContext().getTargetAddressSpace(AS: T.getAddressSpace());
3737 llvm::Type *PtrTy =
3738 llvm::PointerType::get(C&: CGM.getLLVMContext(), AddressSpace: TargetAS);
3739 llvm::Constant *ASC = CGM.performAddrSpaceCast(Src: ATPO.getPointer(), DestTy: PtrTy);
3740 ATPO = ConstantAddress(ASC, ATPO.getElementType(), ATPO.getAlignment());
3741 }
3742
3743 return MakeAddrLValue(Addr: ATPO, T, Source: AlignmentSource::Decl);
3744 }
3745
3746 llvm_unreachable("Unhandled DeclRefExpr");
3747}
3748
3749LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
3750 // __extension__ doesn't affect lvalue-ness.
3751 if (E->getOpcode() == UO_Extension)
3752 return EmitLValue(E: E->getSubExpr());
3753
3754 QualType ExprTy = getContext().getCanonicalType(T: E->getSubExpr()->getType());
3755 switch (E->getOpcode()) {
3756 default: llvm_unreachable("Unknown unary operator lvalue!");
3757 case UO_Deref: {
3758 QualType T = E->getSubExpr()->getType()->getPointeeType();
3759 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
3760
3761 LValueBaseInfo BaseInfo;
3762 TBAAAccessInfo TBAAInfo;
3763 Address Addr = EmitPointerWithAlignment(E: E->getSubExpr(), BaseInfo: &BaseInfo,
3764 TBAAInfo: &TBAAInfo);
3765 LValue LV = MakeAddrLValue(Addr, T, BaseInfo, TBAAInfo);
3766 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
3767
3768 // We should not generate __weak write barrier on indirect reference
3769 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
3770 // But, we continue to generate __strong write barrier on indirect write
3771 // into a pointer to object.
3772 if (getLangOpts().ObjC &&
3773 getLangOpts().getGC() != LangOptions::NonGC &&
3774 LV.isObjCWeak())
3775 LV.setNonGC(!E->isOBJCGCCandidate(Ctx&: getContext()));
3776 return LV;
3777 }
3778 case UO_Real:
3779 case UO_Imag: {
3780 LValue LV = EmitLValue(E: E->getSubExpr());
3781 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
3782
3783 // __real is valid on scalars. This is a faster way of testing that.
3784 // __imag can only produce an rvalue on scalars.
3785 if (E->getOpcode() == UO_Real &&
3786 !LV.getAddress().getElementType()->isStructTy()) {
3787 assert(E->getSubExpr()->getType()->isArithmeticType());
3788 return LV;
3789 }
3790
3791 QualType T = ExprTy->castAs<ComplexType>()->getElementType();
3792
3793 Address Component =
3794 (E->getOpcode() == UO_Real
3795 ? emitAddrOfRealComponent(complex: LV.getAddress(), complexType: LV.getType())
3796 : emitAddrOfImagComponent(complex: LV.getAddress(), complexType: LV.getType()));
3797 LValue ElemLV = MakeAddrLValue(Addr: Component, T, BaseInfo: LV.getBaseInfo(),
3798 TBAAInfo: CGM.getTBAAInfoForSubobject(Base: LV, AccessType: T));
3799 ElemLV.getQuals().addQualifiers(Q: LV.getQuals());
3800 return ElemLV;
3801 }
3802 case UO_PreInc:
3803 case UO_PreDec: {
3804 LValue LV = EmitLValue(E: E->getSubExpr());
3805 bool isInc = E->getOpcode() == UO_PreInc;
3806
3807 if (E->getType()->isAnyComplexType())
3808 EmitComplexPrePostIncDec(E, LV, isInc, isPre: true/*isPre*/);
3809 else
3810 EmitScalarPrePostIncDec(E, LV, isInc, isPre: true/*isPre*/);
3811 return LV;
3812 }
3813 }
3814}
3815
3816LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
3817 return MakeAddrLValue(Addr: CGM.GetAddrOfConstantStringFromLiteral(S: E),
3818 T: E->getType(), Source: AlignmentSource::Decl);
3819}
3820
3821LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
3822 return MakeAddrLValue(Addr: CGM.GetAddrOfConstantStringFromObjCEncode(E),
3823 T: E->getType(), Source: AlignmentSource::Decl);
3824}
3825
3826LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
3827 auto SL = E->getFunctionName();
3828 assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
3829 StringRef FnName = CurFn->getName();
3830 FnName.consume_front(Prefix: "\01");
3831 StringRef NameItems[] = {
3832 PredefinedExpr::getIdentKindName(IK: E->getIdentKind()), FnName};
3833 std::string GVName = llvm::join(Begin: NameItems, End: NameItems + 2, Separator: ".");
3834 if (auto *BD = dyn_cast_or_null<BlockDecl>(Val: CurCodeDecl)) {
3835 std::string Name = std::string(SL->getString());
3836 if (!Name.empty()) {
3837 unsigned Discriminator =
3838 CGM.getCXXABI().getMangleContext().getBlockId(BD, Local: true);
3839 if (Discriminator)
3840 Name += "_" + Twine(Discriminator + 1).str();
3841 auto C = CGM.GetAddrOfConstantCString(Str: Name, GlobalName: GVName);
3842 return MakeAddrLValue(Addr: C, T: E->getType(), Source: AlignmentSource::Decl);
3843 } else {
3844 auto C = CGM.GetAddrOfConstantCString(Str: std::string(FnName), GlobalName: GVName);
3845 return MakeAddrLValue(Addr: C, T: E->getType(), Source: AlignmentSource::Decl);
3846 }
3847 }
3848 auto C = CGM.GetAddrOfConstantStringFromLiteral(S: SL, Name: GVName);
3849 return MakeAddrLValue(Addr: C, T: E->getType(), Source: AlignmentSource::Decl);
3850}
3851
3852/// Emit a type description suitable for use by a runtime sanitizer library. The
3853/// format of a type descriptor is
3854///
3855/// \code
3856/// { i16 TypeKind, i16 TypeInfo }
3857/// \endcode
3858///
3859/// followed by an array of i8 containing the type name with extra information
3860/// for BitInt. TypeKind is TK_Integer(0) for an integer, TK_Float(1) for a
3861/// floating point value, TK_BitInt(2) for BitInt and TK_Unknown(0xFFFF) for
3862/// anything else.
3863llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
3864 // Only emit each type's descriptor once.
3865 if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(Ty: T))
3866 return C;
3867
3868 uint16_t TypeKind = TK_Unknown;
3869 uint16_t TypeInfo = 0;
3870 bool IsBitInt = false;
3871
3872 if (T->isIntegerType()) {
3873 TypeKind = TK_Integer;
3874 TypeInfo = (llvm::Log2_32(Value: getContext().getTypeSize(T)) << 1) |
3875 (T->isSignedIntegerType() ? 1 : 0);
3876 // Follow suggestion from discussion of issue 64100.
3877 // So we can write the exact amount of bits in TypeName after '\0'
3878 // making it <diagnostic-like type name>.'\0'.<32-bit width>.
3879 if (T->isSignedIntegerType() && T->getAs<BitIntType>()) {
3880 // Do a sanity checks as we are using 32-bit type to store bit length.
3881 assert(getContext().getTypeSize(T) > 0 &&
3882 " non positive amount of bits in __BitInt type");
3883 assert(getContext().getTypeSize(T) <= 0xFFFFFFFF &&
3884 " too many bits in __BitInt type");
3885
3886 // Redefine TypeKind with the actual __BitInt type if we have signed
3887 // BitInt.
3888 TypeKind = TK_BitInt;
3889 IsBitInt = true;
3890 }
3891 } else if (T->isFloatingType()) {
3892 TypeKind = TK_Float;
3893 TypeInfo = getContext().getTypeSize(T);
3894 }
3895
3896 // Format the type name as if for a diagnostic, including quotes and
3897 // optionally an 'aka'.
3898 SmallString<32> Buffer;
3899 CGM.getDiags().ConvertArgToString(Kind: DiagnosticsEngine::ak_qualtype,
3900 Val: (intptr_t)T.getAsOpaquePtr(), Modifier: StringRef(),
3901 Argument: StringRef(), PrevArgs: {}, Output&: Buffer, QualTypeVals: {});
3902
3903 if (IsBitInt) {
3904 // The Structure is: 0 to end the string, 32 bit unsigned integer in target
3905 // endianness, zero.
3906 char S[6] = {'\0', '\0', '\0', '\0', '\0', '\0'};
3907 const auto *EIT = T->castAs<BitIntType>();
3908 uint32_t Bits = EIT->getNumBits();
3909 llvm::support::endian::write32(P: S + 1, V: Bits,
3910 E: getTarget().isBigEndian()
3911 ? llvm::endianness::big
3912 : llvm::endianness::little);
3913 StringRef Str = StringRef(S, sizeof(S) / sizeof(decltype(S[0])));
3914 Buffer.append(RHS: Str);
3915 }
3916
3917 llvm::Constant *Components[] = {
3918 Builder.getInt16(C: TypeKind), Builder.getInt16(C: TypeInfo),
3919 llvm::ConstantDataArray::getString(Context&: getLLVMContext(), Initializer: Buffer)
3920 };
3921 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(V: Components);
3922
3923 auto *GV = new llvm::GlobalVariable(
3924 CGM.getModule(), Descriptor->getType(),
3925 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
3926 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3927 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
3928
3929 // Remember the descriptor for this type.
3930 CGM.setTypeDescriptorInMap(Ty: T, C: GV);
3931
3932 return GV;
3933}
3934
3935llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
3936 llvm::Type *TargetTy = IntPtrTy;
3937
3938 if (V->getType() == TargetTy)
3939 return V;
3940
3941 // Floating-point types which fit into intptr_t are bitcast to integers
3942 // and then passed directly (after zero-extension, if necessary).
3943 if (V->getType()->isFloatingPointTy()) {
3944 unsigned Bits = V->getType()->getPrimitiveSizeInBits().getFixedValue();
3945 if (Bits <= TargetTy->getIntegerBitWidth())
3946 V = Builder.CreateBitCast(V, DestTy: llvm::Type::getIntNTy(C&: getLLVMContext(),
3947 N: Bits));
3948 }
3949
3950 // Integers which fit in intptr_t are zero-extended and passed directly.
3951 if (V->getType()->isIntegerTy() &&
3952 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
3953 return Builder.CreateZExt(V, DestTy: TargetTy);
3954
3955 // Pointers are passed directly, everything else is passed by address.
3956 if (!V->getType()->isPointerTy()) {
3957 RawAddress Ptr = CreateDefaultAlignTempAlloca(Ty: V->getType());
3958 Builder.CreateStore(Val: V, Addr: Ptr);
3959 V = Ptr.getPointer();
3960 }
3961 return Builder.CreatePtrToInt(V, DestTy: TargetTy);
3962}
3963
3964/// Emit a representation of a SourceLocation for passing to a handler
3965/// in a sanitizer runtime library. The format for this data is:
3966/// \code
3967/// struct SourceLocation {
3968/// const char *Filename;
3969/// int32_t Line, Column;
3970/// };
3971/// \endcode
3972/// For an invalid SourceLocation, the Filename pointer is null.
3973llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
3974 llvm::Constant *Filename;
3975 int Line, Column;
3976
3977 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
3978 if (PLoc.isValid()) {
3979 StringRef FilenameString = PLoc.getFilename();
3980
3981 int PathComponentsToStrip =
3982 CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
3983 if (PathComponentsToStrip < 0) {
3984 assert(PathComponentsToStrip != INT_MIN);
3985 int PathComponentsToKeep = -PathComponentsToStrip;
3986 auto I = llvm::sys::path::rbegin(path: FilenameString);
3987 auto E = llvm::sys::path::rend(path: FilenameString);
3988 while (I != E && --PathComponentsToKeep)
3989 ++I;
3990
3991 FilenameString = FilenameString.substr(Start: I - E);
3992 } else if (PathComponentsToStrip > 0) {
3993 auto I = llvm::sys::path::begin(path: FilenameString);
3994 auto E = llvm::sys::path::end(path: FilenameString);
3995 while (I != E && PathComponentsToStrip--)
3996 ++I;
3997
3998 if (I != E)
3999 FilenameString =
4000 FilenameString.substr(Start: I - llvm::sys::path::begin(path: FilenameString));
4001 else
4002 FilenameString = llvm::sys::path::filename(path: FilenameString);
4003 }
4004
4005 auto FilenameGV =
4006 CGM.GetAddrOfConstantCString(Str: std::string(FilenameString), GlobalName: ".src");
4007 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
4008 GV: cast<llvm::GlobalVariable>(
4009 Val: FilenameGV.getPointer()->stripPointerCasts()));
4010 Filename = FilenameGV.getPointer();
4011 Line = PLoc.getLine();
4012 Column = PLoc.getColumn();
4013 } else {
4014 Filename = llvm::Constant::getNullValue(Ty: Int8PtrTy);
4015 Line = Column = 0;
4016 }
4017
4018 llvm::Constant *Data[] = {Filename, Builder.getInt32(C: Line),
4019 Builder.getInt32(C: Column)};
4020
4021 return llvm::ConstantStruct::getAnon(V: Data);
4022}
4023
4024namespace {
4025/// Specify under what conditions this check can be recovered
4026enum class CheckRecoverableKind {
4027 /// Always terminate program execution if this check fails.
4028 Unrecoverable,
4029 /// Check supports recovering, runtime has both fatal (noreturn) and
4030 /// non-fatal handlers for this check.
4031 Recoverable,
4032 /// Runtime conditionally aborts, always need to support recovery.
4033 AlwaysRecoverable
4034};
4035}
4036
4037static CheckRecoverableKind
4038getRecoverableKind(SanitizerKind::SanitizerOrdinal Ordinal) {
4039 if (Ordinal == SanitizerKind::SO_Vptr)
4040 return CheckRecoverableKind::AlwaysRecoverable;
4041 else if (Ordinal == SanitizerKind::SO_Return ||
4042 Ordinal == SanitizerKind::SO_Unreachable)
4043 return CheckRecoverableKind::Unrecoverable;
4044 else
4045 return CheckRecoverableKind::Recoverable;
4046}
4047
4048namespace {
4049struct SanitizerHandlerInfo {
4050 char const *const Name;
4051 unsigned Version;
4052};
4053}
4054
4055const SanitizerHandlerInfo SanitizerHandlers[] = {
4056#define SANITIZER_CHECK(Enum, Name, Version, Msg) {#Name, Version},
4057 LIST_SANITIZER_CHECKS
4058#undef SANITIZER_CHECK
4059};
4060
4061static void emitCheckHandlerCall(CodeGenFunction &CGF,
4062 llvm::FunctionType *FnType,
4063 ArrayRef<llvm::Value *> FnArgs,
4064 SanitizerHandler CheckHandler,
4065 CheckRecoverableKind RecoverKind, bool IsFatal,
4066 llvm::BasicBlock *ContBB, bool NoMerge) {
4067 assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
4068 std::optional<ApplyDebugLocation> DL;
4069 if (!CGF.Builder.getCurrentDebugLocation()) {
4070 // Ensure that the call has at least an artificial debug location.
4071 DL.emplace(args&: CGF, args: SourceLocation());
4072 }
4073 bool NeedsAbortSuffix =
4074 IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
4075 bool MinimalRuntime = CGF.CGM.getCodeGenOpts().SanitizeMinimalRuntime;
4076 bool HandlerPreserveAllRegs =
4077 CGF.CGM.getCodeGenOpts().SanitizeHandlerPreserveAllRegs;
4078 const SanitizerHandlerInfo &CheckInfo = SanitizerHandlers[CheckHandler];
4079 const StringRef CheckName = CheckInfo.Name;
4080 std::string FnName = "__ubsan_handle_" + CheckName.str();
4081 if (CheckInfo.Version && !MinimalRuntime)
4082 FnName += "_v" + llvm::utostr(X: CheckInfo.Version);
4083 if (MinimalRuntime)
4084 FnName += "_minimal";
4085 if (NeedsAbortSuffix)
4086 FnName += "_abort";
4087 if (HandlerPreserveAllRegs && !NeedsAbortSuffix)
4088 FnName += "_preserve";
4089 bool MayReturn =
4090 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
4091
4092 llvm::AttrBuilder B(CGF.getLLVMContext());
4093 if (!MayReturn) {
4094 B.addAttribute(Val: llvm::Attribute::NoReturn)
4095 .addAttribute(Val: llvm::Attribute::NoUnwind);
4096 }
4097 B.addUWTableAttr(Kind: llvm::UWTableKind::Default);
4098
4099 llvm::FunctionCallee Fn = CGF.CGM.CreateRuntimeFunction(
4100 Ty: FnType, Name: FnName,
4101 ExtraAttrs: llvm::AttributeList::get(C&: CGF.getLLVMContext(),
4102 Index: llvm::AttributeList::FunctionIndex, B),
4103 /*Local=*/true);
4104 llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(callee: Fn, args: FnArgs);
4105 NoMerge = NoMerge || !CGF.CGM.getCodeGenOpts().OptimizationLevel ||
4106 (CGF.CurCodeDecl && CGF.CurCodeDecl->hasAttr<OptimizeNoneAttr>());
4107 if (NoMerge)
4108 HandlerCall->addFnAttr(Kind: llvm::Attribute::NoMerge);
4109 if (HandlerPreserveAllRegs && !NeedsAbortSuffix) {
4110 // N.B. there is also a clang::CallingConv which is not what we want here.
4111 HandlerCall->setCallingConv(llvm::CallingConv::PreserveAll);
4112 }
4113 if (!MayReturn) {
4114 HandlerCall->setDoesNotReturn();
4115 CGF.Builder.CreateUnreachable();
4116 } else {
4117 CGF.Builder.CreateBr(Dest: ContBB);
4118 }
4119}
4120
4121void CodeGenFunction::EmitCheck(
4122 ArrayRef<std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>> Checked,
4123 SanitizerHandler CheckHandler, ArrayRef<llvm::Constant *> StaticArgs,
4124 ArrayRef<llvm::Value *> DynamicArgs, const TrapReason *TR) {
4125 assert(IsSanitizerScope);
4126 assert(Checked.size() > 0);
4127 assert(CheckHandler >= 0 &&
4128 size_t(CheckHandler) < std::size(SanitizerHandlers));
4129 const StringRef CheckName = SanitizerHandlers[CheckHandler].Name;
4130
4131 llvm::Value *FatalCond = nullptr;
4132 llvm::Value *RecoverableCond = nullptr;
4133 llvm::Value *TrapCond = nullptr;
4134 bool NoMerge = false;
4135 // Expand checks into:
4136 // (Check1 || !allow_ubsan_check) && (Check2 || !allow_ubsan_check) ...
4137 // We need separate allow_ubsan_check intrinsics because they have separately
4138 // specified cutoffs.
4139 // This expression looks expensive but will be simplified after
4140 // LowerAllowCheckPass.
4141 for (auto &[Check, Ord] : Checked) {
4142 llvm::Value *GuardedCheck = Check;
4143 if (ClSanitizeGuardChecks ||
4144 (CGM.getCodeGenOpts().SanitizeSkipHotCutoffs[Ord] > 0)) {
4145 llvm::Value *Allow = Builder.CreateCall(
4146 Callee: CGM.getIntrinsic(IID: llvm::Intrinsic::allow_ubsan_check),
4147 Args: llvm::ConstantInt::get(Ty: CGM.Int8Ty, V: Ord));
4148 GuardedCheck = Builder.CreateOr(LHS: Check, RHS: Builder.CreateNot(V: Allow));
4149 }
4150
4151 // -fsanitize-trap= overrides -fsanitize-recover=.
4152 llvm::Value *&Cond = CGM.getCodeGenOpts().SanitizeTrap.has(O: Ord) ? TrapCond
4153 : CGM.getCodeGenOpts().SanitizeRecover.has(O: Ord)
4154 ? RecoverableCond
4155 : FatalCond;
4156 Cond = Cond ? Builder.CreateAnd(LHS: Cond, RHS: GuardedCheck) : GuardedCheck;
4157
4158 if (!CGM.getCodeGenOpts().SanitizeMergeHandlers.has(O: Ord))
4159 NoMerge = true;
4160 }
4161
4162 if (TrapCond)
4163 EmitTrapCheck(Checked: TrapCond, CheckHandlerID: CheckHandler, NoMerge, TR);
4164 if (!FatalCond && !RecoverableCond)
4165 return;
4166
4167 llvm::Value *JointCond;
4168 if (FatalCond && RecoverableCond)
4169 JointCond = Builder.CreateAnd(LHS: FatalCond, RHS: RecoverableCond);
4170 else
4171 JointCond = FatalCond ? FatalCond : RecoverableCond;
4172 assert(JointCond);
4173
4174 CheckRecoverableKind RecoverKind = getRecoverableKind(Ordinal: Checked[0].second);
4175 assert(SanOpts.has(Checked[0].second));
4176#ifndef NDEBUG
4177 for (int i = 1, n = Checked.size(); i < n; ++i) {
4178 assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
4179 "All recoverable kinds in a single check must be same!");
4180 assert(SanOpts.has(Checked[i].second));
4181 }
4182#endif
4183
4184 llvm::BasicBlock *Cont = createBasicBlock(name: "cont");
4185 llvm::BasicBlock *Handlers = createBasicBlock(name: "handler." + CheckName);
4186 llvm::Instruction *Branch = Builder.CreateCondBr(Cond: JointCond, True: Cont, False: Handlers);
4187 // Give hint that we very much don't expect to execute the handler
4188 llvm::MDBuilder MDHelper(getLLVMContext());
4189 llvm::MDNode *Node = MDHelper.createLikelyBranchWeights();
4190 Branch->setMetadata(KindID: llvm::LLVMContext::MD_prof, Node);
4191 EmitBlock(BB: Handlers);
4192
4193 // Clear arguments for the MinimalRuntime handler.
4194 if (CGM.getCodeGenOpts().SanitizeMinimalRuntime) {
4195 StaticArgs = {};
4196 DynamicArgs = {};
4197 }
4198
4199 // Handler functions take an i8* pointing to the (handler-specific) static
4200 // information block, followed by a sequence of intptr_t arguments
4201 // representing operand values.
4202 SmallVector<llvm::Value *, 4> Args;
4203 SmallVector<llvm::Type *, 4> ArgTypes;
4204
4205 Args.reserve(N: DynamicArgs.size() + 1);
4206 ArgTypes.reserve(N: DynamicArgs.size() + 1);
4207
4208 // Emit handler arguments and create handler function type.
4209 if (!StaticArgs.empty()) {
4210 llvm::Constant *Info = llvm::ConstantStruct::getAnon(V: StaticArgs);
4211 auto *InfoPtr = new llvm::GlobalVariable(
4212 CGM.getModule(), Info->getType(),
4213 // Non-constant global is used in a handler to deduplicate reports.
4214 // TODO: change deduplication logic and make it constant.
4215 /*isConstant=*/false, llvm::GlobalVariable::PrivateLinkage, Info, "",
4216 nullptr, llvm::GlobalVariable::NotThreadLocal,
4217 CGM.getDataLayout().getDefaultGlobalsAddressSpace());
4218 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4219 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV: InfoPtr);
4220 Args.push_back(Elt: InfoPtr);
4221 ArgTypes.push_back(Elt: Args.back()->getType());
4222 }
4223
4224 for (llvm::Value *DynamicArg : DynamicArgs) {
4225 Args.push_back(Elt: EmitCheckValue(V: DynamicArg));
4226 ArgTypes.push_back(Elt: IntPtrTy);
4227 }
4228
4229 llvm::FunctionType *FnType =
4230 llvm::FunctionType::get(Result: CGM.VoidTy, Params: ArgTypes, isVarArg: false);
4231
4232 if (!FatalCond || !RecoverableCond) {
4233 // Simple case: we need to generate a single handler call, either
4234 // fatal, or non-fatal.
4235 emitCheckHandlerCall(CGF&: *this, FnType, FnArgs: Args, CheckHandler, RecoverKind,
4236 IsFatal: (FatalCond != nullptr), ContBB: Cont, NoMerge);
4237 } else {
4238 // Emit two handler calls: first one for set of unrecoverable checks,
4239 // another one for recoverable.
4240 llvm::BasicBlock *NonFatalHandlerBB =
4241 createBasicBlock(name: "non_fatal." + CheckName);
4242 llvm::BasicBlock *FatalHandlerBB = createBasicBlock(name: "fatal." + CheckName);
4243 Builder.CreateCondBr(Cond: FatalCond, True: NonFatalHandlerBB, False: FatalHandlerBB);
4244 EmitBlock(BB: FatalHandlerBB);
4245 emitCheckHandlerCall(CGF&: *this, FnType, FnArgs: Args, CheckHandler, RecoverKind, IsFatal: true,
4246 ContBB: NonFatalHandlerBB, NoMerge);
4247 EmitBlock(BB: NonFatalHandlerBB);
4248 emitCheckHandlerCall(CGF&: *this, FnType, FnArgs: Args, CheckHandler, RecoverKind, IsFatal: false,
4249 ContBB: Cont, NoMerge);
4250 }
4251
4252 EmitBlock(BB: Cont);
4253}
4254
4255void CodeGenFunction::EmitCfiSlowPathCheck(
4256 SanitizerKind::SanitizerOrdinal Ordinal, llvm::Value *Cond,
4257 llvm::ConstantInt *TypeId, llvm::Value *Ptr,
4258 ArrayRef<llvm::Constant *> StaticArgs) {
4259 llvm::BasicBlock *Cont = createBasicBlock(name: "cfi.cont");
4260
4261 llvm::BasicBlock *CheckBB = createBasicBlock(name: "cfi.slowpath");
4262 llvm::BranchInst *BI = Builder.CreateCondBr(Cond, True: Cont, False: CheckBB);
4263
4264 llvm::MDBuilder MDHelper(getLLVMContext());
4265 llvm::MDNode *Node = MDHelper.createLikelyBranchWeights();
4266 BI->setMetadata(KindID: llvm::LLVMContext::MD_prof, Node);
4267
4268 EmitBlock(BB: CheckBB);
4269
4270 bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(O: Ordinal);
4271
4272 llvm::CallInst *CheckCall;
4273 llvm::FunctionCallee SlowPathFn;
4274 if (WithDiag) {
4275 llvm::Constant *Info = llvm::ConstantStruct::getAnon(V: StaticArgs);
4276 auto *InfoPtr =
4277 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
4278 llvm::GlobalVariable::PrivateLinkage, Info);
4279 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4280 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV: InfoPtr);
4281
4282 SlowPathFn = CGM.getModule().getOrInsertFunction(
4283 Name: "__cfi_slowpath_diag",
4284 T: llvm::FunctionType::get(Result: VoidTy, Params: {Int64Ty, Int8PtrTy, Int8PtrTy},
4285 isVarArg: false));
4286 CheckCall = Builder.CreateCall(Callee: SlowPathFn, Args: {TypeId, Ptr, InfoPtr});
4287 } else {
4288 SlowPathFn = CGM.getModule().getOrInsertFunction(
4289 Name: "__cfi_slowpath",
4290 T: llvm::FunctionType::get(Result: VoidTy, Params: {Int64Ty, Int8PtrTy}, isVarArg: false));
4291 CheckCall = Builder.CreateCall(Callee: SlowPathFn, Args: {TypeId, Ptr});
4292 }
4293
4294 CGM.setDSOLocal(
4295 cast<llvm::GlobalValue>(Val: SlowPathFn.getCallee()->stripPointerCasts()));
4296 CheckCall->setDoesNotThrow();
4297
4298 EmitBlock(BB: Cont);
4299}
4300
4301// Emit a stub for __cfi_check function so that the linker knows about this
4302// symbol in LTO mode.
4303void CodeGenFunction::EmitCfiCheckStub() {
4304 llvm::Module *M = &CGM.getModule();
4305 ASTContext &C = getContext();
4306 QualType QInt64Ty = C.getIntTypeForBitwidth(DestWidth: 64, Signed: false);
4307
4308 FunctionArgList FnArgs;
4309 ImplicitParamDecl ArgCallsiteTypeId(C, QInt64Ty, ImplicitParamKind::Other);
4310 ImplicitParamDecl ArgAddr(C, C.VoidPtrTy, ImplicitParamKind::Other);
4311 ImplicitParamDecl ArgCFICheckFailData(C, C.VoidPtrTy,
4312 ImplicitParamKind::Other);
4313 FnArgs.push_back(Elt: &ArgCallsiteTypeId);
4314 FnArgs.push_back(Elt: &ArgAddr);
4315 FnArgs.push_back(Elt: &ArgCFICheckFailData);
4316 const CGFunctionInfo &FI =
4317 CGM.getTypes().arrangeBuiltinFunctionDeclaration(resultType: C.VoidTy, args: FnArgs);
4318
4319 llvm::Function *F = llvm::Function::Create(
4320 Ty: llvm::FunctionType::get(Result: VoidTy, Params: {Int64Ty, VoidPtrTy, VoidPtrTy}, isVarArg: false),
4321 Linkage: llvm::GlobalValue::WeakAnyLinkage, N: "__cfi_check", M);
4322 CGM.SetLLVMFunctionAttributes(GD: GlobalDecl(), Info: FI, F, /*IsThunk=*/false);
4323 CGM.SetLLVMFunctionAttributesForDefinition(D: nullptr, F);
4324 F->setAlignment(llvm::Align(4096));
4325 CGM.setDSOLocal(F);
4326
4327 llvm::LLVMContext &Ctx = M->getContext();
4328 llvm::BasicBlock *BB = llvm::BasicBlock::Create(Context&: Ctx, Name: "entry", Parent: F);
4329 // CrossDSOCFI pass is not executed if there is no executable code.
4330 SmallVector<llvm::Value*> Args{F->getArg(i: 2), F->getArg(i: 1)};
4331 llvm::CallInst::Create(Func: M->getFunction(Name: "__cfi_check_fail"), Args, NameStr: "", InsertBefore: BB);
4332 llvm::ReturnInst::Create(C&: Ctx, retVal: nullptr, InsertBefore: BB);
4333}
4334
4335// This function is basically a switch over the CFI failure kind, which is
4336// extracted from CFICheckFailData (1st function argument). Each case is either
4337// llvm.trap or a call to one of the two runtime handlers, based on
4338// -fsanitize-trap and -fsanitize-recover settings. Default case (invalid
4339// failure kind) traps, but this should really never happen. CFICheckFailData
4340// can be nullptr if the calling module has -fsanitize-trap behavior for this
4341// check kind; in this case __cfi_check_fail traps as well.
4342void CodeGenFunction::EmitCfiCheckFail() {
4343 auto CheckHandler = SanitizerHandler::CFICheckFail;
4344 // TODO: the SanitizerKind is not yet determined for this check (and might
4345 // not even be available, if Data == nullptr). However, we still want to
4346 // annotate the instrumentation. We approximate this by using all the CFI
4347 // kinds.
4348 SanitizerDebugLocation SanScope(
4349 this,
4350 {SanitizerKind::SO_CFIVCall, SanitizerKind::SO_CFINVCall,
4351 SanitizerKind::SO_CFIDerivedCast, SanitizerKind::SO_CFIUnrelatedCast,
4352 SanitizerKind::SO_CFIICall},
4353 CheckHandler);
4354 FunctionArgList Args;
4355 ImplicitParamDecl ArgData(getContext(), getContext().VoidPtrTy,
4356 ImplicitParamKind::Other);
4357 ImplicitParamDecl ArgAddr(getContext(), getContext().VoidPtrTy,
4358 ImplicitParamKind::Other);
4359 Args.push_back(Elt: &ArgData);
4360 Args.push_back(Elt: &ArgAddr);
4361
4362 const CGFunctionInfo &FI =
4363 CGM.getTypes().arrangeBuiltinFunctionDeclaration(resultType: getContext().VoidTy, args: Args);
4364
4365 llvm::Function *F = llvm::Function::Create(
4366 Ty: llvm::FunctionType::get(Result: VoidTy, Params: {VoidPtrTy, VoidPtrTy}, isVarArg: false),
4367 Linkage: llvm::GlobalValue::WeakODRLinkage, N: "__cfi_check_fail", M: &CGM.getModule());
4368
4369 CGM.SetLLVMFunctionAttributes(GD: GlobalDecl(), Info: FI, F, /*IsThunk=*/false);
4370 CGM.SetLLVMFunctionAttributesForDefinition(D: nullptr, F);
4371 F->setVisibility(llvm::GlobalValue::HiddenVisibility);
4372
4373 StartFunction(GD: GlobalDecl(), RetTy: CGM.getContext().VoidTy, Fn: F, FnInfo: FI, Args,
4374 Loc: SourceLocation());
4375
4376 ApplyDebugLocation ADL = ApplyDebugLocation::CreateArtificial(CGF&: *this);
4377
4378 // This function is not affected by NoSanitizeList. This function does
4379 // not have a source location, but "src:*" would still apply. Revert any
4380 // changes to SanOpts made in StartFunction.
4381 SanOpts = CGM.getLangOpts().Sanitize;
4382
4383 llvm::Value *Data =
4384 EmitLoadOfScalar(Addr: GetAddrOfLocalVar(VD: &ArgData), /*Volatile=*/false,
4385 Ty: CGM.getContext().VoidPtrTy, Loc: ArgData.getLocation());
4386 llvm::Value *Addr =
4387 EmitLoadOfScalar(Addr: GetAddrOfLocalVar(VD: &ArgAddr), /*Volatile=*/false,
4388 Ty: CGM.getContext().VoidPtrTy, Loc: ArgAddr.getLocation());
4389
4390 // Data == nullptr means the calling module has trap behaviour for this check.
4391 llvm::Value *DataIsNotNullPtr =
4392 Builder.CreateICmpNE(LHS: Data, RHS: llvm::ConstantPointerNull::get(T: Int8PtrTy));
4393 // TODO: since there is no data, we don't know the CheckKind, and therefore
4394 // cannot inspect CGM.getCodeGenOpts().SanitizeMergeHandlers. We default to
4395 // NoMerge = false. Users can disable merging by disabling optimization.
4396 EmitTrapCheck(Checked: DataIsNotNullPtr, CheckHandlerID: SanitizerHandler::CFICheckFail,
4397 /*NoMerge=*/false);
4398
4399 llvm::StructType *SourceLocationTy =
4400 llvm::StructType::get(elt1: VoidPtrTy, elts: Int32Ty, elts: Int32Ty);
4401 llvm::StructType *CfiCheckFailDataTy =
4402 llvm::StructType::get(elt1: Int8Ty, elts: SourceLocationTy, elts: VoidPtrTy);
4403
4404 llvm::Value *V = Builder.CreateConstGEP2_32(
4405 Ty: CfiCheckFailDataTy, Ptr: Builder.CreatePointerCast(V: Data, DestTy: DefaultPtrTy), Idx0: 0, Idx1: 0);
4406
4407 Address CheckKindAddr(V, Int8Ty, getIntAlign());
4408 llvm::Value *CheckKind = Builder.CreateLoad(Addr: CheckKindAddr);
4409
4410 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
4411 Context&: CGM.getLLVMContext(),
4412 MD: llvm::MDString::get(Context&: CGM.getLLVMContext(), Str: "all-vtables"));
4413 llvm::Value *ValidVtable = Builder.CreateZExt(
4414 V: Builder.CreateCall(Callee: CGM.getIntrinsic(IID: llvm::Intrinsic::type_test),
4415 Args: {Addr, AllVtables}),
4416 DestTy: IntPtrTy);
4417
4418 const std::pair<int, SanitizerKind::SanitizerOrdinal> CheckKinds[] = {
4419 {CFITCK_VCall, SanitizerKind::SO_CFIVCall},
4420 {CFITCK_NVCall, SanitizerKind::SO_CFINVCall},
4421 {CFITCK_DerivedCast, SanitizerKind::SO_CFIDerivedCast},
4422 {CFITCK_UnrelatedCast, SanitizerKind::SO_CFIUnrelatedCast},
4423 {CFITCK_ICall, SanitizerKind::SO_CFIICall}};
4424
4425 for (auto CheckKindOrdinalPair : CheckKinds) {
4426 int Kind = CheckKindOrdinalPair.first;
4427 SanitizerKind::SanitizerOrdinal Ordinal = CheckKindOrdinalPair.second;
4428
4429 // TODO: we could apply SanitizerAnnotateDebugInfo(Ordinal) instead of
4430 // relying on the SanitizerScope with all CFI ordinals
4431
4432 llvm::Value *Cond =
4433 Builder.CreateICmpNE(LHS: CheckKind, RHS: llvm::ConstantInt::get(Ty: Int8Ty, V: Kind));
4434 if (CGM.getLangOpts().Sanitize.has(O: Ordinal))
4435 EmitCheck(Checked: std::make_pair(x&: Cond, y&: Ordinal), CheckHandler: SanitizerHandler::CFICheckFail,
4436 StaticArgs: {}, DynamicArgs: {Data, Addr, ValidVtable});
4437 else
4438 // TODO: we can't rely on CGM.getCodeGenOpts().SanitizeMergeHandlers.
4439 // Although the compiler allows SanitizeMergeHandlers to be set
4440 // independently of CGM.getLangOpts().Sanitize, Driver/SanitizerArgs.cpp
4441 // requires that SanitizeMergeHandlers is a subset of Sanitize.
4442 EmitTrapCheck(Checked: Cond, CheckHandlerID: CheckHandler, /*NoMerge=*/false);
4443 }
4444
4445 FinishFunction();
4446 // The only reference to this function will be created during LTO link.
4447 // Make sure it survives until then.
4448 CGM.addUsedGlobal(GV: F);
4449}
4450
4451void CodeGenFunction::EmitUnreachable(SourceLocation Loc) {
4452 if (SanOpts.has(K: SanitizerKind::Unreachable)) {
4453 auto CheckOrdinal = SanitizerKind::SO_Unreachable;
4454 auto CheckHandler = SanitizerHandler::BuiltinUnreachable;
4455 SanitizerDebugLocation SanScope(this, {CheckOrdinal}, CheckHandler);
4456 EmitCheck(Checked: std::make_pair(x: static_cast<llvm::Value *>(Builder.getFalse()),
4457 y&: CheckOrdinal),
4458 CheckHandler, StaticArgs: EmitCheckSourceLocation(Loc), DynamicArgs: {});
4459 }
4460 Builder.CreateUnreachable();
4461}
4462
4463void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked,
4464 SanitizerHandler CheckHandlerID,
4465 bool NoMerge, const TrapReason *TR) {
4466 llvm::BasicBlock *Cont = createBasicBlock(name: "cont");
4467
4468 // If we're optimizing, collapse all calls to trap down to just one per
4469 // check-type per function to save on code size.
4470 if ((int)TrapBBs.size() <= CheckHandlerID)
4471 TrapBBs.resize(N: CheckHandlerID + 1);
4472
4473 llvm::BasicBlock *&TrapBB = TrapBBs[CheckHandlerID];
4474
4475 llvm::DILocation *TrapLocation = Builder.getCurrentDebugLocation();
4476 llvm::StringRef TrapMessage;
4477 llvm::StringRef TrapCategory;
4478 auto DebugTrapReasonKind = CGM.getCodeGenOpts().getSanitizeDebugTrapReasons();
4479 if (TR && !TR->isEmpty() &&
4480 DebugTrapReasonKind ==
4481 CodeGenOptions::SanitizeDebugTrapReasonKind::Detailed) {
4482 TrapMessage = TR->getMessage();
4483 TrapCategory = TR->getCategory();
4484 } else {
4485 TrapMessage = GetUBSanTrapForHandler(ID: CheckHandlerID);
4486 TrapCategory = "Undefined Behavior Sanitizer";
4487 }
4488
4489 if (getDebugInfo() && !TrapMessage.empty() &&
4490 DebugTrapReasonKind !=
4491 CodeGenOptions::SanitizeDebugTrapReasonKind::None &&
4492 TrapLocation) {
4493 TrapLocation = getDebugInfo()->CreateTrapFailureMessageFor(
4494 TrapLocation, Category: TrapCategory, FailureMsg: TrapMessage);
4495 }
4496
4497 NoMerge = NoMerge || !CGM.getCodeGenOpts().OptimizationLevel ||
4498 (CurCodeDecl && CurCodeDecl->hasAttr<OptimizeNoneAttr>());
4499
4500 llvm::MDBuilder MDHelper(getLLVMContext());
4501 if (TrapBB && !NoMerge) {
4502 auto Call = TrapBB->begin();
4503 assert(isa<llvm::CallInst>(Call) && "Expected call in trap BB");
4504
4505 Call->applyMergedLocation(LocA: Call->getDebugLoc(), LocB: TrapLocation);
4506
4507 Builder.CreateCondBr(Cond: Checked, True: Cont, False: TrapBB,
4508 BranchWeights: MDHelper.createLikelyBranchWeights());
4509 } else {
4510 TrapBB = createBasicBlock(name: "trap");
4511 Builder.CreateCondBr(Cond: Checked, True: Cont, False: TrapBB,
4512 BranchWeights: MDHelper.createLikelyBranchWeights());
4513 EmitBlock(BB: TrapBB);
4514
4515 ApplyDebugLocation applyTrapDI(*this, TrapLocation);
4516
4517 llvm::CallInst *TrapCall;
4518 if (CGM.getCodeGenOpts().SanitizeTrapLoop)
4519 TrapCall =
4520 Builder.CreateCall(Callee: CGM.getIntrinsic(IID: llvm::Intrinsic::looptrap));
4521 else
4522 TrapCall = Builder.CreateCall(
4523 Callee: CGM.getIntrinsic(IID: llvm::Intrinsic::ubsantrap),
4524 Args: llvm::ConstantInt::get(Ty: CGM.Int8Ty, V: CheckHandlerID));
4525
4526 if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
4527 auto A = llvm::Attribute::get(Context&: getLLVMContext(), Kind: "trap-func-name",
4528 Val: CGM.getCodeGenOpts().TrapFuncName);
4529 TrapCall->addFnAttr(Attr: A);
4530 }
4531 if (NoMerge)
4532 TrapCall->addFnAttr(Kind: llvm::Attribute::NoMerge);
4533 TrapCall->setDoesNotReturn();
4534 TrapCall->setDoesNotThrow();
4535 Builder.CreateUnreachable();
4536 }
4537
4538 EmitBlock(BB: Cont);
4539}
4540
4541llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
4542 llvm::CallInst *TrapCall =
4543 Builder.CreateCall(Callee: CGM.getIntrinsic(IID: IntrID));
4544
4545 if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
4546 auto A = llvm::Attribute::get(Context&: getLLVMContext(), Kind: "trap-func-name",
4547 Val: CGM.getCodeGenOpts().TrapFuncName);
4548 TrapCall->addFnAttr(Attr: A);
4549 }
4550
4551 if (InNoMergeAttributedStmt)
4552 TrapCall->addFnAttr(Kind: llvm::Attribute::NoMerge);
4553 return TrapCall;
4554}
4555
4556Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E,
4557 LValueBaseInfo *BaseInfo,
4558 TBAAAccessInfo *TBAAInfo) {
4559 assert(E->getType()->isArrayType() &&
4560 "Array to pointer decay must have array source type!");
4561
4562 // Expressions of array type can't be bitfields or vector elements.
4563 LValue LV = EmitLValue(E);
4564 Address Addr = LV.getAddress();
4565
4566 // If the array type was an incomplete type, we need to make sure
4567 // the decay ends up being the right type.
4568 llvm::Type *NewTy = ConvertType(T: E->getType());
4569 Addr = Addr.withElementType(ElemTy: NewTy);
4570
4571 // Note that VLA pointers are always decayed, so we don't need to do
4572 // anything here.
4573 if (!E->getType()->isVariableArrayType()) {
4574 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
4575 "Expected pointer to array");
4576
4577 if (getLangOpts().EmitStructuredGEP) {
4578 // Array-to-pointer decay for an SGEP is a no-op as we don't do any
4579 // logical indexing. See #179951 for some additional context.
4580 auto *SGEP =
4581 Builder.CreateStructuredGEP(BaseType: NewTy, PtrBase: Addr.emitRawPointer(CGF&: *this), Indices: {});
4582 Addr = Address(SGEP, NewTy, Addr.getAlignment(), Addr.isKnownNonNull());
4583 } else {
4584 Addr = Builder.CreateConstArrayGEP(Addr, Index: 0, Name: "arraydecay");
4585 }
4586 }
4587
4588 // The result of this decay conversion points to an array element within the
4589 // base lvalue. However, since TBAA currently does not support representing
4590 // accesses to elements of member arrays, we conservatively represent accesses
4591 // to the pointee object as if it had no any base lvalue specified.
4592 // TODO: Support TBAA for member arrays.
4593 QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
4594 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
4595 if (TBAAInfo) *TBAAInfo = CGM.getTBAAAccessInfo(AccessType: EltType);
4596
4597 return Addr.withElementType(ElemTy: ConvertTypeForMem(T: EltType));
4598}
4599
4600/// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
4601/// array to pointer, return the array subexpression.
4602static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
4603 // If this isn't just an array->pointer decay, bail out.
4604 const auto *CE = dyn_cast<CastExpr>(Val: E);
4605 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
4606 return nullptr;
4607
4608 // If this is a decay from variable width array, bail out.
4609 const Expr *SubExpr = CE->getSubExpr();
4610 if (SubExpr->getType()->isVariableArrayType())
4611 return nullptr;
4612
4613 return SubExpr;
4614}
4615
4616static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF,
4617 llvm::Type *elemType,
4618 llvm::Value *ptr,
4619 ArrayRef<llvm::Value*> indices,
4620 bool inbounds,
4621 bool signedIndices,
4622 SourceLocation loc,
4623 const llvm::Twine &name = "arrayidx") {
4624 if (inbounds && CGF.getLangOpts().EmitStructuredGEP)
4625 return CGF.Builder.CreateStructuredGEP(BaseType: elemType, PtrBase: ptr, Indices: indices);
4626
4627 if (inbounds) {
4628 return CGF.EmitCheckedInBoundsGEP(ElemTy: elemType, Ptr: ptr, IdxList: indices, SignedIndices: signedIndices,
4629 IsSubtraction: CodeGenFunction::NotSubtraction, Loc: loc,
4630 Name: name);
4631 } else {
4632 return CGF.Builder.CreateGEP(Ty: elemType, Ptr: ptr, IdxList: indices, Name: name);
4633 }
4634}
4635
4636static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
4637 ArrayRef<llvm::Value *> indices,
4638 llvm::Type *arrayType,
4639 llvm::Type *elementType, bool inbounds,
4640 bool signedIndices, SourceLocation loc,
4641 CharUnits align,
4642 const llvm::Twine &name = "arrayidx") {
4643 if (inbounds && CGF.getLangOpts().EmitStructuredGEP)
4644 return RawAddress(CGF.Builder.CreateStructuredGEP(BaseType: arrayType,
4645 PtrBase: addr.emitRawPointer(CGF),
4646 Indices: indices.drop_front()),
4647 elementType, align);
4648
4649 if (inbounds) {
4650 return CGF.EmitCheckedInBoundsGEP(Addr: addr, IdxList: indices, elementType, SignedIndices: signedIndices,
4651 IsSubtraction: CodeGenFunction::NotSubtraction, Loc: loc,
4652 Align: align, Name: name);
4653 } else {
4654 return CGF.Builder.CreateGEP(Addr: addr, IdxList: indices, ElementType: elementType, Align: align, Name: name);
4655 }
4656}
4657
4658static QualType getFixedSizeElementType(const ASTContext &ctx,
4659 const VariableArrayType *vla) {
4660 QualType eltType;
4661 do {
4662 eltType = vla->getElementType();
4663 } while ((vla = ctx.getAsVariableArrayType(T: eltType)));
4664 return eltType;
4665}
4666
4667static bool hasBPFPreserveStaticOffset(const RecordDecl *D) {
4668 return D && D->hasAttr<BPFPreserveStaticOffsetAttr>();
4669}
4670
4671static bool hasBPFPreserveStaticOffset(const Expr *E) {
4672 if (!E)
4673 return false;
4674 QualType PointeeType = E->getType()->getPointeeType();
4675 if (PointeeType.isNull())
4676 return false;
4677 if (const auto *BaseDecl = PointeeType->getAsRecordDecl())
4678 return hasBPFPreserveStaticOffset(D: BaseDecl);
4679 return false;
4680}
4681
4682// Wraps Addr with a call to llvm.preserve.static.offset intrinsic.
4683static Address wrapWithBPFPreserveStaticOffset(CodeGenFunction &CGF,
4684 Address &Addr) {
4685 if (!CGF.getTarget().getTriple().isBPF())
4686 return Addr;
4687
4688 llvm::Function *Fn =
4689 CGF.CGM.getIntrinsic(IID: llvm::Intrinsic::preserve_static_offset);
4690 llvm::CallInst *Call = CGF.Builder.CreateCall(Callee: Fn, Args: {Addr.emitRawPointer(CGF)});
4691 return Address(Call, Addr.getElementType(), Addr.getAlignment());
4692}
4693
4694/// Given an array base, check whether its member access belongs to a record
4695/// with preserve_access_index attribute or not.
4696static bool IsPreserveAIArrayBase(CodeGenFunction &CGF, const Expr *ArrayBase) {
4697 if (!ArrayBase || !CGF.getDebugInfo())
4698 return false;
4699
4700 // Only support base as either a MemberExpr or DeclRefExpr.
4701 // DeclRefExpr to cover cases like:
4702 // struct s { int a; int b[10]; };
4703 // struct s *p;
4704 // p[1].a
4705 // p[1] will generate a DeclRefExpr and p[1].a is a MemberExpr.
4706 // p->b[5] is a MemberExpr example.
4707 const Expr *E = ArrayBase->IgnoreImpCasts();
4708 if (const auto *ME = dyn_cast<MemberExpr>(Val: E))
4709 return ME->getMemberDecl()->hasAttr<BPFPreserveAccessIndexAttr>();
4710
4711 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
4712 const auto *VarDef = dyn_cast<VarDecl>(Val: DRE->getDecl());
4713 if (!VarDef)
4714 return false;
4715
4716 const auto *PtrT = VarDef->getType()->getAs<PointerType>();
4717 if (!PtrT)
4718 return false;
4719
4720 const auto *PointeeT = PtrT->getPointeeType()
4721 ->getUnqualifiedDesugaredType();
4722 if (const auto *RecT = dyn_cast<RecordType>(Val: PointeeT))
4723 return RecT->getDecl()
4724 ->getMostRecentDecl()
4725 ->hasAttr<BPFPreserveAccessIndexAttr>();
4726 return false;
4727 }
4728
4729 return false;
4730}
4731
4732static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
4733 ArrayRef<llvm::Value *> indices,
4734 QualType eltType, bool inbounds,
4735 bool signedIndices, SourceLocation loc,
4736 QualType *arrayType = nullptr,
4737 const Expr *Base = nullptr,
4738 const llvm::Twine &name = "arrayidx") {
4739 // All the indices except that last must be zero.
4740#ifndef NDEBUG
4741 for (auto *idx : indices.drop_back())
4742 assert(isa<llvm::ConstantInt>(idx) &&
4743 cast<llvm::ConstantInt>(idx)->isZero());
4744#endif
4745
4746 // Determine the element size of the statically-sized base. This is
4747 // the thing that the indices are expressed in terms of.
4748 if (auto vla = CGF.getContext().getAsVariableArrayType(T: eltType)) {
4749 eltType = getFixedSizeElementType(ctx: CGF.getContext(), vla);
4750 }
4751
4752 // We can use that to compute the best alignment of the element.
4753 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(T: eltType);
4754 CharUnits eltAlign =
4755 getArrayElementAlign(arrayAlign: addr.getAlignment(), idx: indices.back(), eltSize);
4756
4757 if (hasBPFPreserveStaticOffset(E: Base))
4758 addr = wrapWithBPFPreserveStaticOffset(CGF, Addr&: addr);
4759
4760 llvm::Value *eltPtr;
4761 auto LastIndex = dyn_cast<llvm::ConstantInt>(Val: indices.back());
4762 if (!LastIndex ||
4763 (!CGF.IsInPreservedAIRegion && !IsPreserveAIArrayBase(CGF, ArrayBase: Base))) {
4764 addr = emitArraySubscriptGEP(CGF, addr, indices,
4765 arrayType: arrayType ? CGF.ConvertTypeForMem(T: *arrayType)
4766 : nullptr,
4767 elementType: CGF.ConvertTypeForMem(T: eltType), inbounds,
4768 signedIndices, loc, align: eltAlign, name);
4769 return addr;
4770 } else {
4771 // Remember the original array subscript for bpf target
4772 unsigned idx = LastIndex->getZExtValue();
4773 llvm::DIType *DbgInfo = nullptr;
4774 if (arrayType)
4775 DbgInfo = CGF.getDebugInfo()->getOrCreateStandaloneType(Ty: *arrayType, Loc: loc);
4776 eltPtr = CGF.Builder.CreatePreserveArrayAccessIndex(
4777 ElTy: addr.getElementType(), Base: addr.emitRawPointer(CGF), Dimension: indices.size() - 1,
4778 LastIndex: idx, DbgInfo);
4779 }
4780
4781 return Address(eltPtr, CGF.ConvertTypeForMem(T: eltType), eltAlign);
4782}
4783
4784namespace {
4785
4786/// StructFieldAccess is a simple visitor class to grab the first l-value to
4787/// r-value cast Expr.
4788struct StructFieldAccess
4789 : public ConstStmtVisitor<StructFieldAccess, const Expr *> {
4790 const Expr *VisitCastExpr(const CastExpr *E) {
4791 if (E->getCastKind() == CK_LValueToRValue)
4792 return E;
4793 return Visit(S: E->getSubExpr());
4794 }
4795 const Expr *VisitParenExpr(const ParenExpr *E) {
4796 return Visit(S: E->getSubExpr());
4797 }
4798};
4799
4800} // end anonymous namespace
4801
4802/// The offset of a field from the beginning of the record.
4803static bool getFieldOffsetInBits(CodeGenFunction &CGF, const RecordDecl *RD,
4804 const FieldDecl *Field, int64_t &Offset) {
4805 ASTContext &Ctx = CGF.getContext();
4806 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(D: RD);
4807 unsigned FieldNo = 0;
4808
4809 for (const FieldDecl *FD : RD->fields()) {
4810 if (FD == Field) {
4811 Offset += Layout.getFieldOffset(FieldNo);
4812 return true;
4813 }
4814
4815 QualType Ty = FD->getType();
4816 if (Ty->isRecordType())
4817 if (getFieldOffsetInBits(CGF, RD: Ty->getAsRecordDecl(), Field, Offset)) {
4818 Offset += Layout.getFieldOffset(FieldNo);
4819 return true;
4820 }
4821
4822 if (!RD->isUnion())
4823 ++FieldNo;
4824 }
4825
4826 return false;
4827}
4828
4829/// Returns the relative offset difference between \p FD1 and \p FD2.
4830/// \code
4831/// offsetof(struct foo, FD1) - offsetof(struct foo, FD2)
4832/// \endcode
4833/// Both fields must be within the same struct.
4834static std::optional<int64_t> getOffsetDifferenceInBits(CodeGenFunction &CGF,
4835 const FieldDecl *FD1,
4836 const FieldDecl *FD2) {
4837 const RecordDecl *FD1OuterRec =
4838 FD1->getParent()->getOuterLexicalRecordContext();
4839 const RecordDecl *FD2OuterRec =
4840 FD2->getParent()->getOuterLexicalRecordContext();
4841
4842 if (FD1OuterRec != FD2OuterRec)
4843 // Fields must be within the same RecordDecl.
4844 return std::optional<int64_t>();
4845
4846 int64_t FD1Offset = 0;
4847 if (!getFieldOffsetInBits(CGF, RD: FD1OuterRec, Field: FD1, Offset&: FD1Offset))
4848 return std::optional<int64_t>();
4849
4850 int64_t FD2Offset = 0;
4851 if (!getFieldOffsetInBits(CGF, RD: FD2OuterRec, Field: FD2, Offset&: FD2Offset))
4852 return std::optional<int64_t>();
4853
4854 return std::make_optional<int64_t>(t: FD1Offset - FD2Offset);
4855}
4856
4857/// EmitCountedByBoundsChecking - If the array being accessed has a "counted_by"
4858/// attribute, generate bounds checking code. The "count" field is at the top
4859/// level of the struct or in an anonymous struct, that's also at the top level.
4860/// Future expansions may allow the "count" to reside at any place in the
4861/// struct, but the value of "counted_by" will be a "simple" path to the count,
4862/// i.e. "a.b.count", so we shouldn't need the full force of EmitLValue or
4863/// similar to emit the correct GEP.
4864void CodeGenFunction::EmitCountedByBoundsChecking(
4865 const Expr *ArrayExpr, QualType ArrayType, Address ArrayInst,
4866 QualType IndexType, llvm::Value *IndexVal, bool Accessed,
4867 bool FlexibleArray) {
4868 const auto *ME = dyn_cast<MemberExpr>(Val: ArrayExpr->IgnoreImpCasts());
4869 if (!ME || !ME->getMemberDecl()->getType()->isCountAttributedType())
4870 return;
4871
4872 const LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
4873 getLangOpts().getStrictFlexArraysLevel();
4874 if (FlexibleArray &&
4875 !ME->isFlexibleArrayMemberLike(Context: getContext(), StrictFlexArraysLevel))
4876 return;
4877
4878 const FieldDecl *FD = cast<FieldDecl>(Val: ME->getMemberDecl());
4879 const FieldDecl *CountFD = FD->findCountedByField();
4880 if (!CountFD)
4881 return;
4882
4883 if (std::optional<int64_t> Diff =
4884 getOffsetDifferenceInBits(CGF&: *this, FD1: CountFD, FD2: FD)) {
4885 if (!ArrayInst.isValid()) {
4886 // An invalid Address indicates we're checking a pointer array access.
4887 // Emit the checked L-Value here.
4888 LValue LV = EmitCheckedLValue(E: ArrayExpr, TCK: TCK_MemberAccess);
4889 ArrayInst = LV.getAddress();
4890 }
4891
4892 // FIXME: The 'static_cast' is necessary, otherwise the result turns into a
4893 // uint64_t, which messes things up if we have a negative offset difference.
4894 Diff = *Diff / static_cast<int64_t>(CGM.getContext().getCharWidth());
4895
4896 // Create a GEP with the byte offset between the counted object and the
4897 // count and use that to load the count value.
4898 ArrayInst = Builder.CreatePointerBitCastOrAddrSpaceCast(Addr: ArrayInst,
4899 Ty: Int8PtrTy, ElementTy: Int8Ty);
4900
4901 llvm::Type *BoundsType = ConvertType(T: CountFD->getType());
4902 llvm::Value *BoundsVal =
4903 Builder.CreateInBoundsGEP(Ty: Int8Ty, Ptr: ArrayInst.emitRawPointer(CGF&: *this),
4904 IdxList: Builder.getInt32(C: *Diff), Name: ".counted_by.gep");
4905 BoundsVal = Builder.CreateAlignedLoad(Ty: BoundsType, Addr: BoundsVal, Align: getIntAlign(),
4906 Name: ".counted_by.load");
4907
4908 // Now emit the bounds checking.
4909 EmitBoundsCheckImpl(ArrayExpr, ArrayBaseType: ArrayType, IndexVal, IndexType, BoundsVal,
4910 BoundsType: CountFD->getType(), Accessed);
4911 }
4912}
4913
4914LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
4915 bool Accessed) {
4916 // The index must always be an integer, which is not an aggregate. Emit it
4917 // in lexical order (this complexity is, sadly, required by C++17).
4918 llvm::Value *IdxPre =
4919 (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E: E->getIdx()) : nullptr;
4920 bool SignedIndices = false;
4921 auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * {
4922 auto *Idx = IdxPre;
4923 if (E->getLHS() != E->getIdx()) {
4924 assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS");
4925 Idx = EmitScalarExpr(E: E->getIdx());
4926 }
4927
4928 QualType IdxTy = E->getIdx()->getType();
4929 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
4930 SignedIndices |= IdxSigned;
4931
4932 if (SanOpts.has(K: SanitizerKind::ArrayBounds))
4933 EmitBoundsCheck(ArrayExpr: E, ArrayExprBase: E->getBase(), IndexVal: Idx, IndexType: IdxTy, Accessed);
4934
4935 // Extend or truncate the index type to 32 or 64-bits.
4936 if (Promote && Idx->getType() != IntPtrTy)
4937 Idx = Builder.CreateIntCast(V: Idx, DestTy: IntPtrTy, isSigned: IdxSigned, Name: "idxprom");
4938
4939 return Idx;
4940 };
4941 IdxPre = nullptr;
4942
4943 // If the base is a vector type, then we are forming a vector element lvalue
4944 // with this subscript.
4945 if (E->getBase()->getType()->isSubscriptableVectorType() &&
4946 !isa<ExtVectorElementExpr>(Val: E->getBase())) {
4947 // Emit the vector as an lvalue to get its address.
4948 LValue LHS = EmitLValue(E: E->getBase());
4949 auto *Idx = EmitIdxAfterBase(/*Promote*/false);
4950 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
4951 return LValue::MakeVectorElt(vecAddress: LHS.getAddress(), Idx, type: E->getBase()->getType(),
4952 BaseInfo: LHS.getBaseInfo(), TBAAInfo: TBAAAccessInfo());
4953 }
4954
4955 // The HLSL runtime handles subscript expressions on global resource arrays
4956 // and objects with HLSL buffer layouts.
4957 if (getLangOpts().HLSL) {
4958 std::optional<LValue> LV;
4959 if (E->getType()->isHLSLResourceRecord() ||
4960 E->getType()->isHLSLResourceRecordArray()) {
4961 LV = CGM.getHLSLRuntime().emitResourceArraySubscriptExpr(E, CGF&: *this);
4962 } else if (E->getType().getAddressSpace() == LangAS::hlsl_constant) {
4963 LV = CGM.getHLSLRuntime().emitBufferArraySubscriptExpr(E, CGF&: *this,
4964 EmitIdxAfterBase);
4965 }
4966 if (LV.has_value())
4967 return *LV;
4968 }
4969
4970 // All the other cases basically behave like simple offsetting.
4971
4972 // Handle the extvector case we ignored above.
4973 if (isa<ExtVectorElementExpr>(Val: E->getBase())) {
4974 LValue LV = EmitLValue(E: E->getBase());
4975 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
4976 Address Addr = EmitExtVectorElementLValue(LV);
4977
4978 QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
4979 Addr = emitArraySubscriptGEP(CGF&: *this, addr: Addr, indices: Idx, eltType: EltType, /*inbounds*/ true,
4980 signedIndices: SignedIndices, loc: E->getExprLoc());
4981 return MakeAddrLValue(Addr, T: EltType, BaseInfo: LV.getBaseInfo(),
4982 TBAAInfo: CGM.getTBAAInfoForSubobject(Base: LV, AccessType: EltType));
4983 }
4984
4985 LValueBaseInfo EltBaseInfo;
4986 TBAAAccessInfo EltTBAAInfo;
4987 Address Addr = Address::invalid();
4988 if (const VariableArrayType *vla =
4989 getContext().getAsVariableArrayType(T: E->getType())) {
4990 // The base must be a pointer, which is not an aggregate. Emit
4991 // it. It needs to be emitted first in case it's what captures
4992 // the VLA bounds.
4993 Addr = EmitPointerWithAlignment(E: E->getBase(), BaseInfo: &EltBaseInfo, TBAAInfo: &EltTBAAInfo);
4994 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
4995
4996 // The element count here is the total number of non-VLA elements.
4997 llvm::Value *numElements = getVLASize(vla).NumElts;
4998
4999 // Effectively, the multiply by the VLA size is part of the GEP.
5000 // GEP indexes are signed, and scaling an index isn't permitted to
5001 // signed-overflow, so we use the same semantics for our explicit
5002 // multiply. We suppress this if overflow is not undefined behavior.
5003 if (getLangOpts().PointerOverflowDefined) {
5004 Idx = Builder.CreateMul(LHS: Idx, RHS: numElements);
5005 } else {
5006 Idx = Builder.CreateNSWMul(LHS: Idx, RHS: numElements);
5007 }
5008
5009 Addr = emitArraySubscriptGEP(CGF&: *this, addr: Addr, indices: Idx, eltType: vla->getElementType(),
5010 inbounds: !getLangOpts().PointerOverflowDefined,
5011 signedIndices: SignedIndices, loc: E->getExprLoc());
5012
5013 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
5014 // Indexing over an interface, as in "NSString *P; P[4];"
5015
5016 // Emit the base pointer.
5017 Addr = EmitPointerWithAlignment(E: E->getBase(), BaseInfo: &EltBaseInfo, TBAAInfo: &EltTBAAInfo);
5018 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
5019
5020 CharUnits InterfaceSize = getContext().getTypeSizeInChars(T: OIT);
5021 llvm::Value *InterfaceSizeVal =
5022 llvm::ConstantInt::get(Ty: Idx->getType(), V: InterfaceSize.getQuantity());
5023
5024 llvm::Value *ScaledIdx = Builder.CreateMul(LHS: Idx, RHS: InterfaceSizeVal);
5025
5026 // We don't necessarily build correct LLVM struct types for ObjC
5027 // interfaces, so we can't rely on GEP to do this scaling
5028 // correctly, so we need to cast to i8*. FIXME: is this actually
5029 // true? A lot of other things in the fragile ABI would break...
5030 llvm::Type *OrigBaseElemTy = Addr.getElementType();
5031
5032 // Do the GEP.
5033 CharUnits EltAlign =
5034 getArrayElementAlign(arrayAlign: Addr.getAlignment(), idx: Idx, eltSize: InterfaceSize);
5035 llvm::Value *EltPtr =
5036 emitArraySubscriptGEP(CGF&: *this, elemType: Int8Ty, ptr: Addr.emitRawPointer(CGF&: *this),
5037 indices: ScaledIdx, inbounds: false, signedIndices: SignedIndices, loc: E->getExprLoc());
5038 Addr = Address(EltPtr, OrigBaseElemTy, EltAlign);
5039 } else if (const Expr *Array = isSimpleArrayDecayOperand(E: E->getBase())) {
5040 // If this is A[i] where A is an array, the frontend will have decayed the
5041 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
5042 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
5043 // "gep x, i" here. Emit one "gep A, 0, i".
5044 assert(Array->getType()->isArrayType() &&
5045 "Array to pointer decay must have array source type!");
5046 LValue ArrayLV;
5047 // For simple multidimensional array indexing, set the 'accessed' flag for
5048 // better bounds-checking of the base expression.
5049 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Val: Array))
5050 ArrayLV = EmitArraySubscriptExpr(E: ASE, /*Accessed*/ true);
5051 else
5052 ArrayLV = EmitLValue(E: Array);
5053 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
5054
5055 if (SanOpts.has(K: SanitizerKind::ArrayBounds))
5056 EmitCountedByBoundsChecking(ArrayExpr: Array, ArrayType: Array->getType(), ArrayInst: ArrayLV.getAddress(),
5057 IndexType: E->getIdx()->getType(), IndexVal: Idx, Accessed,
5058 /*FlexibleArray=*/true);
5059
5060 // Propagate the alignment from the array itself to the result.
5061 QualType arrayType = Array->getType();
5062 Addr = emitArraySubscriptGEP(
5063 CGF&: *this, addr: ArrayLV.getAddress(), indices: {CGM.getSize(numChars: CharUnits::Zero()), Idx},
5064 eltType: E->getType(), inbounds: !getLangOpts().PointerOverflowDefined, signedIndices: SignedIndices,
5065 loc: E->getExprLoc(), arrayType: &arrayType, Base: E->getBase());
5066 EltBaseInfo = ArrayLV.getBaseInfo();
5067 if (!CGM.getCodeGenOpts().NewStructPathTBAA) {
5068 // Since CodeGenTBAA::getTypeInfoHelper only handles array types for
5069 // new struct path TBAA, we must a use a plain access.
5070 EltTBAAInfo = CGM.getTBAAInfoForSubobject(Base: ArrayLV, AccessType: E->getType());
5071 } else if (ArrayLV.getTBAAInfo().isMayAlias()) {
5072 EltTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
5073 } else if (ArrayLV.getTBAAInfo().isIncomplete()) {
5074 // The array element is complete, even if the array is not.
5075 EltTBAAInfo = CGM.getTBAAAccessInfo(AccessType: E->getType());
5076 } else {
5077 // The TBAA access info from the array (base) lvalue is ordinary. We will
5078 // adapt it to create access info for the element.
5079 EltTBAAInfo = ArrayLV.getTBAAInfo();
5080
5081 // We retain the TBAA struct path (BaseType and Offset members) from the
5082 // array. In the TBAA representation, we map any array access to the
5083 // element at index 0, as the index is generally a runtime value. This
5084 // element has the same offset in the base type as the array itself.
5085 // If the array lvalue had no base type, there is no point trying to
5086 // generate one, since an array itself is not a valid base type.
5087
5088 // We also retain the access type from the base lvalue, but the access
5089 // size must be updated to the size of an individual element.
5090 EltTBAAInfo.Size =
5091 getContext().getTypeSizeInChars(T: E->getType()).getQuantity();
5092 }
5093 } else {
5094 // The base must be a pointer; emit it with an estimate of its alignment.
5095 Address BaseAddr =
5096 EmitPointerWithAlignment(E: E->getBase(), BaseInfo: &EltBaseInfo, TBAAInfo: &EltTBAAInfo);
5097 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
5098 QualType ptrType = E->getBase()->getType();
5099 Addr = emitArraySubscriptGEP(CGF&: *this, addr: BaseAddr, indices: Idx, eltType: E->getType(),
5100 inbounds: !getLangOpts().PointerOverflowDefined,
5101 signedIndices: SignedIndices, loc: E->getExprLoc(), arrayType: &ptrType,
5102 Base: E->getBase());
5103
5104 if (SanOpts.has(K: SanitizerKind::ArrayBounds)) {
5105 StructFieldAccess Visitor;
5106 const Expr *Base = Visitor.Visit(S: E->getBase());
5107
5108 if (const auto *CE = dyn_cast_if_present<CastExpr>(Val: Base);
5109 CE && CE->getCastKind() == CK_LValueToRValue)
5110 EmitCountedByBoundsChecking(ArrayExpr: CE, ArrayType: ptrType, ArrayInst: Address::invalid(),
5111 IndexType: E->getIdx()->getType(), IndexVal: Idx, Accessed,
5112 /*FlexibleArray=*/false);
5113 }
5114 }
5115
5116 LValue LV = MakeAddrLValue(Addr, T: E->getType(), BaseInfo: EltBaseInfo, TBAAInfo: EltTBAAInfo);
5117
5118 if (getLangOpts().ObjC &&
5119 getLangOpts().getGC() != LangOptions::NonGC) {
5120 LV.setNonGC(!E->isOBJCGCCandidate(Ctx&: getContext()));
5121 setObjCGCLValueClass(Ctx: getContext(), E, LV);
5122 }
5123 return LV;
5124}
5125
5126llvm::Value *CodeGenFunction::EmitMatrixIndexExpr(const Expr *E) {
5127 llvm::Value *Idx = EmitScalarExpr(E);
5128 if (Idx->getType() == IntPtrTy)
5129 return Idx;
5130 bool IsSigned = E->getType()->isSignedIntegerOrEnumerationType();
5131 return Builder.CreateIntCast(V: Idx, DestTy: IntPtrTy, isSigned: IsSigned);
5132}
5133
5134LValue CodeGenFunction::EmitMatrixSingleSubscriptExpr(
5135 const MatrixSingleSubscriptExpr *E) {
5136 LValue Base = EmitLValue(E: E->getBase());
5137 llvm::Value *RowIdx = EmitMatrixIndexExpr(E: E->getRowIdx());
5138 return LValue::MakeMatrixRow(
5139 Addr: MaybeConvertMatrixAddress(Addr: Base.getAddress(), CGF&: *this), RowIdx,
5140 MatrixTy: E->getBase()->getType(), BaseInfo: Base.getBaseInfo(), TBAAInfo: TBAAAccessInfo());
5141}
5142
5143LValue CodeGenFunction::EmitMatrixSubscriptExpr(const MatrixSubscriptExpr *E) {
5144 assert(
5145 !E->isIncomplete() &&
5146 "incomplete matrix subscript expressions should be rejected during Sema");
5147 LValue Base = EmitLValue(E: E->getBase());
5148
5149 // Extend or truncate the index type to 32 or 64-bits if needed.
5150 llvm::Value *RowIdx = EmitMatrixIndexExpr(E: E->getRowIdx());
5151 llvm::Value *ColIdx = EmitMatrixIndexExpr(E: E->getColumnIdx());
5152 llvm::MatrixBuilder MB(Builder);
5153 const auto *MatrixTy = E->getBase()->getType()->castAs<ConstantMatrixType>();
5154 unsigned NumCols = MatrixTy->getNumColumns();
5155 unsigned NumRows = MatrixTy->getNumRows();
5156 bool IsMatrixRowMajor = getLangOpts().getDefaultMatrixMemoryLayout() ==
5157 LangOptions::MatrixMemoryLayout::MatrixRowMajor;
5158 llvm::Value *FinalIdx =
5159 MB.CreateIndex(RowIdx, ColumnIdx: ColIdx, NumRows, NumCols, IsMatrixRowMajor);
5160
5161 return LValue::MakeMatrixElt(
5162 matAddress: MaybeConvertMatrixAddress(Addr: Base.getAddress(), CGF&: *this), Idx: FinalIdx,
5163 type: E->getBase()->getType(), BaseInfo: Base.getBaseInfo(), TBAAInfo: TBAAAccessInfo());
5164}
5165
5166static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base,
5167 LValueBaseInfo &BaseInfo,
5168 TBAAAccessInfo &TBAAInfo,
5169 QualType BaseTy, QualType ElTy,
5170 bool IsLowerBound) {
5171 LValue BaseLVal;
5172 if (auto *ASE = dyn_cast<ArraySectionExpr>(Val: Base->IgnoreParenImpCasts())) {
5173 BaseLVal = CGF.EmitArraySectionExpr(E: ASE, IsLowerBound);
5174 if (BaseTy->isArrayType()) {
5175 Address Addr = BaseLVal.getAddress();
5176 BaseInfo = BaseLVal.getBaseInfo();
5177
5178 // If the array type was an incomplete type, we need to make sure
5179 // the decay ends up being the right type.
5180 llvm::Type *NewTy = CGF.ConvertType(T: BaseTy);
5181 Addr = Addr.withElementType(ElemTy: NewTy);
5182
5183 // Note that VLA pointers are always decayed, so we don't need to do
5184 // anything here.
5185 if (!BaseTy->isVariableArrayType()) {
5186 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
5187 "Expected pointer to array");
5188 Addr = CGF.Builder.CreateConstArrayGEP(Addr, Index: 0, Name: "arraydecay");
5189 }
5190
5191 return Addr.withElementType(ElemTy: CGF.ConvertTypeForMem(T: ElTy));
5192 }
5193 LValueBaseInfo TypeBaseInfo;
5194 TBAAAccessInfo TypeTBAAInfo;
5195 CharUnits Align =
5196 CGF.CGM.getNaturalTypeAlignment(T: ElTy, BaseInfo: &TypeBaseInfo, TBAAInfo: &TypeTBAAInfo);
5197 BaseInfo.mergeForCast(Info: TypeBaseInfo);
5198 TBAAInfo = CGF.CGM.mergeTBAAInfoForCast(SourceInfo: TBAAInfo, TargetInfo: TypeTBAAInfo);
5199 return Address(CGF.Builder.CreateLoad(Addr: BaseLVal.getAddress()),
5200 CGF.ConvertTypeForMem(T: ElTy), Align);
5201 }
5202 return CGF.EmitPointerWithAlignment(E: Base, BaseInfo: &BaseInfo, TBAAInfo: &TBAAInfo);
5203}
5204
5205LValue CodeGenFunction::EmitArraySectionExpr(const ArraySectionExpr *E,
5206 bool IsLowerBound) {
5207
5208 assert(!E->isOpenACCArraySection() &&
5209 "OpenACC Array section codegen not implemented");
5210
5211 QualType BaseTy = ArraySectionExpr::getBaseOriginalType(Base: E->getBase());
5212 QualType ResultExprTy;
5213 if (auto *AT = getContext().getAsArrayType(T: BaseTy))
5214 ResultExprTy = AT->getElementType();
5215 else
5216 ResultExprTy = BaseTy->getPointeeType();
5217 llvm::Value *Idx = nullptr;
5218 if (IsLowerBound || E->getColonLocFirst().isInvalid()) {
5219 // Requesting lower bound or upper bound, but without provided length and
5220 // without ':' symbol for the default length -> length = 1.
5221 // Idx = LowerBound ?: 0;
5222 if (auto *LowerBound = E->getLowerBound()) {
5223 Idx = Builder.CreateIntCast(
5224 V: EmitScalarExpr(E: LowerBound), DestTy: IntPtrTy,
5225 isSigned: LowerBound->getType()->hasSignedIntegerRepresentation());
5226 } else
5227 Idx = llvm::ConstantInt::getNullValue(Ty: IntPtrTy);
5228 } else {
5229 // Try to emit length or lower bound as constant. If this is possible, 1
5230 // is subtracted from constant length or lower bound. Otherwise, emit LLVM
5231 // IR (LB + Len) - 1.
5232 auto &C = CGM.getContext();
5233 auto *Length = E->getLength();
5234 llvm::APSInt ConstLength;
5235 if (Length) {
5236 // Idx = LowerBound + Length - 1;
5237 if (std::optional<llvm::APSInt> CL = Length->getIntegerConstantExpr(Ctx: C)) {
5238 ConstLength = CL->zextOrTrunc(width: PointerWidthInBits);
5239 Length = nullptr;
5240 }
5241 auto *LowerBound = E->getLowerBound();
5242 llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
5243 if (LowerBound) {
5244 if (std::optional<llvm::APSInt> LB =
5245 LowerBound->getIntegerConstantExpr(Ctx: C)) {
5246 ConstLowerBound = LB->zextOrTrunc(width: PointerWidthInBits);
5247 LowerBound = nullptr;
5248 }
5249 }
5250 if (!Length)
5251 --ConstLength;
5252 else if (!LowerBound)
5253 --ConstLowerBound;
5254
5255 if (Length || LowerBound) {
5256 auto *LowerBoundVal =
5257 LowerBound
5258 ? Builder.CreateIntCast(
5259 V: EmitScalarExpr(E: LowerBound), DestTy: IntPtrTy,
5260 isSigned: LowerBound->getType()->hasSignedIntegerRepresentation())
5261 : llvm::ConstantInt::get(Ty: IntPtrTy, V: ConstLowerBound);
5262 auto *LengthVal =
5263 Length
5264 ? Builder.CreateIntCast(
5265 V: EmitScalarExpr(E: Length), DestTy: IntPtrTy,
5266 isSigned: Length->getType()->hasSignedIntegerRepresentation())
5267 : llvm::ConstantInt::get(Ty: IntPtrTy, V: ConstLength);
5268 Idx = Builder.CreateAdd(LHS: LowerBoundVal, RHS: LengthVal, Name: "lb_add_len",
5269 /*HasNUW=*/false,
5270 HasNSW: !getLangOpts().PointerOverflowDefined);
5271 if (Length && LowerBound) {
5272 Idx = Builder.CreateSub(
5273 LHS: Idx, RHS: llvm::ConstantInt::get(Ty: IntPtrTy, /*V=*/1), Name: "idx_sub_1",
5274 /*HasNUW=*/false, HasNSW: !getLangOpts().PointerOverflowDefined);
5275 }
5276 } else
5277 Idx = llvm::ConstantInt::get(Ty: IntPtrTy, V: ConstLength + ConstLowerBound);
5278 } else {
5279 // Idx = ArraySize - 1;
5280 QualType ArrayTy = BaseTy->isPointerType()
5281 ? E->getBase()->IgnoreParenImpCasts()->getType()
5282 : BaseTy;
5283 if (auto *VAT = C.getAsVariableArrayType(T: ArrayTy)) {
5284 Length = VAT->getSizeExpr();
5285 if (std::optional<llvm::APSInt> L = Length->getIntegerConstantExpr(Ctx: C)) {
5286 ConstLength = *L;
5287 Length = nullptr;
5288 }
5289 } else {
5290 auto *CAT = C.getAsConstantArrayType(T: ArrayTy);
5291 assert(CAT && "unexpected type for array initializer");
5292 ConstLength = CAT->getSize();
5293 }
5294 if (Length) {
5295 auto *LengthVal = Builder.CreateIntCast(
5296 V: EmitScalarExpr(E: Length), DestTy: IntPtrTy,
5297 isSigned: Length->getType()->hasSignedIntegerRepresentation());
5298 Idx = Builder.CreateSub(
5299 LHS: LengthVal, RHS: llvm::ConstantInt::get(Ty: IntPtrTy, /*V=*/1), Name: "len_sub_1",
5300 /*HasNUW=*/false, HasNSW: !getLangOpts().PointerOverflowDefined);
5301 } else {
5302 ConstLength = ConstLength.zextOrTrunc(width: PointerWidthInBits);
5303 --ConstLength;
5304 Idx = llvm::ConstantInt::get(Ty: IntPtrTy, V: ConstLength);
5305 }
5306 }
5307 }
5308 assert(Idx);
5309
5310 Address EltPtr = Address::invalid();
5311 LValueBaseInfo BaseInfo;
5312 TBAAAccessInfo TBAAInfo;
5313 if (auto *VLA = getContext().getAsVariableArrayType(T: ResultExprTy)) {
5314 // The base must be a pointer, which is not an aggregate. Emit
5315 // it. It needs to be emitted first in case it's what captures
5316 // the VLA bounds.
5317 Address Base =
5318 emitOMPArraySectionBase(CGF&: *this, Base: E->getBase(), BaseInfo, TBAAInfo,
5319 BaseTy, ElTy: VLA->getElementType(), IsLowerBound);
5320 // The element count here is the total number of non-VLA elements.
5321 llvm::Value *NumElements = getVLASize(vla: VLA).NumElts;
5322
5323 // Effectively, the multiply by the VLA size is part of the GEP.
5324 // GEP indexes are signed, and scaling an index isn't permitted to
5325 // signed-overflow, so we use the same semantics for our explicit
5326 // multiply. We suppress this if overflow is not undefined behavior.
5327 if (getLangOpts().PointerOverflowDefined)
5328 Idx = Builder.CreateMul(LHS: Idx, RHS: NumElements);
5329 else
5330 Idx = Builder.CreateNSWMul(LHS: Idx, RHS: NumElements);
5331 EltPtr = emitArraySubscriptGEP(CGF&: *this, addr: Base, indices: Idx, eltType: VLA->getElementType(),
5332 inbounds: !getLangOpts().PointerOverflowDefined,
5333 /*signedIndices=*/false, loc: E->getExprLoc());
5334 } else if (const Expr *Array = isSimpleArrayDecayOperand(E: E->getBase())) {
5335 // If this is A[i] where A is an array, the frontend will have decayed the
5336 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
5337 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
5338 // "gep x, i" here. Emit one "gep A, 0, i".
5339 assert(Array->getType()->isArrayType() &&
5340 "Array to pointer decay must have array source type!");
5341 LValue ArrayLV;
5342 // For simple multidimensional array indexing, set the 'accessed' flag for
5343 // better bounds-checking of the base expression.
5344 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Val: Array))
5345 ArrayLV = EmitArraySubscriptExpr(E: ASE, /*Accessed*/ true);
5346 else
5347 ArrayLV = EmitLValue(E: Array);
5348
5349 // Propagate the alignment from the array itself to the result.
5350 EltPtr = emitArraySubscriptGEP(
5351 CGF&: *this, addr: ArrayLV.getAddress(), indices: {CGM.getSize(numChars: CharUnits::Zero()), Idx},
5352 eltType: ResultExprTy, inbounds: !getLangOpts().PointerOverflowDefined,
5353 /*signedIndices=*/false, loc: E->getExprLoc());
5354 BaseInfo = ArrayLV.getBaseInfo();
5355 TBAAInfo = CGM.getTBAAInfoForSubobject(Base: ArrayLV, AccessType: ResultExprTy);
5356 } else {
5357 Address Base =
5358 emitOMPArraySectionBase(CGF&: *this, Base: E->getBase(), BaseInfo, TBAAInfo, BaseTy,
5359 ElTy: ResultExprTy, IsLowerBound);
5360 EltPtr = emitArraySubscriptGEP(CGF&: *this, addr: Base, indices: Idx, eltType: ResultExprTy,
5361 inbounds: !getLangOpts().PointerOverflowDefined,
5362 /*signedIndices=*/false, loc: E->getExprLoc());
5363 }
5364
5365 return MakeAddrLValue(Addr: EltPtr, T: ResultExprTy, BaseInfo, TBAAInfo);
5366}
5367
5368LValue CodeGenFunction::
5369EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
5370 // Emit the base vector as an l-value.
5371 LValue Base;
5372
5373 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
5374 if (E->isArrow()) {
5375 // If it is a pointer to a vector, emit the address and form an lvalue with
5376 // it.
5377 LValueBaseInfo BaseInfo;
5378 TBAAAccessInfo TBAAInfo;
5379 Address Ptr = EmitPointerWithAlignment(E: E->getBase(), BaseInfo: &BaseInfo, TBAAInfo: &TBAAInfo);
5380 const auto *PT = E->getBase()->getType()->castAs<PointerType>();
5381 Base = MakeAddrLValue(Addr: Ptr, T: PT->getPointeeType(), BaseInfo, TBAAInfo);
5382 Base.getQuals().removeObjCGCAttr();
5383 } else if (E->getBase()->isGLValue()) {
5384 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
5385 // emit the base as an lvalue.
5386 assert(E->getBase()->getType()->isVectorType());
5387 Base = EmitLValue(E: E->getBase());
5388 } else {
5389 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
5390 assert(E->getBase()->getType()->isVectorType() &&
5391 "Result must be a vector");
5392 llvm::Value *Vec = EmitScalarExpr(E: E->getBase());
5393
5394 // Store the vector to memory (because LValue wants an address).
5395 Address VecMem = CreateMemTemp(Ty: E->getBase()->getType());
5396 // need to zero extend an hlsl boolean vector to store it back to memory
5397 QualType Ty = E->getBase()->getType();
5398 llvm::Type *LTy = convertTypeForLoadStore(ASTTy: Ty, LLVMTy: Vec->getType());
5399 if (LTy->getScalarSizeInBits() > Vec->getType()->getScalarSizeInBits())
5400 Vec = Builder.CreateZExt(V: Vec, DestTy: LTy);
5401 Builder.CreateStore(Val: Vec, Addr: VecMem);
5402 Base = MakeAddrLValue(Addr: VecMem, T: Ty, Source: AlignmentSource::Decl);
5403 }
5404
5405 QualType type =
5406 E->getType().withCVRQualifiers(CVR: Base.getQuals().getCVRQualifiers());
5407
5408 // Encode the element access list into a vector of unsigned indices.
5409 SmallVector<uint32_t, 4> Indices;
5410 E->getEncodedElementAccess(Elts&: Indices);
5411
5412 if (Base.isSimple()) {
5413 llvm::Constant *CV =
5414 llvm::ConstantDataVector::get(Context&: getLLVMContext(), Elts: Indices);
5415 return LValue::MakeExtVectorElt(Addr: Base.getAddress(), Elts: CV, type,
5416 BaseInfo: Base.getBaseInfo(), TBAAInfo: TBAAAccessInfo());
5417 }
5418 if (Base.isMatrixRow()) {
5419 if (auto *RowIdx =
5420 llvm::dyn_cast<llvm::ConstantInt>(Val: Base.getMatrixRowIdx())) {
5421 llvm::SmallVector<llvm::Constant *> MatIndices;
5422 QualType MatTy = Base.getType();
5423 const ConstantMatrixType *MT = MatTy->castAs<ConstantMatrixType>();
5424 unsigned NumCols = MT->getNumColumns();
5425 unsigned NumRows = MT->getNumRows();
5426 MatIndices.reserve(N: NumCols);
5427
5428 unsigned Row = RowIdx->getZExtValue();
5429 for (unsigned C = 0; C < NumCols; ++C) {
5430 unsigned Col = Indices[C];
5431 unsigned Linear = Col * NumRows + Row;
5432 MatIndices.push_back(Elt: llvm::ConstantInt::get(Ty: Int32Ty, V: Linear));
5433 }
5434
5435 llvm::Constant *ConstIdxs = llvm::ConstantVector::get(V: MatIndices);
5436 return LValue::MakeExtVectorElt(Addr: Base.getMatrixAddress(), Elts: ConstIdxs,
5437 type: E->getBase()->getType(),
5438 BaseInfo: Base.getBaseInfo(), TBAAInfo: TBAAAccessInfo());
5439 }
5440 llvm::Constant *Cols =
5441 llvm::ConstantDataVector::get(Context&: getLLVMContext(), Elts: Indices);
5442 // Note: intentionally not using E.getType() so we can reuse isMatrixRow()
5443 // implementations in EmitLoadOfLValue & EmitStoreThroughLValue and don't
5444 // need the LValue to have its own number of rows and columns when the
5445 // type is a vector.
5446 return LValue::MakeMatrixRowSwizzle(
5447 MatAddr: Base.getMatrixAddress(), RowIdx: Base.getMatrixRowIdx(), Cols, MatrixTy: Base.getType(),
5448 BaseInfo: Base.getBaseInfo(), TBAAInfo: TBAAAccessInfo());
5449 }
5450
5451 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
5452
5453 llvm::Constant *BaseElts = Base.getExtVectorElts();
5454 SmallVector<llvm::Constant *, 4> CElts;
5455
5456 for (unsigned Index : Indices)
5457 CElts.push_back(Elt: BaseElts->getAggregateElement(Elt: Index));
5458 llvm::Constant *CV = llvm::ConstantVector::get(V: CElts);
5459 return LValue::MakeExtVectorElt(Addr: Base.getExtVectorAddress(), Elts: CV, type,
5460 BaseInfo: Base.getBaseInfo(), TBAAInfo: TBAAAccessInfo());
5461}
5462
5463bool CodeGenFunction::isUnderlyingBasePointerConstantNull(const Expr *E) {
5464 const Expr *UnderlyingBaseExpr = E->IgnoreParens();
5465 while (auto *BaseMemberExpr = dyn_cast<MemberExpr>(Val: UnderlyingBaseExpr))
5466 UnderlyingBaseExpr = BaseMemberExpr->getBase()->IgnoreParens();
5467 return getContext().isSentinelNullExpr(E: UnderlyingBaseExpr);
5468}
5469
5470LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
5471 if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(CGF&: *this, ME: E)) {
5472 EmitIgnoredExpr(E: E->getBase());
5473 return EmitDeclRefLValue(E: DRE);
5474 }
5475 if (getLangOpts().HLSL &&
5476 E->getType().getAddressSpace() == LangAS::hlsl_constant) {
5477 // We have an HLSL buffer - emit using HLSL's layout rules.
5478 return CGM.getHLSLRuntime().emitBufferMemberExpr(CGF&: *this, E);
5479 }
5480
5481 Expr *BaseExpr = E->getBase();
5482 // Check whether the underlying base pointer is a constant null.
5483 // If so, we do not set inbounds flag for GEP to avoid breaking some
5484 // old-style offsetof idioms.
5485 bool IsInBounds = !getLangOpts().PointerOverflowDefined &&
5486 !isUnderlyingBasePointerConstantNull(E: BaseExpr);
5487 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
5488 LValue BaseLV;
5489 if (E->isArrow()) {
5490 LValueBaseInfo BaseInfo;
5491 TBAAAccessInfo TBAAInfo;
5492 Address Addr = EmitPointerWithAlignment(E: BaseExpr, BaseInfo: &BaseInfo, TBAAInfo: &TBAAInfo);
5493 QualType PtrTy = BaseExpr->getType()->getPointeeType();
5494 SanitizerSet SkippedChecks;
5495 bool IsBaseCXXThis = IsWrappedCXXThis(Obj: BaseExpr);
5496 if (IsBaseCXXThis)
5497 SkippedChecks.set(K: SanitizerKind::Alignment, Value: true);
5498 if (IsBaseCXXThis || isa<DeclRefExpr>(Val: BaseExpr))
5499 SkippedChecks.set(K: SanitizerKind::Null, Value: true);
5500 EmitTypeCheck(TCK: TCK_MemberAccess, Loc: E->getExprLoc(), Addr, Type: PtrTy,
5501 /*Alignment=*/CharUnits::Zero(), SkippedChecks);
5502 BaseLV = MakeAddrLValue(Addr, T: PtrTy, BaseInfo, TBAAInfo);
5503 } else
5504 BaseLV = EmitCheckedLValue(E: BaseExpr, TCK: TCK_MemberAccess);
5505
5506 NamedDecl *ND = E->getMemberDecl();
5507 if (auto *Field = dyn_cast<FieldDecl>(Val: ND)) {
5508 LValue LV = EmitLValueForField(Base: BaseLV, Field, IsInBounds);
5509 setObjCGCLValueClass(Ctx: getContext(), E, LV);
5510 if (getLangOpts().OpenMP) {
5511 // If the member was explicitly marked as nontemporal, mark it as
5512 // nontemporal. If the base lvalue is marked as nontemporal, mark access
5513 // to children as nontemporal too.
5514 if ((IsWrappedCXXThis(Obj: BaseExpr) &&
5515 CGM.getOpenMPRuntime().isNontemporalDecl(VD: Field)) ||
5516 BaseLV.isNontemporal())
5517 LV.setNontemporal(/*Value=*/true);
5518 }
5519 return LV;
5520 }
5521
5522 if (const auto *FD = dyn_cast<FunctionDecl>(Val: ND))
5523 return EmitFunctionDeclLValue(CGF&: *this, E, GD: FD);
5524
5525 llvm_unreachable("Unhandled member declaration!");
5526}
5527
5528/// Given that we are currently emitting a lambda, emit an l-value for
5529/// one of its members.
5530///
5531LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field,
5532 llvm::Value *ThisValue) {
5533 bool HasExplicitObjectParameter = false;
5534 const auto *MD = dyn_cast_if_present<CXXMethodDecl>(Val: CurCodeDecl);
5535 if (MD) {
5536 HasExplicitObjectParameter = MD->isExplicitObjectMemberFunction();
5537 assert(MD->getParent()->isLambda());
5538 assert(MD->getParent() == Field->getParent());
5539 }
5540 LValue LambdaLV;
5541 if (HasExplicitObjectParameter) {
5542 const VarDecl *D = cast<CXXMethodDecl>(Val: CurCodeDecl)->getParamDecl(i: 0);
5543 auto It = LocalDeclMap.find(Val: D);
5544 assert(It != LocalDeclMap.end() && "explicit parameter not loaded?");
5545 Address AddrOfExplicitObject = It->getSecond();
5546 if (D->getType()->isReferenceType())
5547 LambdaLV = EmitLoadOfReferenceLValue(RefAddr: AddrOfExplicitObject, RefTy: D->getType(),
5548 Source: AlignmentSource::Decl);
5549 else
5550 LambdaLV = MakeAddrLValue(Addr: AddrOfExplicitObject,
5551 T: D->getType().getNonReferenceType());
5552
5553 // Make sure we have an lvalue to the lambda itself and not a derived class.
5554 auto *ThisTy = D->getType().getNonReferenceType()->getAsCXXRecordDecl();
5555 auto *LambdaTy = cast<CXXRecordDecl>(Val: Field->getParent());
5556 if (ThisTy != LambdaTy) {
5557 const CXXCastPath &BasePathArray = getContext().LambdaCastPaths.at(Val: MD);
5558 Address Base = GetAddressOfBaseClass(
5559 Value: LambdaLV.getAddress(), Derived: ThisTy, PathBegin: BasePathArray.begin(),
5560 PathEnd: BasePathArray.end(), /*NullCheckValue=*/false, Loc: SourceLocation());
5561 CanQualType T = getContext().getCanonicalTagType(TD: LambdaTy);
5562 LambdaLV = MakeAddrLValue(Addr: Base, T);
5563 }
5564 } else {
5565 CanQualType LambdaTagType =
5566 getContext().getCanonicalTagType(TD: Field->getParent());
5567 LambdaLV = MakeNaturalAlignAddrLValue(V: ThisValue, T: LambdaTagType);
5568 }
5569 return EmitLValueForField(Base: LambdaLV, Field);
5570}
5571
5572LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
5573 return EmitLValueForLambdaField(Field, ThisValue: CXXABIThisValue);
5574}
5575
5576/// Get the field index in the debug info. The debug info structure/union
5577/// will ignore the unnamed bitfields.
5578unsigned CodeGenFunction::getDebugInfoFIndex(const RecordDecl *Rec,
5579 unsigned FieldIndex) {
5580 unsigned I = 0, Skipped = 0;
5581
5582 for (auto *F : Rec->getDefinition()->fields()) {
5583 if (I == FieldIndex)
5584 break;
5585 if (F->isUnnamedBitField())
5586 Skipped++;
5587 I++;
5588 }
5589
5590 return FieldIndex - Skipped;
5591}
5592
5593/// Get the address of a zero-sized field within a record. The resulting
5594/// address doesn't necessarily have the right type.
5595static Address emitAddrOfZeroSizeField(CodeGenFunction &CGF, Address Base,
5596 const FieldDecl *Field,
5597 bool IsInBounds) {
5598 CharUnits Offset = CGF.getContext().toCharUnitsFromBits(
5599 BitSize: CGF.getContext().getFieldOffset(FD: Field));
5600 if (Offset.isZero())
5601 return Base;
5602 Base = Base.withElementType(ElemTy: CGF.Int8Ty);
5603 if (!IsInBounds)
5604 return CGF.Builder.CreateConstByteGEP(Addr: Base, Offset);
5605 return CGF.Builder.CreateConstInBoundsByteGEP(Addr: Base, Offset);
5606}
5607
5608/// Drill down to the storage of a field without walking into reference types,
5609/// and without respect for pointer field protection.
5610///
5611/// The resulting address doesn't necessarily have the right type.
5612static Address emitRawAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
5613 const FieldDecl *field,
5614 bool IsInBounds) {
5615 if (isEmptyFieldForLayout(Context: CGF.getContext(), FD: field))
5616 return emitAddrOfZeroSizeField(CGF, Base: base, Field: field, IsInBounds);
5617
5618 const RecordDecl *rec = field->getParent();
5619
5620 unsigned idx =
5621 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(FD: field);
5622 llvm::Type *StructType =
5623 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMType();
5624
5625 if (CGF.getLangOpts().EmitStructuredGEP)
5626 return RawAddress(
5627 CGF.Builder.CreateStructuredGEP(BaseType: StructType, PtrBase: base.emitRawPointer(CGF),
5628 Indices: {CGF.Builder.getSize(N: idx)}),
5629 base.getElementType(), base.getAlignment());
5630
5631 if (!IsInBounds)
5632 return CGF.Builder.CreateConstGEP2_32(Addr: base, Idx0: 0, Idx1: idx, Name: field->getName());
5633
5634 return CGF.Builder.CreateStructGEP(Addr: base, Index: idx, Name: field->getName());
5635}
5636
5637/// Drill down to the storage of a field without walking into reference types,
5638/// wrapping the address in an llvm.protected.field.ptr intrinsic for the
5639/// pointer field protection feature if necessary.
5640///
5641/// The resulting address doesn't necessarily have the right type.
5642static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
5643 const FieldDecl *field, bool IsInBounds) {
5644 Address Addr = emitRawAddrOfFieldStorage(CGF, base, field, IsInBounds);
5645
5646 if (!CGF.getContext().isPFPField(Field: field))
5647 return Addr;
5648
5649 return CGF.EmitAddressOfPFPField(RecordPtr: base, FieldPtr: Addr, Field: field);
5650}
5651
5652static Address emitPreserveStructAccess(CodeGenFunction &CGF, LValue base,
5653 Address addr, const FieldDecl *field) {
5654 const RecordDecl *rec = field->getParent();
5655 llvm::DIType *DbgInfo = CGF.getDebugInfo()->getOrCreateStandaloneType(
5656 Ty: base.getType(), Loc: rec->getLocation());
5657
5658 unsigned idx =
5659 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(FD: field);
5660
5661 return CGF.Builder.CreatePreserveStructAccessIndex(
5662 Addr: addr, Index: idx, FieldIndex: CGF.getDebugInfoFIndex(Rec: rec, FieldIndex: field->getFieldIndex()), DbgInfo);
5663}
5664
5665static bool hasAnyVptr(const QualType Type, const ASTContext &Context) {
5666 const auto *RD = Type.getTypePtr()->getAsCXXRecordDecl();
5667 if (!RD)
5668 return false;
5669
5670 if (RD->isDynamicClass())
5671 return true;
5672
5673 for (const auto &Base : RD->bases())
5674 if (hasAnyVptr(Type: Base.getType(), Context))
5675 return true;
5676
5677 for (const FieldDecl *Field : RD->fields())
5678 if (hasAnyVptr(Type: Field->getType(), Context))
5679 return true;
5680
5681 return false;
5682}
5683
5684LValue CodeGenFunction::EmitLValueForField(LValue base, const FieldDecl *field,
5685 bool IsInBounds) {
5686 LValueBaseInfo BaseInfo = base.getBaseInfo();
5687
5688 if (field->isBitField()) {
5689 const CGRecordLayout &RL =
5690 CGM.getTypes().getCGRecordLayout(field->getParent());
5691 const CGBitFieldInfo &Info = RL.getBitFieldInfo(FD: field);
5692 const bool UseVolatile = isAAPCS(TargetInfo: CGM.getTarget()) &&
5693 CGM.getCodeGenOpts().AAPCSBitfieldWidth &&
5694 Info.VolatileStorageSize != 0 &&
5695 field->getType()
5696 .withCVRQualifiers(CVR: base.getVRQualifiers())
5697 .isVolatileQualified();
5698 Address Addr = base.getAddress();
5699 unsigned Idx = RL.getLLVMFieldNo(FD: field);
5700 const RecordDecl *rec = field->getParent();
5701 if (hasBPFPreserveStaticOffset(D: rec))
5702 Addr = wrapWithBPFPreserveStaticOffset(CGF&: *this, Addr);
5703 if (!UseVolatile) {
5704 if (!IsInPreservedAIRegion &&
5705 (!getDebugInfo() || !rec->hasAttr<BPFPreserveAccessIndexAttr>())) {
5706 if (Idx != 0) {
5707 // For structs, we GEP to the field that the record layout suggests.
5708 if (!IsInBounds)
5709 Addr = Builder.CreateConstGEP2_32(Addr, Idx0: 0, Idx1: Idx, Name: field->getName());
5710 else
5711 Addr = Builder.CreateStructGEP(Addr, Index: Idx, Name: field->getName());
5712 }
5713 } else {
5714 llvm::DIType *DbgInfo = getDebugInfo()->getOrCreateRecordType(
5715 Ty: getContext().getCanonicalTagType(TD: rec), L: rec->getLocation());
5716 Addr = Builder.CreatePreserveStructAccessIndex(
5717 Addr, Index: Idx, FieldIndex: getDebugInfoFIndex(Rec: rec, FieldIndex: field->getFieldIndex()),
5718 DbgInfo);
5719 }
5720 }
5721 const unsigned SS =
5722 UseVolatile ? Info.VolatileStorageSize : Info.StorageSize;
5723 // Get the access type.
5724 llvm::Type *FieldIntTy = llvm::Type::getIntNTy(C&: getLLVMContext(), N: SS);
5725 Addr = Addr.withElementType(ElemTy: FieldIntTy);
5726 if (UseVolatile) {
5727 const unsigned VolatileOffset = Info.VolatileStorageOffset.getQuantity();
5728 if (VolatileOffset)
5729 Addr = Builder.CreateConstInBoundsGEP(Addr, Index: VolatileOffset);
5730 }
5731
5732 QualType fieldType =
5733 field->getType().withCVRQualifiers(CVR: base.getVRQualifiers());
5734 // TODO: Support TBAA for bit fields.
5735 LValueBaseInfo FieldBaseInfo(BaseInfo.getAlignmentSource());
5736 return LValue::MakeBitfield(Addr, Info, type: fieldType, BaseInfo: FieldBaseInfo,
5737 TBAAInfo: TBAAAccessInfo());
5738 }
5739
5740 // Fields of may-alias structures are may-alias themselves.
5741 // FIXME: this should get propagated down through anonymous structs
5742 // and unions.
5743 QualType FieldType = field->getType();
5744 const RecordDecl *rec = field->getParent();
5745 AlignmentSource BaseAlignSource = BaseInfo.getAlignmentSource();
5746 LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(Source: BaseAlignSource));
5747 TBAAAccessInfo FieldTBAAInfo;
5748 if (base.getTBAAInfo().isMayAlias() ||
5749 rec->hasAttr<MayAliasAttr>() || FieldType->isVectorType()) {
5750 FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
5751 } else if (rec->isUnion()) {
5752 // TODO: Support TBAA for unions.
5753 FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
5754 } else {
5755 // If no base type been assigned for the base access, then try to generate
5756 // one for this base lvalue.
5757 FieldTBAAInfo = base.getTBAAInfo();
5758 if (!FieldTBAAInfo.BaseType) {
5759 FieldTBAAInfo.BaseType = CGM.getTBAABaseTypeInfo(QTy: base.getType());
5760 assert(!FieldTBAAInfo.Offset &&
5761 "Nonzero offset for an access with no base type!");
5762 }
5763
5764 // Adjust offset to be relative to the base type.
5765 const ASTRecordLayout &Layout =
5766 getContext().getASTRecordLayout(D: field->getParent());
5767 unsigned CharWidth = getContext().getCharWidth();
5768 if (FieldTBAAInfo.BaseType)
5769 FieldTBAAInfo.Offset +=
5770 Layout.getFieldOffset(FieldNo: field->getFieldIndex()) / CharWidth;
5771
5772 // Update the final access type and size.
5773 FieldTBAAInfo.AccessType = CGM.getTBAATypeInfo(QTy: FieldType);
5774 FieldTBAAInfo.Size =
5775 getContext().getTypeSizeInChars(T: FieldType).getQuantity();
5776 }
5777
5778 Address addr = base.getAddress();
5779 if (hasBPFPreserveStaticOffset(D: rec))
5780 addr = wrapWithBPFPreserveStaticOffset(CGF&: *this, Addr&: addr);
5781 if (auto *ClassDef = dyn_cast<CXXRecordDecl>(Val: rec)) {
5782 if (CGM.getCodeGenOpts().StrictVTablePointers &&
5783 ClassDef->isDynamicClass()) {
5784 // Getting to any field of dynamic object requires stripping dynamic
5785 // information provided by invariant.group. This is because accessing
5786 // fields may leak the real address of dynamic object, which could result
5787 // in miscompilation when leaked pointer would be compared.
5788 auto *stripped =
5789 Builder.CreateStripInvariantGroup(Ptr: addr.emitRawPointer(CGF&: *this));
5790 addr = Address(stripped, addr.getElementType(), addr.getAlignment());
5791 }
5792 }
5793
5794 unsigned RecordCVR = base.getVRQualifiers();
5795 if (rec->isUnion()) {
5796 // For unions, there is no pointer adjustment.
5797 if (CGM.getCodeGenOpts().StrictVTablePointers &&
5798 hasAnyVptr(Type: FieldType, Context: getContext()))
5799 // Because unions can easily skip invariant.barriers, we need to add
5800 // a barrier every time CXXRecord field with vptr is referenced.
5801 addr = Builder.CreateLaunderInvariantGroup(Addr: addr);
5802
5803 if (IsInPreservedAIRegion ||
5804 (getDebugInfo() && rec->hasAttr<BPFPreserveAccessIndexAttr>())) {
5805 // Remember the original union field index
5806 llvm::DIType *DbgInfo = getDebugInfo()->getOrCreateStandaloneType(Ty: base.getType(),
5807 Loc: rec->getLocation());
5808 addr =
5809 Address(Builder.CreatePreserveUnionAccessIndex(
5810 Base: addr.emitRawPointer(CGF&: *this),
5811 FieldIndex: getDebugInfoFIndex(Rec: rec, FieldIndex: field->getFieldIndex()), DbgInfo),
5812 addr.getElementType(), addr.getAlignment());
5813 }
5814
5815 if (FieldType->isReferenceType())
5816 addr = addr.withElementType(ElemTy: CGM.getTypes().ConvertTypeForMem(T: FieldType));
5817 } else {
5818 if (!IsInPreservedAIRegion &&
5819 (!getDebugInfo() || !rec->hasAttr<BPFPreserveAccessIndexAttr>()))
5820 // For structs, we GEP to the field that the record layout suggests.
5821 addr = emitAddrOfFieldStorage(CGF&: *this, base: addr, field, IsInBounds);
5822 else
5823 // Remember the original struct field index
5824 addr = emitPreserveStructAccess(CGF&: *this, base, addr, field);
5825 }
5826
5827 // If this is a reference field, load the reference right now.
5828 if (FieldType->isReferenceType()) {
5829 LValue RefLVal =
5830 MakeAddrLValue(Addr: addr, T: FieldType, BaseInfo: FieldBaseInfo, TBAAInfo: FieldTBAAInfo);
5831 if (RecordCVR & Qualifiers::Volatile)
5832 RefLVal.getQuals().addVolatile();
5833 addr = EmitLoadOfReference(RefLVal, PointeeBaseInfo: &FieldBaseInfo, PointeeTBAAInfo: &FieldTBAAInfo);
5834
5835 // Qualifiers on the struct don't apply to the referencee.
5836 RecordCVR = 0;
5837 FieldType = FieldType->getPointeeType();
5838 }
5839
5840 // Make sure that the address is pointing to the right type. This is critical
5841 // for both unions and structs.
5842 addr = addr.withElementType(ElemTy: CGM.getTypes().ConvertTypeForMem(T: FieldType));
5843
5844 if (field->hasAttr<AnnotateAttr>())
5845 addr = EmitFieldAnnotations(D: field, V: addr);
5846
5847 LValue LV = MakeAddrLValue(Addr: addr, T: FieldType, BaseInfo: FieldBaseInfo, TBAAInfo: FieldTBAAInfo);
5848 LV.getQuals().addCVRQualifiers(mask: RecordCVR);
5849
5850 // __weak attribute on a field is ignored.
5851 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
5852 LV.getQuals().removeObjCGCAttr();
5853
5854 return LV;
5855}
5856
5857LValue
5858CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
5859 const FieldDecl *Field) {
5860 QualType FieldType = Field->getType();
5861
5862 if (!FieldType->isReferenceType())
5863 return EmitLValueForField(base: Base, field: Field);
5864
5865 Address V = emitAddrOfFieldStorage(
5866 CGF&: *this, base: Base.getAddress(), field: Field,
5867 /*IsInBounds=*/!getLangOpts().PointerOverflowDefined);
5868
5869 // Make sure that the address is pointing to the right type.
5870 llvm::Type *llvmType = ConvertTypeForMem(T: FieldType);
5871 V = V.withElementType(ElemTy: llvmType);
5872
5873 // TODO: Generate TBAA information that describes this access as a structure
5874 // member access and not just an access to an object of the field's type. This
5875 // should be similar to what we do in EmitLValueForField().
5876 LValueBaseInfo BaseInfo = Base.getBaseInfo();
5877 AlignmentSource FieldAlignSource = BaseInfo.getAlignmentSource();
5878 LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(Source: FieldAlignSource));
5879 return MakeAddrLValue(Addr: V, T: FieldType, BaseInfo: FieldBaseInfo,
5880 TBAAInfo: CGM.getTBAAInfoForSubobject(Base, AccessType: FieldType));
5881}
5882
5883LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
5884 if (E->isFileScope()) {
5885 ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
5886 return MakeAddrLValue(Addr: GlobalPtr, T: E->getType(), Source: AlignmentSource::Decl);
5887 }
5888 if (E->getType()->isVariablyModifiedType())
5889 // make sure to emit the VLA size.
5890 EmitVariablyModifiedType(Ty: E->getType());
5891
5892 Address DeclPtr = CreateMemTemp(Ty: E->getType(), Name: ".compoundliteral");
5893 const Expr *InitExpr = E->getInitializer();
5894 LValue Result = MakeAddrLValue(Addr: DeclPtr, T: E->getType(), Source: AlignmentSource::Decl);
5895
5896 EmitAnyExprToMem(E: InitExpr, Location: DeclPtr, Quals: E->getType().getQualifiers(),
5897 /*Init*/ IsInit: true);
5898
5899 // Block-scope compound literals are destroyed at the end of the enclosing
5900 // scope in C.
5901 if (!getLangOpts().CPlusPlus)
5902 if (QualType::DestructionKind DtorKind = E->getType().isDestructedType())
5903 pushLifetimeExtendedDestroy(kind: getCleanupKind(kind: DtorKind), addr: DeclPtr,
5904 type: E->getType(), destroyer: getDestroyer(destructionKind: DtorKind),
5905 useEHCleanupForArray: DtorKind & EHCleanup);
5906
5907 return Result;
5908}
5909
5910LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
5911 if (!E->isGLValue())
5912 // Initializing an aggregate temporary in C++11: T{...}.
5913 return EmitAggExprToLValue(E);
5914
5915 // An lvalue initializer list must be initializing a reference.
5916 assert(E->isTransparent() && "non-transparent glvalue init list");
5917 return EmitLValue(E: E->getInit(Init: 0));
5918}
5919
5920/// Emit the operand of a glvalue conditional operator. This is either a glvalue
5921/// or a (possibly-parenthesized) throw-expression. If this is a throw, no
5922/// LValue is returned and the current block has been terminated.
5923static std::optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
5924 const Expr *Operand) {
5925 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Val: Operand->IgnoreParens())) {
5926 CGF.EmitCXXThrowExpr(E: ThrowExpr, /*KeepInsertionPoint*/false);
5927 return std::nullopt;
5928 }
5929
5930 return CGF.EmitLValue(E: Operand);
5931}
5932
5933namespace {
5934// Handle the case where the condition is a constant evaluatable simple integer,
5935// which means we don't have to separately handle the true/false blocks.
5936std::optional<LValue> HandleConditionalOperatorLValueSimpleCase(
5937 CodeGenFunction &CGF, const AbstractConditionalOperator *E) {
5938 const Expr *condExpr = E->getCond();
5939 bool CondExprBool;
5940 if (CGF.ConstantFoldsToSimpleInteger(Cond: condExpr, Result&: CondExprBool)) {
5941 const Expr *Live = E->getTrueExpr(), *Dead = E->getFalseExpr();
5942 if (!CondExprBool)
5943 std::swap(a&: Live, b&: Dead);
5944
5945 if (!CGF.ContainsLabel(S: Dead)) {
5946 // If the true case is live, we need to track its region.
5947 CGF.incrementProfileCounter(ExecSkip: CondExprBool ? CGF.UseExecPath
5948 : CGF.UseSkipPath,
5949 S: E, /*UseBoth=*/true);
5950 CGF.markStmtMaybeUsed(S: Dead);
5951 // If a throw expression we emit it and return an undefined lvalue
5952 // because it can't be used.
5953 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Val: Live->IgnoreParens())) {
5954 CGF.EmitCXXThrowExpr(E: ThrowExpr);
5955 llvm::Type *ElemTy = CGF.ConvertType(T: Dead->getType());
5956 llvm::Type *Ty = CGF.DefaultPtrTy;
5957 return CGF.MakeAddrLValue(
5958 Addr: Address(llvm::UndefValue::get(T: Ty), ElemTy, CharUnits::One()),
5959 T: Dead->getType());
5960 }
5961 return CGF.EmitLValue(E: Live);
5962 }
5963 }
5964 return std::nullopt;
5965}
5966struct ConditionalInfo {
5967 llvm::BasicBlock *lhsBlock, *rhsBlock;
5968 std::optional<LValue> LHS, RHS;
5969};
5970
5971// Create and generate the 3 blocks for a conditional operator.
5972// Leaves the 'current block' in the continuation basic block.
5973template<typename FuncTy>
5974ConditionalInfo EmitConditionalBlocks(CodeGenFunction &CGF,
5975 const AbstractConditionalOperator *E,
5976 const FuncTy &BranchGenFunc) {
5977 ConditionalInfo Info{.lhsBlock: CGF.createBasicBlock(name: "cond.true"),
5978 .rhsBlock: CGF.createBasicBlock(name: "cond.false"), .LHS: std::nullopt,
5979 .RHS: std::nullopt};
5980 llvm::BasicBlock *endBlock = CGF.createBasicBlock(name: "cond.end");
5981
5982 CodeGenFunction::ConditionalEvaluation eval(CGF);
5983 CGF.EmitBranchOnBoolExpr(Cond: E->getCond(), TrueBlock: Info.lhsBlock, FalseBlock: Info.rhsBlock,
5984 TrueCount: CGF.getProfileCount(S: E));
5985
5986 // Any temporaries created here are conditional.
5987 CGF.EmitBlock(BB: Info.lhsBlock);
5988 CGF.incrementProfileCounter(ExecSkip: CGF.UseExecPath, S: E);
5989 eval.begin(CGF);
5990 Info.LHS = BranchGenFunc(CGF, E->getTrueExpr());
5991 eval.end(CGF);
5992 Info.lhsBlock = CGF.Builder.GetInsertBlock();
5993
5994 if (Info.LHS)
5995 CGF.Builder.CreateBr(Dest: endBlock);
5996
5997 // Any temporaries created here are conditional.
5998 CGF.EmitBlock(BB: Info.rhsBlock);
5999 CGF.incrementProfileCounter(ExecSkip: CGF.UseSkipPath, S: E);
6000 eval.begin(CGF);
6001 Info.RHS = BranchGenFunc(CGF, E->getFalseExpr());
6002 eval.end(CGF);
6003 Info.rhsBlock = CGF.Builder.GetInsertBlock();
6004 CGF.EmitBlock(BB: endBlock);
6005
6006 return Info;
6007}
6008} // namespace
6009
6010void CodeGenFunction::EmitIgnoredConditionalOperator(
6011 const AbstractConditionalOperator *E) {
6012 if (!E->isGLValue()) {
6013 // ?: here should be an aggregate.
6014 assert(hasAggregateEvaluationKind(E->getType()) &&
6015 "Unexpected conditional operator!");
6016 return (void)EmitAggExprToLValue(E);
6017 }
6018
6019 OpaqueValueMapping binding(*this, E);
6020 if (HandleConditionalOperatorLValueSimpleCase(CGF&: *this, E))
6021 return;
6022
6023 EmitConditionalBlocks(CGF&: *this, E, BranchGenFunc: [](CodeGenFunction &CGF, const Expr *E) {
6024 CGF.EmitIgnoredExpr(E);
6025 return LValue{};
6026 });
6027}
6028LValue CodeGenFunction::EmitConditionalOperatorLValue(
6029 const AbstractConditionalOperator *expr) {
6030 if (!expr->isGLValue()) {
6031 // ?: here should be an aggregate.
6032 assert(hasAggregateEvaluationKind(expr->getType()) &&
6033 "Unexpected conditional operator!");
6034 return EmitAggExprToLValue(E: expr);
6035 }
6036
6037 OpaqueValueMapping binding(*this, expr);
6038 if (std::optional<LValue> Res =
6039 HandleConditionalOperatorLValueSimpleCase(CGF&: *this, E: expr))
6040 return *Res;
6041
6042 ConditionalInfo Info = EmitConditionalBlocks(
6043 CGF&: *this, E: expr, BranchGenFunc: [](CodeGenFunction &CGF, const Expr *E) {
6044 return EmitLValueOrThrowExpression(CGF, Operand: E);
6045 });
6046
6047 if ((Info.LHS && !Info.LHS->isSimple()) ||
6048 (Info.RHS && !Info.RHS->isSimple()))
6049 return EmitUnsupportedLValue(E: expr, Name: "conditional operator");
6050
6051 if (Info.LHS && Info.RHS) {
6052 Address lhsAddr = Info.LHS->getAddress();
6053 Address rhsAddr = Info.RHS->getAddress();
6054 Address result = mergeAddressesInConditionalExpr(
6055 LHS: lhsAddr, RHS: rhsAddr, LHSBlock: Info.lhsBlock, RHSBlock: Info.rhsBlock,
6056 MergeBlock: Builder.GetInsertBlock(), MergedType: expr->getType());
6057 AlignmentSource alignSource =
6058 std::max(a: Info.LHS->getBaseInfo().getAlignmentSource(),
6059 b: Info.RHS->getBaseInfo().getAlignmentSource());
6060 TBAAAccessInfo TBAAInfo = CGM.mergeTBAAInfoForConditionalOperator(
6061 InfoA: Info.LHS->getTBAAInfo(), InfoB: Info.RHS->getTBAAInfo());
6062 return MakeAddrLValue(Addr: result, T: expr->getType(), BaseInfo: LValueBaseInfo(alignSource),
6063 TBAAInfo);
6064 } else {
6065 assert((Info.LHS || Info.RHS) &&
6066 "both operands of glvalue conditional are throw-expressions?");
6067 return Info.LHS ? *Info.LHS : *Info.RHS;
6068 }
6069}
6070
6071/// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
6072/// type. If the cast is to a reference, we can have the usual lvalue result,
6073/// otherwise if a cast is needed by the code generator in an lvalue context,
6074/// then it must mean that we need the address of an aggregate in order to
6075/// access one of its members. This can happen for all the reasons that casts
6076/// are permitted with aggregate result, including noop aggregate casts, and
6077/// cast from scalar to union.
6078LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
6079 llvm::scope_exit RestoreCurCast([this, Prev = CurCast] { CurCast = Prev; });
6080 CurCast = E;
6081 switch (E->getCastKind()) {
6082 case CK_ToVoid:
6083 case CK_BitCast:
6084 case CK_LValueToRValueBitCast:
6085 case CK_ArrayToPointerDecay:
6086 case CK_FunctionToPointerDecay:
6087 case CK_NullToMemberPointer:
6088 case CK_NullToPointer:
6089 case CK_IntegralToPointer:
6090 case CK_PointerToIntegral:
6091 case CK_PointerToBoolean:
6092 case CK_IntegralCast:
6093 case CK_BooleanToSignedIntegral:
6094 case CK_IntegralToBoolean:
6095 case CK_IntegralToFloating:
6096 case CK_FloatingToIntegral:
6097 case CK_FloatingToBoolean:
6098 case CK_FloatingCast:
6099 case CK_FloatingRealToComplex:
6100 case CK_FloatingComplexToReal:
6101 case CK_FloatingComplexToBoolean:
6102 case CK_FloatingComplexCast:
6103 case CK_FloatingComplexToIntegralComplex:
6104 case CK_IntegralRealToComplex:
6105 case CK_IntegralComplexToReal:
6106 case CK_IntegralComplexToBoolean:
6107 case CK_IntegralComplexCast:
6108 case CK_IntegralComplexToFloatingComplex:
6109 case CK_DerivedToBaseMemberPointer:
6110 case CK_BaseToDerivedMemberPointer:
6111 case CK_MemberPointerToBoolean:
6112 case CK_ReinterpretMemberPointer:
6113 case CK_AnyPointerToBlockPointerCast:
6114 case CK_ARCProduceObject:
6115 case CK_ARCConsumeObject:
6116 case CK_ARCReclaimReturnedObject:
6117 case CK_ARCExtendBlockObject:
6118 case CK_CopyAndAutoreleaseBlockObject:
6119 case CK_IntToOCLSampler:
6120 case CK_FloatingToFixedPoint:
6121 case CK_FixedPointToFloating:
6122 case CK_FixedPointCast:
6123 case CK_FixedPointToBoolean:
6124 case CK_FixedPointToIntegral:
6125 case CK_IntegralToFixedPoint:
6126 case CK_MatrixCast:
6127 case CK_HLSLVectorTruncation:
6128 case CK_HLSLMatrixTruncation:
6129 case CK_HLSLArrayRValue:
6130 case CK_HLSLElementwiseCast:
6131 case CK_HLSLAggregateSplatCast:
6132 return EmitUnsupportedLValue(E, Name: "unexpected cast lvalue");
6133
6134 case CK_Dependent:
6135 llvm_unreachable("dependent cast kind in IR gen!");
6136
6137 case CK_BuiltinFnToFnPtr:
6138 llvm_unreachable("builtin functions are handled elsewhere");
6139
6140 // These are never l-values; just use the aggregate emission code.
6141 case CK_NonAtomicToAtomic:
6142 case CK_AtomicToNonAtomic:
6143 return EmitAggExprToLValue(E);
6144
6145 case CK_Dynamic: {
6146 LValue LV = EmitLValue(E: E->getSubExpr());
6147 Address V = LV.getAddress();
6148 const auto *DCE = cast<CXXDynamicCastExpr>(Val: E);
6149 return MakeNaturalAlignRawAddrLValue(V: EmitDynamicCast(V, DCE), T: E->getType());
6150 }
6151
6152 case CK_ConstructorConversion:
6153 case CK_UserDefinedConversion:
6154 case CK_CPointerToObjCPointerCast:
6155 case CK_BlockPointerToObjCPointerCast:
6156 case CK_LValueToRValue:
6157 return EmitLValue(E: E->getSubExpr());
6158
6159 case CK_NoOp: {
6160 // CK_NoOp can model a qualification conversion, which can remove an array
6161 // bound and change the IR type.
6162 // FIXME: Once pointee types are removed from IR, remove this.
6163 LValue LV = EmitLValue(E: E->getSubExpr());
6164 // Propagate the volatile qualifer to LValue, if exist in E.
6165 if (E->changesVolatileQualification())
6166 LV.getQuals() = E->getType().getQualifiers();
6167 if (LV.isSimple()) {
6168 Address V = LV.getAddress();
6169 if (V.isValid()) {
6170 llvm::Type *T = ConvertTypeForMem(T: E->getType());
6171 if (V.getElementType() != T)
6172 LV.setAddress(V.withElementType(ElemTy: T));
6173 }
6174 }
6175 return LV;
6176 }
6177
6178 case CK_UncheckedDerivedToBase:
6179 case CK_DerivedToBase: {
6180 auto *DerivedClassDecl = E->getSubExpr()->getType()->castAsCXXRecordDecl();
6181 LValue LV = EmitLValue(E: E->getSubExpr());
6182 Address This = LV.getAddress();
6183
6184 // Perform the derived-to-base conversion
6185 Address Base = GetAddressOfBaseClass(
6186 Value: This, Derived: DerivedClassDecl, PathBegin: E->path_begin(), PathEnd: E->path_end(),
6187 /*NullCheckValue=*/false, Loc: E->getExprLoc());
6188
6189 // TODO: Support accesses to members of base classes in TBAA. For now, we
6190 // conservatively pretend that the complete object is of the base class
6191 // type.
6192 return MakeAddrLValue(Addr: Base, T: E->getType(), BaseInfo: LV.getBaseInfo(),
6193 TBAAInfo: CGM.getTBAAInfoForSubobject(Base: LV, AccessType: E->getType()));
6194 }
6195 case CK_ToUnion:
6196 return EmitAggExprToLValue(E);
6197 case CK_BaseToDerived: {
6198 auto *DerivedClassDecl = E->getType()->castAsCXXRecordDecl();
6199 LValue LV = EmitLValue(E: E->getSubExpr());
6200
6201 // Perform the base-to-derived conversion
6202 Address Derived = GetAddressOfDerivedClass(
6203 Value: LV.getAddress(), Derived: DerivedClassDecl, PathBegin: E->path_begin(), PathEnd: E->path_end(),
6204 /*NullCheckValue=*/false);
6205
6206 // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
6207 // performed and the object is not of the derived type.
6208 if (sanitizePerformTypeCheck())
6209 EmitTypeCheck(TCK: TCK_DowncastReference, Loc: E->getExprLoc(), Addr: Derived,
6210 Type: E->getType());
6211
6212 if (SanOpts.has(K: SanitizerKind::CFIDerivedCast))
6213 EmitVTablePtrCheckForCast(T: E->getType(), Derived,
6214 /*MayBeNull=*/false, TCK: CFITCK_DerivedCast,
6215 Loc: E->getBeginLoc());
6216
6217 return MakeAddrLValue(Addr: Derived, T: E->getType(), BaseInfo: LV.getBaseInfo(),
6218 TBAAInfo: CGM.getTBAAInfoForSubobject(Base: LV, AccessType: E->getType()));
6219 }
6220 case CK_LValueBitCast: {
6221 // This must be a reinterpret_cast (or c-style equivalent).
6222 const auto *CE = cast<ExplicitCastExpr>(Val: E);
6223
6224 CGM.EmitExplicitCastExprType(E: CE, CGF: this);
6225 LValue LV = EmitLValue(E: E->getSubExpr());
6226 Address V = LV.getAddress().withElementType(
6227 ElemTy: ConvertTypeForMem(T: CE->getTypeAsWritten()->getPointeeType()));
6228
6229 if (SanOpts.has(K: SanitizerKind::CFIUnrelatedCast))
6230 EmitVTablePtrCheckForCast(T: E->getType(), Derived: V,
6231 /*MayBeNull=*/false, TCK: CFITCK_UnrelatedCast,
6232 Loc: E->getBeginLoc());
6233
6234 return MakeAddrLValue(Addr: V, T: E->getType(), BaseInfo: LV.getBaseInfo(),
6235 TBAAInfo: CGM.getTBAAInfoForSubobject(Base: LV, AccessType: E->getType()));
6236 }
6237 case CK_AddressSpaceConversion: {
6238 LValue LV = EmitLValue(E: E->getSubExpr());
6239 QualType DestTy = getContext().getPointerType(T: E->getType());
6240 llvm::Value *V =
6241 performAddrSpaceCast(Src: LV.getPointer(CGF&: *this), DestTy: ConvertType(T: DestTy));
6242 return MakeAddrLValue(Addr: Address(V, ConvertTypeForMem(T: E->getType()),
6243 LV.getAddress().getAlignment()),
6244 T: E->getType(), BaseInfo: LV.getBaseInfo(), TBAAInfo: LV.getTBAAInfo());
6245 }
6246 case CK_ObjCObjectLValueCast: {
6247 LValue LV = EmitLValue(E: E->getSubExpr());
6248 Address V = LV.getAddress().withElementType(ElemTy: ConvertType(T: E->getType()));
6249 return MakeAddrLValue(Addr: V, T: E->getType(), BaseInfo: LV.getBaseInfo(),
6250 TBAAInfo: CGM.getTBAAInfoForSubobject(Base: LV, AccessType: E->getType()));
6251 }
6252 case CK_ZeroToOCLOpaqueType:
6253 llvm_unreachable("NULL to OpenCL opaque type lvalue cast is not valid");
6254
6255 case CK_VectorSplat: {
6256 // LValue results of vector splats are only supported in HLSL.
6257 if (!getLangOpts().HLSL)
6258 return EmitUnsupportedLValue(E, Name: "unexpected cast lvalue");
6259 return EmitLValue(E: E->getSubExpr());
6260 }
6261 }
6262
6263 llvm_unreachable("Unhandled lvalue cast kind?");
6264}
6265
6266LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
6267 assert(OpaqueValueMappingData::shouldBindAsLValue(e));
6268 return getOrCreateOpaqueLValueMapping(e);
6269}
6270
6271std::pair<LValue, LValue>
6272CodeGenFunction::EmitHLSLOutArgLValues(const HLSLOutArgExpr *E, QualType Ty) {
6273 // Emitting the casted temporary through an opaque value.
6274 LValue BaseLV = EmitLValue(E: E->getArgLValue());
6275 OpaqueValueMappingData::bind(CGF&: *this, ov: E->getOpaqueArgLValue(), lv: BaseLV);
6276
6277 QualType ExprTy = E->getType();
6278 Address OutTemp = CreateIRTempWithoutCast(Ty: ExprTy);
6279 LValue TempLV = MakeAddrLValue(Addr: OutTemp, T: ExprTy);
6280
6281 if (E->isInOut())
6282 EmitInitializationToLValue(E: E->getCastedTemporary()->getSourceExpr(),
6283 LV: TempLV);
6284
6285 OpaqueValueMappingData::bind(CGF&: *this, ov: E->getCastedTemporary(), lv: TempLV);
6286 return std::make_pair(x&: BaseLV, y&: TempLV);
6287}
6288
6289LValue CodeGenFunction::EmitHLSLOutArgExpr(const HLSLOutArgExpr *E,
6290 CallArgList &Args, QualType Ty) {
6291
6292 auto [BaseLV, TempLV] = EmitHLSLOutArgLValues(E, Ty);
6293
6294 llvm::Value *Addr = TempLV.getAddress().getBasePointer();
6295 llvm::Type *ElTy = ConvertTypeForMem(T: TempLV.getType());
6296
6297 EmitLifetimeStart(Addr);
6298
6299 Address TmpAddr(Addr, ElTy, TempLV.getAlignment());
6300 Args.addWriteback(srcLV: BaseLV, temporary: TmpAddr, toUse: nullptr, writebackExpr: E->getWritebackCast());
6301 Args.add(rvalue: RValue::get(Addr: TmpAddr, CGF&: *this), type: Ty);
6302 return TempLV;
6303}
6304
6305LValue
6306CodeGenFunction::getOrCreateOpaqueLValueMapping(const OpaqueValueExpr *e) {
6307 assert(OpaqueValueMapping::shouldBindAsLValue(e));
6308
6309 llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator
6310 it = OpaqueLValues.find(Val: e);
6311
6312 if (it != OpaqueLValues.end())
6313 return it->second;
6314
6315 assert(e->isUnique() && "LValue for a nonunique OVE hasn't been emitted");
6316 return EmitLValue(E: e->getSourceExpr());
6317}
6318
6319RValue
6320CodeGenFunction::getOrCreateOpaqueRValueMapping(const OpaqueValueExpr *e) {
6321 assert(!OpaqueValueMapping::shouldBindAsLValue(e));
6322
6323 llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator
6324 it = OpaqueRValues.find(Val: e);
6325
6326 if (it != OpaqueRValues.end())
6327 return it->second;
6328
6329 assert(e->isUnique() && "RValue for a nonunique OVE hasn't been emitted");
6330 return EmitAnyExpr(E: e->getSourceExpr());
6331}
6332
6333bool CodeGenFunction::isOpaqueValueEmitted(const OpaqueValueExpr *E) {
6334 if (OpaqueValueMapping::shouldBindAsLValue(expr: E))
6335 return OpaqueLValues.contains(Val: E);
6336 return OpaqueRValues.contains(Val: E);
6337}
6338
6339RValue CodeGenFunction::EmitRValueForField(LValue LV,
6340 const FieldDecl *FD,
6341 SourceLocation Loc) {
6342 QualType FT = FD->getType();
6343 LValue FieldLV = EmitLValueForField(base: LV, field: FD);
6344 switch (getEvaluationKind(T: FT)) {
6345 case TEK_Complex:
6346 return RValue::getComplex(C: EmitLoadOfComplex(src: FieldLV, loc: Loc));
6347 case TEK_Aggregate:
6348 return FieldLV.asAggregateRValue();
6349 case TEK_Scalar:
6350 // This routine is used to load fields one-by-one to perform a copy, so
6351 // don't load reference fields.
6352 if (FD->getType()->isReferenceType())
6353 return RValue::get(V: FieldLV.getPointer(CGF&: *this));
6354 // Call EmitLoadOfScalar except when the lvalue is a bitfield to emit a
6355 // primitive load.
6356 if (FieldLV.isBitField())
6357 return EmitLoadOfLValue(LV: FieldLV, Loc);
6358 return RValue::get(V: EmitLoadOfScalar(lvalue: FieldLV, Loc));
6359 }
6360 llvm_unreachable("bad evaluation kind");
6361}
6362
6363//===--------------------------------------------------------------------===//
6364// Expression Emission
6365//===--------------------------------------------------------------------===//
6366
6367RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
6368 ReturnValueSlot ReturnValue,
6369 llvm::CallBase **CallOrInvoke) {
6370 llvm::CallBase *CallOrInvokeStorage;
6371 if (!CallOrInvoke) {
6372 CallOrInvoke = &CallOrInvokeStorage;
6373 }
6374
6375 llvm::scope_exit AddCoroElideSafeOnExit([&] {
6376 if (E->isCoroElideSafe()) {
6377 auto *I = *CallOrInvoke;
6378 if (I)
6379 I->addFnAttr(Kind: llvm::Attribute::CoroElideSafe);
6380 }
6381 });
6382
6383 // Builtins never have block type.
6384 if (E->getCallee()->getType()->isBlockPointerType())
6385 return EmitBlockCallExpr(E, ReturnValue, CallOrInvoke);
6386
6387 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(Val: E))
6388 return EmitCXXMemberCallExpr(E: CE, ReturnValue, CallOrInvoke);
6389
6390 if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(Val: E))
6391 return EmitCUDAKernelCallExpr(E: CE, ReturnValue, CallOrInvoke);
6392
6393 // A CXXOperatorCallExpr is created even for explicit object methods, but
6394 // these should be treated like static function call.
6395 if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(Val: E))
6396 if (const auto *MD =
6397 dyn_cast_if_present<CXXMethodDecl>(Val: CE->getCalleeDecl());
6398 MD && MD->isImplicitObjectMemberFunction())
6399 return EmitCXXOperatorMemberCallExpr(E: CE, MD, ReturnValue, CallOrInvoke);
6400
6401 CGCallee callee = EmitCallee(E: E->getCallee());
6402
6403 if (callee.isBuiltin()) {
6404 return EmitBuiltinExpr(GD: callee.getBuiltinDecl(), BuiltinID: callee.getBuiltinID(),
6405 E, ReturnValue);
6406 }
6407
6408 if (callee.isPseudoDestructor()) {
6409 return EmitCXXPseudoDestructorExpr(E: callee.getPseudoDestructorExpr());
6410 }
6411
6412 return EmitCall(FnType: E->getCallee()->getType(), Callee: callee, E, ReturnValue,
6413 /*Chain=*/nullptr, CallOrInvoke);
6414}
6415
6416/// Emit a CallExpr without considering whether it might be a subclass.
6417RValue CodeGenFunction::EmitSimpleCallExpr(const CallExpr *E,
6418 ReturnValueSlot ReturnValue,
6419 llvm::CallBase **CallOrInvoke) {
6420 CGCallee Callee = EmitCallee(E: E->getCallee());
6421 return EmitCall(FnType: E->getCallee()->getType(), Callee, E, ReturnValue,
6422 /*Chain=*/nullptr, CallOrInvoke);
6423}
6424
6425// Detect the unusual situation where an inline version is shadowed by a
6426// non-inline version. In that case we should pick the external one
6427// everywhere. That's GCC behavior too.
6428static bool OnlyHasInlineBuiltinDeclaration(const FunctionDecl *FD) {
6429 for (const FunctionDecl *PD = FD; PD; PD = PD->getPreviousDecl())
6430 if (!PD->isInlineBuiltinDeclaration())
6431 return false;
6432 return true;
6433}
6434
6435static CGCallee EmitDirectCallee(CodeGenFunction &CGF, GlobalDecl GD) {
6436 const FunctionDecl *FD = cast<FunctionDecl>(Val: GD.getDecl());
6437
6438 if (auto builtinID = FD->getBuiltinID()) {
6439 std::string NoBuiltinFD = ("no-builtin-" + FD->getName()).str();
6440 std::string NoBuiltins = "no-builtins";
6441
6442 StringRef Ident = CGF.CGM.getMangledName(GD);
6443 std::string FDInlineName = (Ident + ".inline").str();
6444
6445 bool IsPredefinedLibFunction =
6446 CGF.getContext().BuiltinInfo.isPredefinedLibFunction(ID: builtinID);
6447 bool HasAttributeNoBuiltin =
6448 CGF.CurFn->getAttributes().hasFnAttr(Kind: NoBuiltinFD) ||
6449 CGF.CurFn->getAttributes().hasFnAttr(Kind: NoBuiltins);
6450
6451 // When directing calling an inline builtin, call it through it's mangled
6452 // name to make it clear it's not the actual builtin.
6453 if (CGF.CurFn->getName() != FDInlineName &&
6454 OnlyHasInlineBuiltinDeclaration(FD)) {
6455 llvm::Constant *CalleePtr = CGF.CGM.getRawFunctionPointer(GD);
6456 llvm::Function *Fn = llvm::cast<llvm::Function>(Val: CalleePtr);
6457 llvm::Module *M = Fn->getParent();
6458 llvm::Function *Clone = M->getFunction(Name: FDInlineName);
6459 if (!Clone) {
6460 Clone = llvm::Function::Create(Ty: Fn->getFunctionType(),
6461 Linkage: llvm::GlobalValue::InternalLinkage,
6462 AddrSpace: Fn->getAddressSpace(), N: FDInlineName, M);
6463 Clone->addFnAttr(Kind: llvm::Attribute::AlwaysInline);
6464 }
6465 return CGCallee::forDirect(functionPtr: Clone, abstractInfo: GD);
6466 }
6467
6468 // Replaceable builtins provide their own implementation of a builtin. If we
6469 // are in an inline builtin implementation, avoid trivial infinite
6470 // recursion. Honor __attribute__((no_builtin("foo"))) or
6471 // __attribute__((no_builtin)) on the current function unless foo is
6472 // not a predefined library function which means we must generate the
6473 // builtin no matter what.
6474 else if (!IsPredefinedLibFunction || !HasAttributeNoBuiltin)
6475 return CGCallee::forBuiltin(builtinID, builtinDecl: FD);
6476 }
6477
6478 llvm::Constant *CalleePtr = CGF.CGM.getRawFunctionPointer(GD);
6479 if (CGF.CGM.getLangOpts().CUDA && !CGF.CGM.getLangOpts().CUDAIsDevice &&
6480 FD->hasAttr<CUDAGlobalAttr>())
6481 CalleePtr = CGF.CGM.getCUDARuntime().getKernelStub(
6482 Handle: cast<llvm::GlobalValue>(Val: CalleePtr->stripPointerCasts()));
6483
6484 return CGCallee::forDirect(functionPtr: CalleePtr, abstractInfo: GD);
6485}
6486
6487static GlobalDecl getGlobalDeclForDirectCall(const FunctionDecl *FD) {
6488 if (DeviceKernelAttr::isOpenCLSpelling(A: FD->getAttr<DeviceKernelAttr>()))
6489 return GlobalDecl(FD, KernelReferenceKind::Stub);
6490 return GlobalDecl(FD);
6491}
6492
6493CGCallee CodeGenFunction::EmitCallee(const Expr *E) {
6494 E = E->IgnoreParens();
6495
6496 // Look through function-to-pointer decay.
6497 if (auto ICE = dyn_cast<ImplicitCastExpr>(Val: E)) {
6498 if (ICE->getCastKind() == CK_FunctionToPointerDecay ||
6499 ICE->getCastKind() == CK_BuiltinFnToFnPtr) {
6500 return EmitCallee(E: ICE->getSubExpr());
6501 }
6502
6503 // Try to remember the original __ptrauth qualifier for loads of
6504 // function pointers.
6505 if (ICE->getCastKind() == CK_LValueToRValue) {
6506 const Expr *SubExpr = ICE->getSubExpr();
6507 if (const auto *PtrType = SubExpr->getType()->getAs<PointerType>()) {
6508 std::pair<llvm::Value *, CGPointerAuthInfo> Result =
6509 EmitOrigPointerRValue(E);
6510
6511 QualType FunctionType = PtrType->getPointeeType();
6512 assert(FunctionType->isFunctionType());
6513
6514 GlobalDecl GD;
6515 if (const auto *VD =
6516 dyn_cast_or_null<VarDecl>(Val: E->getReferencedDeclOfCallee())) {
6517 GD = GlobalDecl(VD);
6518 }
6519 CGCalleeInfo CalleeInfo(FunctionType->getAs<FunctionProtoType>(), GD);
6520 CGCallee Callee(CalleeInfo, Result.first, Result.second);
6521 return Callee;
6522 }
6523 }
6524
6525 // Resolve direct calls.
6526 } else if (auto DRE = dyn_cast<DeclRefExpr>(Val: E)) {
6527 if (auto FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl())) {
6528 return EmitDirectCallee(CGF&: *this, GD: getGlobalDeclForDirectCall(FD));
6529 }
6530 } else if (auto ME = dyn_cast<MemberExpr>(Val: E)) {
6531 if (auto FD = dyn_cast<FunctionDecl>(Val: ME->getMemberDecl())) {
6532 EmitIgnoredExpr(E: ME->getBase());
6533 return EmitDirectCallee(CGF&: *this, GD: FD);
6534 }
6535
6536 // Look through template substitutions.
6537 } else if (auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(Val: E)) {
6538 return EmitCallee(E: NTTP->getReplacement());
6539
6540 // Treat pseudo-destructor calls differently.
6541 } else if (auto PDE = dyn_cast<CXXPseudoDestructorExpr>(Val: E)) {
6542 return CGCallee::forPseudoDestructor(E: PDE);
6543 }
6544
6545 // Otherwise, we have an indirect reference.
6546 llvm::Value *calleePtr;
6547 QualType functionType;
6548 if (auto ptrType = E->getType()->getAs<PointerType>()) {
6549 calleePtr = EmitScalarExpr(E);
6550 functionType = ptrType->getPointeeType();
6551 } else {
6552 functionType = E->getType();
6553 calleePtr = EmitLValue(E, IsKnownNonNull: KnownNonNull).getPointer(CGF&: *this);
6554 }
6555 assert(functionType->isFunctionType());
6556
6557 GlobalDecl GD;
6558 if (const auto *VD =
6559 dyn_cast_or_null<VarDecl>(Val: E->getReferencedDeclOfCallee()))
6560 GD = GlobalDecl(VD);
6561
6562 CGCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(), GD);
6563 CGPointerAuthInfo pointerAuth = CGM.getFunctionPointerAuthInfo(T: functionType);
6564 CGCallee callee(calleeInfo, calleePtr, pointerAuth);
6565 return callee;
6566}
6567
6568LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
6569 // Comma expressions just emit their LHS then their RHS as an l-value.
6570 if (E->getOpcode() == BO_Comma) {
6571 EmitIgnoredExpr(E: E->getLHS());
6572 EnsureInsertPoint();
6573 return EmitLValue(E: E->getRHS());
6574 }
6575
6576 if (E->getOpcode() == BO_PtrMemD ||
6577 E->getOpcode() == BO_PtrMemI)
6578 return EmitPointerToDataMemberBinaryExpr(E);
6579
6580 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
6581
6582 // Create a Key Instructions source location atom group that covers both
6583 // LHS and RHS expressions. Nested RHS expressions may get subsequently
6584 // separately grouped (1 below):
6585 //
6586 // 1. `a = b = c` -> Two atoms.
6587 // 2. `x = new(1)` -> One atom (for both addr store and value store).
6588 // 3. Complex and agg assignment -> One atom.
6589 ApplyAtomGroup Grp(getDebugInfo());
6590
6591 // Note that in all of these cases, __block variables need the RHS
6592 // evaluated first just in case the variable gets moved by the RHS.
6593
6594 switch (getEvaluationKind(T: E->getType())) {
6595 case TEK_Scalar: {
6596 if (PointerAuthQualifier PtrAuth =
6597 E->getLHS()->getType().getPointerAuth()) {
6598 LValue LV = EmitCheckedLValue(E: E->getLHS(), TCK: TCK_Store);
6599 LValue CopiedLV = LV;
6600 CopiedLV.getQuals().removePointerAuth();
6601 llvm::Value *RV =
6602 EmitPointerAuthQualify(Qualifier: PtrAuth, PointerExpr: E->getRHS(), StorageAddress: CopiedLV.getAddress());
6603 EmitNullabilityCheck(LHS: CopiedLV, RHS: RV, Loc: E->getExprLoc());
6604 EmitStoreThroughLValue(Src: RValue::get(V: RV), Dst: CopiedLV);
6605 return LV;
6606 }
6607
6608 switch (E->getLHS()->getType().getObjCLifetime()) {
6609 case Qualifiers::OCL_Strong:
6610 return EmitARCStoreStrong(e: E, /*ignored*/ false).first;
6611
6612 case Qualifiers::OCL_Autoreleasing:
6613 return EmitARCStoreAutoreleasing(e: E).first;
6614
6615 // No reason to do any of these differently.
6616 case Qualifiers::OCL_None:
6617 case Qualifiers::OCL_ExplicitNone:
6618 case Qualifiers::OCL_Weak:
6619 break;
6620 }
6621
6622 // TODO: Can we de-duplicate this code with the corresponding code in
6623 // CGExprScalar, similar to the way EmitCompoundAssignmentLValue works?
6624 RValue RV;
6625 llvm::Value *Previous = nullptr;
6626 QualType SrcType = E->getRHS()->getType();
6627 // Check if LHS is a bitfield, if RHS contains an implicit cast expression
6628 // we want to extract that value and potentially (if the bitfield sanitizer
6629 // is enabled) use it to check for an implicit conversion.
6630 if (E->getLHS()->refersToBitField()) {
6631 llvm::Value *RHS =
6632 EmitWithOriginalRHSBitfieldAssignment(E, Previous: &Previous, SrcType: &SrcType);
6633 RV = RValue::get(V: RHS);
6634 } else
6635 RV = EmitAnyExpr(E: E->getRHS());
6636
6637 LValue LV = EmitCheckedLValue(E: E->getLHS(), TCK: TCK_Store);
6638
6639 if (RV.isScalar())
6640 EmitNullabilityCheck(LHS: LV, RHS: RV.getScalarVal(), Loc: E->getExprLoc());
6641
6642 if (LV.isBitField()) {
6643 llvm::Value *Result = nullptr;
6644 // If bitfield sanitizers are enabled we want to use the result
6645 // to check whether a truncation or sign change has occurred.
6646 if (SanOpts.has(K: SanitizerKind::ImplicitBitfieldConversion))
6647 EmitStoreThroughBitfieldLValue(Src: RV, Dst: LV, Result: &Result);
6648 else
6649 EmitStoreThroughBitfieldLValue(Src: RV, Dst: LV);
6650
6651 // If the expression contained an implicit conversion, make sure
6652 // to use the value before the scalar conversion.
6653 llvm::Value *Src = Previous ? Previous : RV.getScalarVal();
6654 QualType DstType = E->getLHS()->getType();
6655 EmitBitfieldConversionCheck(Src, SrcType, Dst: Result, DstType,
6656 Info: LV.getBitFieldInfo(), Loc: E->getExprLoc());
6657 } else
6658 EmitStoreThroughLValue(Src: RV, Dst: LV);
6659
6660 if (getLangOpts().OpenMP)
6661 CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF&: *this,
6662 LHS: E->getLHS());
6663 return LV;
6664 }
6665
6666 case TEK_Complex:
6667 return EmitComplexAssignmentLValue(E);
6668
6669 case TEK_Aggregate:
6670 // If the lang opt is HLSL and the LHS is a constant array
6671 // then we are performing a copy assignment and call a special
6672 // function because EmitAggExprToLValue emits to a temporary LValue
6673 if (getLangOpts().HLSL && E->getLHS()->getType()->isConstantArrayType())
6674 return EmitHLSLArrayAssignLValue(E);
6675
6676 return EmitAggExprToLValue(E);
6677 }
6678 llvm_unreachable("bad evaluation kind");
6679}
6680
6681// This function implements trivial copy assignment for HLSL's
6682// assignable constant arrays.
6683LValue CodeGenFunction::EmitHLSLArrayAssignLValue(const BinaryOperator *E) {
6684 // Don't emit an LValue for the RHS because it might not be an LValue
6685 LValue LHS = EmitLValue(E: E->getLHS());
6686
6687 // If the RHS is a global resource array, copy all individual resources
6688 // into LHS.
6689 if (E->getRHS()->getType()->isHLSLResourceRecordArray())
6690 if (CGM.getHLSLRuntime().emitResourceArrayCopy(LHS, RHSExpr: E->getRHS(), CGF&: *this))
6691 return LHS;
6692
6693 // In C the RHS of an assignment operator is an RValue.
6694 // EmitAggregateAssign takes an LValue for the RHS. Instead we can call
6695 // EmitInitializationToLValue to emit an RValue into an LValue.
6696 EmitInitializationToLValue(E: E->getRHS(), LV: LHS);
6697 return LHS;
6698}
6699
6700LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E,
6701 llvm::CallBase **CallOrInvoke) {
6702 RValue RV = EmitCallExpr(E, ReturnValue: ReturnValueSlot(), CallOrInvoke);
6703
6704 if (!RV.isScalar())
6705 return MakeAddrLValue(Addr: RV.getAggregateAddress(), T: E->getType(),
6706 Source: AlignmentSource::Decl);
6707
6708 assert(E->getCallReturnType(getContext())->isReferenceType() &&
6709 "Can't have a scalar return unless the return type is a "
6710 "reference type!");
6711
6712 return MakeNaturalAlignPointeeAddrLValue(V: RV.getScalarVal(), T: E->getType());
6713}
6714
6715LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
6716 // FIXME: This shouldn't require another copy.
6717 return EmitAggExprToLValue(E);
6718}
6719
6720LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
6721 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
6722 && "binding l-value to type which needs a temporary");
6723 AggValueSlot Slot = CreateAggTemp(T: E->getType());
6724 EmitCXXConstructExpr(E, Dest: Slot);
6725 return MakeAddrLValue(Addr: Slot.getAddress(), T: E->getType(), Source: AlignmentSource::Decl);
6726}
6727
6728LValue
6729CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
6730 return MakeNaturalAlignRawAddrLValue(V: EmitCXXTypeidExpr(E), T: E->getType());
6731}
6732
6733Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
6734 return CGM.GetAddrOfMSGuidDecl(GD: E->getGuidDecl())
6735 .withElementType(ElemTy: ConvertType(T: E->getType()));
6736}
6737
6738LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
6739 return MakeAddrLValue(Addr: EmitCXXUuidofExpr(E), T: E->getType(),
6740 Source: AlignmentSource::Decl);
6741}
6742
6743LValue
6744CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
6745 AggValueSlot Slot = CreateAggTemp(T: E->getType(), Name: "temp.lvalue");
6746 Slot.setExternallyDestructed();
6747 EmitAggExpr(E: E->getSubExpr(), AS: Slot);
6748 EmitCXXTemporary(Temporary: E->getTemporary(), TempType: E->getType(), Ptr: Slot.getAddress());
6749 return MakeAddrLValue(Addr: Slot.getAddress(), T: E->getType(), Source: AlignmentSource::Decl);
6750}
6751
6752LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
6753 RValue RV = EmitObjCMessageExpr(E);
6754
6755 if (!RV.isScalar())
6756 return MakeAddrLValue(Addr: RV.getAggregateAddress(), T: E->getType(),
6757 Source: AlignmentSource::Decl);
6758
6759 assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
6760 "Can't have a scalar return unless the return type is a "
6761 "reference type!");
6762
6763 return MakeNaturalAlignPointeeAddrLValue(V: RV.getScalarVal(), T: E->getType());
6764}
6765
6766LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
6767 Address V =
6768 CGM.getObjCRuntime().GetAddrOfSelector(CGF&: *this, Sel: E->getSelector());
6769 return MakeAddrLValue(Addr: V, T: E->getType(), Source: AlignmentSource::Decl);
6770}
6771
6772llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
6773 const ObjCIvarDecl *Ivar) {
6774 return CGM.getObjCRuntime().EmitIvarOffset(CGF&: *this, Interface, Ivar);
6775}
6776
6777llvm::Value *
6778CodeGenFunction::EmitIvarOffsetAsPointerDiff(const ObjCInterfaceDecl *Interface,
6779 const ObjCIvarDecl *Ivar) {
6780 llvm::Value *OffsetValue = EmitIvarOffset(Interface, Ivar);
6781 QualType PointerDiffType = getContext().getPointerDiffType();
6782 return Builder.CreateZExtOrTrunc(V: OffsetValue,
6783 DestTy: getTypes().ConvertType(T: PointerDiffType));
6784}
6785
6786LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
6787 llvm::Value *BaseValue,
6788 const ObjCIvarDecl *Ivar,
6789 unsigned CVRQualifiers) {
6790 return CGM.getObjCRuntime().EmitObjCValueForIvar(CGF&: *this, ObjectTy, BaseValue,
6791 Ivar, CVRQualifiers);
6792}
6793
6794LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
6795 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
6796 llvm::Value *BaseValue = nullptr;
6797 const Expr *BaseExpr = E->getBase();
6798 Qualifiers BaseQuals;
6799 QualType ObjectTy;
6800 if (E->isArrow()) {
6801 BaseValue = EmitScalarExpr(E: BaseExpr);
6802 ObjectTy = BaseExpr->getType()->getPointeeType();
6803 BaseQuals = ObjectTy.getQualifiers();
6804 } else {
6805 LValue BaseLV = EmitLValue(E: BaseExpr);
6806 BaseValue = BaseLV.getPointer(CGF&: *this);
6807 ObjectTy = BaseExpr->getType();
6808 BaseQuals = ObjectTy.getQualifiers();
6809 }
6810
6811 LValue LV =
6812 EmitLValueForIvar(ObjectTy, BaseValue, Ivar: E->getDecl(),
6813 CVRQualifiers: BaseQuals.getCVRQualifiers());
6814 setObjCGCLValueClass(Ctx: getContext(), E, LV);
6815 return LV;
6816}
6817
6818LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
6819 // Can only get l-value for message expression returning aggregate type
6820 RValue RV = EmitAnyExprToTemp(E);
6821 return MakeAddrLValue(Addr: RV.getAggregateAddress(), T: E->getType(),
6822 Source: AlignmentSource::Decl);
6823}
6824
6825RValue CodeGenFunction::EmitCall(QualType CalleeType,
6826 const CGCallee &OrigCallee, const CallExpr *E,
6827 ReturnValueSlot ReturnValue,
6828 llvm::Value *Chain,
6829 llvm::CallBase **CallOrInvoke,
6830 CGFunctionInfo const **ResolvedFnInfo) {
6831 // Get the actual function type. The callee type will always be a pointer to
6832 // function type or a block pointer type.
6833 assert(CalleeType->isFunctionPointerType() &&
6834 "Call must have function pointer type!");
6835
6836 const Decl *TargetDecl =
6837 OrigCallee.getAbstractInfo().getCalleeDecl().getDecl();
6838
6839 assert((!isa_and_present<FunctionDecl>(TargetDecl) ||
6840 !cast<FunctionDecl>(TargetDecl)->isImmediateFunction()) &&
6841 "trying to emit a call to an immediate function");
6842
6843 CalleeType = getContext().getCanonicalType(T: CalleeType);
6844
6845 auto PointeeType = cast<PointerType>(Val&: CalleeType)->getPointeeType();
6846
6847 CGCallee Callee = OrigCallee;
6848
6849 bool CFIUnchecked = CalleeType->hasPointeeToCFIUncheckedCalleeFunctionType();
6850
6851 if (SanOpts.has(K: SanitizerKind::Function) &&
6852 (!TargetDecl || !isa<FunctionDecl>(Val: TargetDecl)) &&
6853 !isa<FunctionNoProtoType>(Val: PointeeType) && !CFIUnchecked) {
6854 if (llvm::Constant *PrefixSig =
6855 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
6856 auto CheckOrdinal = SanitizerKind::SO_Function;
6857 auto CheckHandler = SanitizerHandler::FunctionTypeMismatch;
6858 SanitizerDebugLocation SanScope(this, {CheckOrdinal}, CheckHandler);
6859 auto *TypeHash = getUBSanFunctionTypeHash(T: PointeeType);
6860
6861 llvm::Type *PrefixSigType = PrefixSig->getType();
6862 llvm::StructType *PrefixStructTy = llvm::StructType::get(
6863 Context&: CGM.getLLVMContext(), Elements: {PrefixSigType, Int32Ty}, /*isPacked=*/true);
6864
6865 llvm::Value *CalleePtr = Callee.getFunctionPointer();
6866 if (CGM.getCodeGenOpts().PointerAuth.FunctionPointers) {
6867 // Use raw pointer since we are using the callee pointer as data here.
6868 Address Addr =
6869 Address(CalleePtr, CalleePtr->getType(),
6870 CharUnits::fromQuantity(
6871 Quantity: CalleePtr->getPointerAlignment(DL: CGM.getDataLayout())),
6872 Callee.getPointerAuthInfo(), nullptr);
6873 CalleePtr = Addr.emitRawPointer(CGF&: *this);
6874 }
6875
6876 // On 32-bit Arm, the low bit of a function pointer indicates whether
6877 // it's using the Arm or Thumb instruction set. The actual first
6878 // instruction lives at the same address either way, so we must clear
6879 // that low bit before using the function address to find the prefix
6880 // structure.
6881 //
6882 // This applies to both Arm and Thumb target triples, because
6883 // either one could be used in an interworking context where it
6884 // might be passed function pointers of both types.
6885 llvm::Value *AlignedCalleePtr;
6886 if (CGM.getTriple().isARM() || CGM.getTriple().isThumb()) {
6887 llvm::Value *CalleeAddress =
6888 Builder.CreatePtrToInt(V: CalleePtr, DestTy: IntPtrTy);
6889 llvm::Value *Mask = llvm::ConstantInt::getSigned(Ty: IntPtrTy, V: ~1);
6890 llvm::Value *AlignedCalleeAddress =
6891 Builder.CreateAnd(LHS: CalleeAddress, RHS: Mask);
6892 AlignedCalleePtr =
6893 Builder.CreateIntToPtr(V: AlignedCalleeAddress, DestTy: CalleePtr->getType());
6894 } else {
6895 AlignedCalleePtr = CalleePtr;
6896 }
6897
6898 llvm::Value *CalleePrefixStruct = AlignedCalleePtr;
6899 llvm::Value *CalleeSigPtr =
6900 Builder.CreateConstGEP2_32(Ty: PrefixStructTy, Ptr: CalleePrefixStruct, Idx0: -1, Idx1: 0);
6901 llvm::Value *CalleeSig =
6902 Builder.CreateAlignedLoad(Ty: PrefixSigType, Addr: CalleeSigPtr, Align: getIntAlign());
6903 llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(LHS: CalleeSig, RHS: PrefixSig);
6904
6905 llvm::BasicBlock *Cont = createBasicBlock(name: "cont");
6906 llvm::BasicBlock *TypeCheck = createBasicBlock(name: "typecheck");
6907 Builder.CreateCondBr(Cond: CalleeSigMatch, True: TypeCheck, False: Cont);
6908
6909 EmitBlock(BB: TypeCheck);
6910 llvm::Value *CalleeTypeHash = Builder.CreateAlignedLoad(
6911 Ty: Int32Ty,
6912 Addr: Builder.CreateConstGEP2_32(Ty: PrefixStructTy, Ptr: CalleePrefixStruct, Idx0: -1, Idx1: 1),
6913 Align: getPointerAlign());
6914 llvm::Value *CalleeTypeHashMatch =
6915 Builder.CreateICmpEQ(LHS: CalleeTypeHash, RHS: TypeHash);
6916 llvm::Constant *StaticData[] = {EmitCheckSourceLocation(Loc: E->getBeginLoc()),
6917 EmitCheckTypeDescriptor(T: CalleeType)};
6918 EmitCheck(Checked: std::make_pair(x&: CalleeTypeHashMatch, y&: CheckOrdinal), CheckHandler,
6919 StaticArgs: StaticData, DynamicArgs: {CalleePtr});
6920
6921 Builder.CreateBr(Dest: Cont);
6922 EmitBlock(BB: Cont);
6923 }
6924 }
6925
6926 const auto *FnType = cast<FunctionType>(Val&: PointeeType);
6927
6928 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(Val: TargetDecl);
6929 FD && DeviceKernelAttr::isOpenCLSpelling(A: FD->getAttr<DeviceKernelAttr>()))
6930 CGM.getTargetCodeGenInfo().setOCLKernelStubCallingConvention(FnType);
6931
6932 // If we are checking indirect calls and this call is indirect, check that the
6933 // function pointer is a member of the bit set for the function type.
6934 if (SanOpts.has(K: SanitizerKind::CFIICall) &&
6935 (!TargetDecl || !isa<FunctionDecl>(Val: TargetDecl)) && !CFIUnchecked) {
6936 auto CheckOrdinal = SanitizerKind::SO_CFIICall;
6937 auto CheckHandler = SanitizerHandler::CFICheckFail;
6938 SanitizerDebugLocation SanScope(this, {CheckOrdinal}, CheckHandler);
6939 EmitSanitizerStatReport(SSK: llvm::SanStat_CFI_ICall);
6940
6941 llvm::Metadata *MD =
6942 CGM.CreateMetadataIdentifierForFnType(T: QualType(FnType, 0));
6943
6944 llvm::Value *TypeId = llvm::MetadataAsValue::get(Context&: getLLVMContext(), MD);
6945
6946 llvm::Value *CalleePtr = Callee.getFunctionPointer();
6947 llvm::Value *TypeTest = Builder.CreateCall(
6948 Callee: CGM.getIntrinsic(IID: llvm::Intrinsic::type_test), Args: {CalleePtr, TypeId});
6949
6950 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
6951 llvm::Constant *StaticData[] = {
6952 llvm::ConstantInt::get(Ty: Int8Ty, V: CFITCK_ICall),
6953 EmitCheckSourceLocation(Loc: E->getBeginLoc()),
6954 EmitCheckTypeDescriptor(T: QualType(FnType, 0)),
6955 };
6956 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
6957 EmitCfiSlowPathCheck(Ordinal: CheckOrdinal, Cond: TypeTest, TypeId: CrossDsoTypeId, Ptr: CalleePtr,
6958 StaticArgs: StaticData);
6959 } else {
6960 EmitCheck(Checked: std::make_pair(x&: TypeTest, y&: CheckOrdinal), CheckHandler,
6961 StaticArgs: StaticData, DynamicArgs: {CalleePtr, llvm::UndefValue::get(T: IntPtrTy)});
6962 }
6963 }
6964
6965 CallArgList Args;
6966 if (Chain)
6967 Args.add(rvalue: RValue::get(V: Chain), type: CGM.getContext().VoidPtrTy);
6968
6969 // C++17 requires that we evaluate arguments to a call using assignment syntax
6970 // right-to-left, and that we evaluate arguments to certain other operators
6971 // left-to-right. Note that we allow this to override the order dictated by
6972 // the calling convention on the MS ABI, which means that parameter
6973 // destruction order is not necessarily reverse construction order.
6974 // FIXME: Revisit this based on C++ committee response to unimplementability.
6975 EvaluationOrder Order = EvaluationOrder::Default;
6976 bool StaticOperator = false;
6977 if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(Val: E)) {
6978 if (OCE->isAssignmentOp())
6979 Order = EvaluationOrder::ForceRightToLeft;
6980 else {
6981 switch (OCE->getOperator()) {
6982 case OO_LessLess:
6983 case OO_GreaterGreater:
6984 case OO_AmpAmp:
6985 case OO_PipePipe:
6986 case OO_Comma:
6987 case OO_ArrowStar:
6988 Order = EvaluationOrder::ForceLeftToRight;
6989 break;
6990 default:
6991 break;
6992 }
6993 }
6994
6995 if (const auto *MD =
6996 dyn_cast_if_present<CXXMethodDecl>(Val: OCE->getCalleeDecl());
6997 MD && MD->isStatic())
6998 StaticOperator = true;
6999 }
7000
7001 auto Arguments = E->arguments();
7002 if (StaticOperator) {
7003 // If we're calling a static operator, we need to emit the object argument
7004 // and ignore it.
7005 EmitIgnoredExpr(E: E->getArg(Arg: 0));
7006 Arguments = drop_begin(RangeOrContainer&: Arguments, N: 1);
7007 }
7008 EmitCallArgs(Args, Prototype: dyn_cast<FunctionProtoType>(Val: FnType), ArgRange: Arguments,
7009 AC: E->getDirectCallee(), /*ParamsToSkip=*/0, Order);
7010
7011 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
7012 Args, Ty: FnType, /*ChainCall=*/Chain);
7013
7014 if (ResolvedFnInfo)
7015 *ResolvedFnInfo = &FnInfo;
7016
7017 // HIP function pointer contains kernel handle when it is used in triple
7018 // chevron. The kernel stub needs to be loaded from kernel handle and used
7019 // as callee.
7020 if (CGM.getLangOpts().HIP && !CGM.getLangOpts().CUDAIsDevice &&
7021 isa<CUDAKernelCallExpr>(Val: E) &&
7022 (!TargetDecl || !isa<FunctionDecl>(Val: TargetDecl))) {
7023 llvm::Value *Handle = Callee.getFunctionPointer();
7024 auto *Stub = Builder.CreateLoad(
7025 Addr: Address(Handle, Handle->getType(), CGM.getPointerAlign()));
7026 Callee.setFunctionPointer(Stub);
7027 }
7028 llvm::CallBase *LocalCallOrInvoke = nullptr;
7029 RValue Call = EmitCall(CallInfo: FnInfo, Callee, ReturnValue, Args, CallOrInvoke: &LocalCallOrInvoke,
7030 IsMustTail: E == MustTailCall, Loc: E->getExprLoc());
7031
7032 if (auto *CalleeDecl = dyn_cast_or_null<FunctionDecl>(Val: TargetDecl)) {
7033 if (CalleeDecl->hasAttr<RestrictAttr>() ||
7034 CalleeDecl->hasAttr<MallocSpanAttr>() ||
7035 CalleeDecl->hasAttr<AllocSizeAttr>()) {
7036 // Function has 'malloc' (aka. 'restrict') or 'alloc_size' attribute.
7037 if (SanOpts.has(K: SanitizerKind::AllocToken)) {
7038 // Set !alloc_token metadata.
7039 EmitAllocToken(CB: LocalCallOrInvoke, E);
7040 }
7041 }
7042 }
7043 if (CallOrInvoke)
7044 *CallOrInvoke = LocalCallOrInvoke;
7045
7046 return Call;
7047}
7048
7049LValue CodeGenFunction::
7050EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
7051 Address BaseAddr = Address::invalid();
7052 if (E->getOpcode() == BO_PtrMemI) {
7053 BaseAddr = EmitPointerWithAlignment(E: E->getLHS());
7054 } else {
7055 BaseAddr = EmitLValue(E: E->getLHS()).getAddress();
7056 }
7057
7058 llvm::Value *OffsetV = EmitScalarExpr(E: E->getRHS());
7059 const auto *MPT = E->getRHS()->getType()->castAs<MemberPointerType>();
7060
7061 LValueBaseInfo BaseInfo;
7062 TBAAAccessInfo TBAAInfo;
7063 bool IsInBounds = !getLangOpts().PointerOverflowDefined &&
7064 !isUnderlyingBasePointerConstantNull(E: E->getLHS());
7065 Address MemberAddr = EmitCXXMemberDataPointerAddress(
7066 E, base: BaseAddr, memberPtr: OffsetV, memberPtrType: MPT, IsInBounds, BaseInfo: &BaseInfo, TBAAInfo: &TBAAInfo);
7067
7068 return MakeAddrLValue(Addr: MemberAddr, T: MPT->getPointeeType(), BaseInfo, TBAAInfo);
7069}
7070
7071/// Given the address of a temporary variable, produce an r-value of
7072/// its type.
7073RValue CodeGenFunction::convertTempToRValue(Address addr,
7074 QualType type,
7075 SourceLocation loc) {
7076 LValue lvalue = MakeAddrLValue(Addr: addr, T: type, Source: AlignmentSource::Decl);
7077 switch (getEvaluationKind(T: type)) {
7078 case TEK_Complex:
7079 return RValue::getComplex(C: EmitLoadOfComplex(src: lvalue, loc));
7080 case TEK_Aggregate:
7081 return lvalue.asAggregateRValue();
7082 case TEK_Scalar:
7083 return RValue::get(V: EmitLoadOfScalar(lvalue, Loc: loc));
7084 }
7085 llvm_unreachable("bad evaluation kind");
7086}
7087
7088void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
7089 assert(Val->getType()->isFPOrFPVectorTy());
7090 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
7091 return;
7092
7093 llvm::MDBuilder MDHelper(getLLVMContext());
7094 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
7095
7096 cast<llvm::Instruction>(Val)->setMetadata(KindID: llvm::LLVMContext::MD_fpmath, Node);
7097}
7098
7099void CodeGenFunction::SetSqrtFPAccuracy(llvm::Value *Val) {
7100 llvm::Type *EltTy = Val->getType()->getScalarType();
7101 if (!EltTy->isFloatTy() && !EltTy->isHalfTy())
7102 return;
7103
7104 if ((getLangOpts().OpenCL &&
7105 !CGM.getCodeGenOpts().OpenCLCorrectlyRoundedDivSqrt) ||
7106 (getLangOpts().HIP && getLangOpts().CUDAIsDevice &&
7107 !CGM.getCodeGenOpts().HIPCorrectlyRoundedDivSqrt)) {
7108 // OpenCL v1.1 s7.4: minimum accuracy of single precision sqrt is 3 ulp.
7109 // OpenCL v3.0 s7.4: minimum accuracy of half precision sqrt is 1.5 ulp.
7110 //
7111 // OpenCL v1.2 s5.6.4.2: The -cl-fp32-correctly-rounded-divide-sqrt
7112 // build option allows an application to specify that single precision
7113 // floating-point divide (x/y and 1/x) and sqrt used in the program
7114 // source are correctly rounded.
7115 //
7116 // TODO: CUDA has a prec-sqrt flag
7117 SetFPAccuracy(Val, Accuracy: EltTy->isFloatTy() ? 3.0f : 1.5f);
7118 }
7119}
7120
7121void CodeGenFunction::SetDivFPAccuracy(llvm::Value *Val) {
7122 llvm::Type *EltTy = Val->getType()->getScalarType();
7123 if (!EltTy->isFloatTy() && !EltTy->isHalfTy())
7124 return;
7125
7126 if ((getLangOpts().OpenCL &&
7127 !CGM.getCodeGenOpts().OpenCLCorrectlyRoundedDivSqrt) ||
7128 (getLangOpts().HIP && getLangOpts().CUDAIsDevice &&
7129 !CGM.getCodeGenOpts().HIPCorrectlyRoundedDivSqrt)) {
7130 // OpenCL v1.1 s7.4: minimum accuracy of single precision / is 2.5 ulp.
7131 // OpenCL v3.0 s7.4: minimum accuracy of half precision / is 1 ulp.
7132 //
7133 // OpenCL v1.2 s5.6.4.2: The -cl-fp32-correctly-rounded-divide-sqrt
7134 // build option allows an application to specify that single precision
7135 // floating-point divide (x/y and 1/x) and sqrt used in the program
7136 // source are correctly rounded.
7137 //
7138 // TODO: CUDA has a prec-div flag
7139 SetFPAccuracy(Val, Accuracy: EltTy->isFloatTy() ? 2.5f : 1.f);
7140 }
7141}
7142
7143namespace {
7144 struct LValueOrRValue {
7145 LValue LV;
7146 RValue RV;
7147 };
7148}
7149
7150static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
7151 const PseudoObjectExpr *E,
7152 bool forLValue,
7153 AggValueSlot slot) {
7154 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
7155
7156 // Find the result expression, if any.
7157 const Expr *resultExpr = E->getResultExpr();
7158 LValueOrRValue result;
7159
7160 for (PseudoObjectExpr::const_semantics_iterator
7161 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
7162 const Expr *semantic = *i;
7163
7164 // If this semantic expression is an opaque value, bind it
7165 // to the result of its source expression.
7166 if (const auto *ov = dyn_cast<OpaqueValueExpr>(Val: semantic)) {
7167 // Skip unique OVEs.
7168 if (ov->isUnique()) {
7169 assert(ov != resultExpr &&
7170 "A unique OVE cannot be used as the result expression");
7171 continue;
7172 }
7173
7174 // If this is the result expression, we may need to evaluate
7175 // directly into the slot.
7176 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
7177 OVMA opaqueData;
7178 if (ov == resultExpr && ov->isPRValue() && !forLValue &&
7179 CodeGenFunction::hasAggregateEvaluationKind(T: ov->getType())) {
7180 CGF.EmitAggExpr(E: ov->getSourceExpr(), AS: slot);
7181 LValue LV = CGF.MakeAddrLValue(Addr: slot.getAddress(), T: ov->getType(),
7182 Source: AlignmentSource::Decl);
7183 opaqueData = OVMA::bind(CGF, ov, lv: LV);
7184 result.RV = slot.asRValue();
7185
7186 // Otherwise, emit as normal.
7187 } else {
7188 opaqueData = OVMA::bind(CGF, ov, e: ov->getSourceExpr());
7189
7190 // If this is the result, also evaluate the result now.
7191 if (ov == resultExpr) {
7192 if (forLValue)
7193 result.LV = CGF.EmitLValue(E: ov);
7194 else
7195 result.RV = CGF.EmitAnyExpr(E: ov, aggSlot: slot);
7196 }
7197 }
7198
7199 opaques.push_back(Elt: opaqueData);
7200
7201 // Otherwise, if the expression is the result, evaluate it
7202 // and remember the result.
7203 } else if (semantic == resultExpr) {
7204 if (forLValue)
7205 result.LV = CGF.EmitLValue(E: semantic);
7206 else
7207 result.RV = CGF.EmitAnyExpr(E: semantic, aggSlot: slot);
7208
7209 // Otherwise, evaluate the expression in an ignored context.
7210 } else {
7211 CGF.EmitIgnoredExpr(E: semantic);
7212 }
7213 }
7214
7215 // Unbind all the opaques now.
7216 for (CodeGenFunction::OpaqueValueMappingData &opaque : opaques)
7217 opaque.unbind(CGF);
7218
7219 return result;
7220}
7221
7222RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
7223 AggValueSlot slot) {
7224 return emitPseudoObjectExpr(CGF&: *this, E, forLValue: false, slot).RV;
7225}
7226
7227LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
7228 return emitPseudoObjectExpr(CGF&: *this, E, forLValue: true, slot: AggValueSlot::ignored()).LV;
7229}
7230
7231void CodeGenFunction::FlattenAccessAndTypeLValue(
7232 LValue Val, SmallVectorImpl<LValue> &AccessList) {
7233
7234 llvm::SmallVector<
7235 std::tuple<LValue, QualType, llvm::SmallVector<llvm::Value *, 4>>, 16>
7236 WorkList;
7237 llvm::IntegerType *IdxTy = llvm::IntegerType::get(C&: getLLVMContext(), NumBits: 32);
7238 WorkList.push_back(Elt: {Val, Val.getType(), {llvm::ConstantInt::get(Ty: IdxTy, V: 0)}});
7239
7240 while (!WorkList.empty()) {
7241 auto [LVal, T, IdxList] = WorkList.pop_back_val();
7242 T = T.getCanonicalType().getUnqualifiedType();
7243 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val&: T)) {
7244 uint64_t Size = CAT->getZExtSize();
7245 for (int64_t I = Size - 1; I > -1; I--) {
7246 llvm::SmallVector<llvm::Value *, 4> IdxListCopy = IdxList;
7247 IdxListCopy.push_back(Elt: llvm::ConstantInt::get(Ty: IdxTy, V: I));
7248 WorkList.emplace_back(Args&: LVal, Args: CAT->getElementType(), Args&: IdxListCopy);
7249 }
7250 } else if (const auto *RT = dyn_cast<RecordType>(Val&: T)) {
7251 const RecordDecl *Record = RT->getDecl()->getDefinitionOrSelf();
7252 assert(!Record->isUnion() && "Union types not supported in flat cast.");
7253
7254 const CXXRecordDecl *CXXD = dyn_cast<CXXRecordDecl>(Val: Record);
7255
7256 llvm::SmallVector<
7257 std::tuple<LValue, QualType, llvm::SmallVector<llvm::Value *, 4>>, 16>
7258 ReverseList;
7259 if (CXXD && CXXD->isStandardLayout())
7260 Record = CXXD->getStandardLayoutBaseWithFields();
7261
7262 // deal with potential base classes
7263 if (CXXD && !CXXD->isStandardLayout()) {
7264 if (CXXD->getNumBases() > 0) {
7265 assert(CXXD->getNumBases() == 1 &&
7266 "HLSL doesn't support multiple inheritance.");
7267 auto Base = CXXD->bases_begin();
7268 llvm::SmallVector<llvm::Value *, 4> IdxListCopy = IdxList;
7269 IdxListCopy.push_back(Elt: llvm::ConstantInt::get(
7270 Ty: IdxTy, V: 0)); // base struct should be at index zero
7271 ReverseList.emplace_back(Args&: LVal, Args: Base->getType(), Args&: IdxListCopy);
7272 }
7273 }
7274
7275 const CGRecordLayout &Layout = CGM.getTypes().getCGRecordLayout(Record);
7276
7277 llvm::Type *LLVMT = ConvertTypeForMem(T);
7278 CharUnits Align = getContext().getTypeAlignInChars(T);
7279 LValue RLValue;
7280 bool createdGEP = false;
7281 for (auto *FD : Record->fields()) {
7282 if (FD->isBitField()) {
7283 if (FD->isUnnamedBitField())
7284 continue;
7285 if (!createdGEP) {
7286 createdGEP = true;
7287 Address GEP = Builder.CreateInBoundsGEP(Addr: LVal.getAddress(), IdxList,
7288 ElementType: LLVMT, Align, Name: "gep");
7289 RLValue = MakeAddrLValue(Addr: GEP, T);
7290 }
7291 LValue FieldLVal = EmitLValueForField(base: RLValue, field: FD, IsInBounds: true);
7292 ReverseList.push_back(Elt: {FieldLVal, FD->getType(), {}});
7293 } else {
7294 llvm::SmallVector<llvm::Value *, 4> IdxListCopy = IdxList;
7295 IdxListCopy.push_back(
7296 Elt: llvm::ConstantInt::get(Ty: IdxTy, V: Layout.getLLVMFieldNo(FD)));
7297 ReverseList.emplace_back(Args&: LVal, Args: FD->getType(), Args&: IdxListCopy);
7298 }
7299 }
7300
7301 std::reverse(first: ReverseList.begin(), last: ReverseList.end());
7302 llvm::append_range(C&: WorkList, R&: ReverseList);
7303 } else if (const auto *VT = dyn_cast<VectorType>(Val&: T)) {
7304 llvm::Type *LLVMT = ConvertTypeForMem(T);
7305 CharUnits Align = getContext().getTypeAlignInChars(T);
7306 Address GEP = Builder.CreateInBoundsGEP(Addr: LVal.getAddress(), IdxList, ElementType: LLVMT,
7307 Align, Name: "vector.gep");
7308 LValue Base = MakeAddrLValue(Addr: GEP, T);
7309 for (unsigned I = 0, E = VT->getNumElements(); I < E; I++) {
7310 llvm::Constant *Idx = llvm::ConstantInt::get(Ty: IdxTy, V: I);
7311 LValue LV =
7312 LValue::MakeVectorElt(vecAddress: Base.getAddress(), Idx, type: VT->getElementType(),
7313 BaseInfo: Base.getBaseInfo(), TBAAInfo: TBAAAccessInfo());
7314 AccessList.emplace_back(Args&: LV);
7315 }
7316 } else if (const auto *MT = dyn_cast<ConstantMatrixType>(Val&: T)) {
7317 // Matrices are represented as flat arrays in memory, but has a vector
7318 // value type. So we use ConvertMatrixAddress to convert the address from
7319 // array to vector, and extract elements similar to the vector case above.
7320 // The matrix elements are iterated over in row-major order regardless of
7321 // the memory layout of the matrix.
7322 llvm::Type *LLVMT = ConvertTypeForMem(T);
7323 CharUnits Align = getContext().getTypeAlignInChars(T);
7324 Address GEP = Builder.CreateInBoundsGEP(Addr: LVal.getAddress(), IdxList, ElementType: LLVMT,
7325 Align, Name: "matrix.gep");
7326 LValue Base = MakeAddrLValue(Addr: GEP, T);
7327 Address MatAddr = MaybeConvertMatrixAddress(Addr: Base.getAddress(), CGF&: *this);
7328 unsigned NumRows = MT->getNumRows();
7329 unsigned NumCols = MT->getNumColumns();
7330 bool IsMatrixRowMajor = getLangOpts().getDefaultMatrixMemoryLayout() ==
7331 LangOptions::MatrixMemoryLayout::MatrixRowMajor;
7332 llvm::MatrixBuilder MB(Builder);
7333 for (unsigned Row = 0; Row < MT->getNumRows(); Row++) {
7334 for (unsigned Col = 0; Col < MT->getNumColumns(); Col++) {
7335 llvm::Value *RowIdx = llvm::ConstantInt::get(Ty: IdxTy, V: Row);
7336 llvm::Value *ColIdx = llvm::ConstantInt::get(Ty: IdxTy, V: Col);
7337 llvm::Value *Idx = MB.CreateIndex(RowIdx, ColumnIdx: ColIdx, NumRows, NumCols,
7338 IsMatrixRowMajor);
7339 LValue LV =
7340 LValue::MakeMatrixElt(matAddress: MatAddr, Idx, type: MT->getElementType(),
7341 BaseInfo: Base.getBaseInfo(), TBAAInfo: TBAAAccessInfo());
7342 AccessList.emplace_back(Args&: LV);
7343 }
7344 }
7345 } else { // a scalar/builtin type
7346 if (!IdxList.empty()) {
7347 llvm::Type *LLVMT = ConvertTypeForMem(T);
7348 CharUnits Align = getContext().getTypeAlignInChars(T);
7349 Address GEP = Builder.CreateInBoundsGEP(Addr: LVal.getAddress(), IdxList,
7350 ElementType: LLVMT, Align, Name: "gep");
7351 AccessList.emplace_back(Args: MakeAddrLValue(Addr: GEP, T));
7352 } else // must be a bitfield we already created an lvalue for
7353 AccessList.emplace_back(Args&: LVal);
7354 }
7355 }
7356}
7357