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