Debian Codegraph @

clang/lib/CodeGen/CGExpr.cpp

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