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