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(Base, *this);
2382
2383 llvm::Constant *CV =
2384 llvm::ConstantDataVector::get(getLLVMContext(), Indices);
2386 CV, ResultType, Base.getBaseInfo(),
2387 TBAAAccessInfo());
2388 }
2389 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
2390
2391 llvm::Constant *BaseElts = Base.getExtVectorElts();
2393
2394 for (unsigned Index : Indices)
2395 CElts.push_back(BaseElts->getAggregateElement(Index));
2396 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
2397
2399 MaybeConvertMatrixAddress(Base.getExtVectorAddress(), *this), CV,
2400 ResultType, Base.getBaseInfo(), TBAAAccessInfo());
2401}
2402
2403// Emit a store of a matrix LValue. This may require casting the original
2404// pointer to memory address (ArrayType) to a pointer to the value type
2405// (VectorType).
2406static void EmitStoreOfMatrixScalar(llvm::Value *value, LValue lvalue,
2407 bool isInit, CodeGenFunction &CGF) {
2408 Address Addr = MaybeConvertMatrixAddress(lvalue.getAddress(), CGF,
2409 value->getType()->isVectorTy());
2410 CGF.EmitStoreOfScalar(value, Addr, lvalue.isVolatile(), lvalue.getType(),
2411 lvalue.getBaseInfo(), lvalue.getTBAAInfo(), isInit,
2412 lvalue.isNontemporal());
2413}
2414
2416 bool Volatile, QualType Ty,
2417 LValueBaseInfo BaseInfo,
2418 TBAAAccessInfo TBAAInfo,
2419 bool isInit, bool isNontemporal) {
2420 if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr.getBasePointer()))
2421 if (GV->isThreadLocal())
2422 Addr = Addr.withPointer(Builder.CreateThreadLocalAddress(GV),
2424
2425 // Handles vectors of sizes that are likely to be expanded to a larger size
2426 // to optimize performance.
2427 llvm::Type *SrcTy = Value->getType();
2428 if (const auto *ClangVecTy = Ty->getAs<VectorType>()) {
2429 if (auto *VecTy = dyn_cast<llvm::FixedVectorType>(SrcTy)) {
2430 auto *NewVecTy =
2431 CGM.getABIInfo().getOptimalVectorMemoryType(VecTy, getLangOpts());
2432 if (!ClangVecTy->isPackedVectorBoolType(getContext()) &&
2433 VecTy != NewVecTy) {
2434 SmallVector<int, 16> Mask(NewVecTy->getNumElements(),
2435 VecTy->getNumElements());
2436 std::iota(Mask.begin(), Mask.begin() + VecTy->getNumElements(), 0);
2437 // Use undef instead of poison for the padding lanes, to make sure no
2438 // padding bits are poisoned, which may break coercion.
2439 Value = Builder.CreateShuffleVector(Value, llvm::UndefValue::get(VecTy),
2440 Mask, "extractVec");
2441 SrcTy = NewVecTy;
2442 }
2443 if (Addr.getElementType() != SrcTy)
2444 Addr = Addr.withElementType(SrcTy);
2445 }
2446 }
2447
2448 Value = EmitToMemory(Value, Ty);
2449
2450 LValue AtomicLValue =
2451 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
2452 if (Ty->isAtomicType() ||
2453 (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) {
2454 EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit);
2455 return;
2456 }
2457
2458 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
2460
2461 if (isNontemporal) {
2462 llvm::MDNode *Node =
2463 llvm::MDNode::get(Store->getContext(),
2464 llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
2465 Store->setMetadata(llvm::LLVMContext::MD_nontemporal, Node);
2466 }
2467
2468 CGM.DecorateInstructionWithTBAA(Store, TBAAInfo);
2469}
2470
2471void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
2472 bool isInit) {
2473 if (lvalue.getType()->isConstantMatrixType()) {
2474 EmitStoreOfMatrixScalar(value, lvalue, isInit, *this);
2475 return;
2476 }
2477
2478 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
2479 lvalue.getType(), lvalue.getBaseInfo(),
2480 lvalue.getTBAAInfo(), isInit, lvalue.isNontemporal());
2481}
2482
2483// Emit a load of a LValue of matrix type. This may require casting the pointer
2484// to memory address (ArrayType) to a pointer to the value type (VectorType).
2486 CodeGenFunction &CGF) {
2487 assert(LV.getType()->isConstantMatrixType());
2488 RawAddress DestAddr = LV.getAddress();
2489
2490 // HLSL constant buffers may pad matrix layouts, so copy elements into a
2491 // non-padded local alloca before loading.
2492 if (CGF.getLangOpts().HLSL &&
2493 LV.getType().getAddressSpace() == LangAS::hlsl_constant)
2494 DestAddr = CGF.CGM.getHLSLRuntime().createBufferMatrixTempAddress(LV, CGF);
2495
2496 Address Addr = MaybeConvertMatrixAddress(DestAddr, CGF);
2497 LV.setAddress(Addr);
2498 return RValue::get(CGF.EmitLoadOfScalar(LV, Loc));
2499}
2500
2502 SourceLocation Loc) {
2503 QualType Ty = LV.getType();
2504 switch (getEvaluationKind(Ty)) {
2505 case TEK_Scalar:
2506 return EmitLoadOfLValue(LV, Loc);
2507 case TEK_Complex:
2508 return RValue::getComplex(EmitLoadOfComplex(LV, Loc));
2509 case TEK_Aggregate:
2510 EmitAggFinalDestCopy(Ty, Slot, LV, EVK_NonRValue);
2511 return Slot.asRValue();
2512 }
2513 llvm_unreachable("bad evaluation kind");
2514}
2515
2516/// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
2517/// method emits the address of the lvalue, then loads the result as an rvalue,
2518/// returning the rvalue.
2520 // Load from __ptrauth.
2521 if (PointerAuthQualifier PtrAuth = LV.getQuals().getPointerAuth()) {
2523 llvm::Value *Value = EmitLoadOfLValue(LV, Loc).getScalarVal();
2524 return RValue::get(EmitPointerAuthUnqualify(PtrAuth, Value, LV.getType(),
2525 LV.getAddress(),
2526 /*known nonnull*/ false));
2527 }
2528
2529 if (LV.isObjCWeak()) {
2530 // load of a __weak object.
2531 Address AddrWeakObj = LV.getAddress();
2532 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
2533 AddrWeakObj));
2534 }
2536 // In MRC mode, we do a load+autorelease.
2537 if (!getLangOpts().ObjCAutoRefCount) {
2539 }
2540
2541 // In ARC mode, we load retained and then consume the value.
2542 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
2544 return RValue::get(Object);
2545 }
2546
2547 if (LV.isSimple()) {
2548 assert(!LV.getType()->isFunctionType());
2549
2550 if (LV.getType()->isConstantMatrixType())
2551 return EmitLoadOfMatrixLValue(LV, Loc, *this);
2552
2553 // Everything needs a load.
2554 return RValue::get(EmitLoadOfScalar(LV, Loc));
2555 }
2556
2557 if (LV.isVectorElt()) {
2558 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
2559 LV.isVolatileQualified());
2560 llvm::Value *Elt =
2561 Builder.CreateExtractElement(Load, LV.getVectorIdx(), "vecext");
2562 return RValue::get(EmitFromMemory(Elt, LV.getType()));
2563 }
2564
2565 // If this is a reference to a subset of the elements of a vector, either
2566 // shuffle the input or extract/insert them as appropriate.
2567 if (LV.isExtVectorElt()) {
2569 }
2570
2571 // Global Register variables always invoke intrinsics
2572 if (LV.isGlobalReg())
2573 return EmitLoadOfGlobalRegLValue(LV);
2574
2575 if (LV.isMatrixElt()) {
2576 llvm::Value *Idx = LV.getMatrixIdx();
2577 QualType EltTy = LV.getType();
2578 if (const auto *MatTy = EltTy->getAs<ConstantMatrixType>()) {
2579 EltTy = MatTy->getElementType();
2580 if (CGM.getCodeGenOpts().isOptimizedBuild()) {
2581 llvm::MatrixBuilder MB(Builder);
2582 MB.CreateIndexAssumption(Idx, MatTy->getNumElementsFlattened());
2583 }
2584 }
2585 llvm::LoadInst *Load =
2586 Builder.CreateLoad(LV.getMatrixAddress(), LV.isVolatileQualified());
2587 llvm::Value *Elt = Builder.CreateExtractElement(Load, Idx, "matrixext");
2588 return RValue::get(EmitFromMemory(Elt, EltTy));
2589 }
2590 if (LV.isMatrixRow()) {
2591 QualType MatTy = LV.getType();
2592 const ConstantMatrixType *MT = MatTy->castAs<ConstantMatrixType>();
2593
2594 unsigned NumRows = MT->getNumRows();
2595 unsigned NumCols = MT->getNumColumns();
2596 unsigned NumLanes = NumCols;
2597 llvm::Value *MatrixVec = EmitLoadOfScalar(LV, Loc);
2598 llvm::Value *Row = LV.getMatrixRowIdx();
2599 llvm::Type *ElemTy = ConvertType(MT->getElementType());
2600 llvm::Constant *ColConstsIndices = nullptr;
2601 llvm::MatrixBuilder MB(Builder);
2602
2603 if (LV.isMatrixRowSwizzle()) {
2604 ColConstsIndices = LV.getMatrixRowElts();
2605 NumLanes = llvm::cast<llvm::FixedVectorType>(ColConstsIndices->getType())
2606 ->getNumElements();
2607 }
2608
2609 llvm::Type *RowTy = llvm::FixedVectorType::get(ElemTy, NumLanes);
2610 llvm::Value *Result = llvm::PoisonValue::get(RowTy); // <NumLanes x T>
2611
2612 for (unsigned Col = 0; Col < NumLanes; ++Col) {
2613 llvm::Value *ColIdx;
2614 if (ColConstsIndices)
2615 ColIdx = ColConstsIndices->getAggregateElement(Col);
2616 else
2617 ColIdx = llvm::ConstantInt::get(Row->getType(), Col);
2618 bool IsMatrixRowMajor = isMatrixRowMajor(getLangOpts(), MatTy);
2619 llvm::Value *EltIndex =
2620 MB.CreateIndex(Row, ColIdx, NumRows, NumCols, IsMatrixRowMajor);
2621 llvm::Value *Elt = Builder.CreateExtractElement(MatrixVec, EltIndex);
2622 llvm::Value *Lane = llvm::ConstantInt::get(Builder.getInt32Ty(), Col);
2623 Result = Builder.CreateInsertElement(Result, Elt, Lane);
2624 }
2625
2626 return RValue::get(Result);
2627 }
2628
2629 assert(LV.isBitField() && "Unknown LValue type!");
2630 return EmitLoadOfBitfieldLValue(LV, Loc);
2631}
2632
2634 SourceLocation Loc) {
2635 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
2636
2637 // Get the output type.
2638 llvm::Type *ResLTy = ConvertType(LV.getType());
2639
2640 Address Ptr = LV.getBitFieldAddress();
2641 llvm::Value *Val =
2642 Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
2643
2644 bool UseVolatile = LV.isVolatileQualified() &&
2645 Info.VolatileStorageSize != 0 && isAAPCS(CGM.getTarget());
2646 const unsigned Offset = UseVolatile ? Info.VolatileOffset : Info.Offset;
2647 const unsigned StorageSize =
2648 UseVolatile ? Info.VolatileStorageSize : Info.StorageSize;
2649 if (Info.IsSigned) {
2650 assert(static_cast<unsigned>(Offset + Info.Size) <= StorageSize);
2651 unsigned HighBits = StorageSize - Offset - Info.Size;
2652 if (HighBits)
2653 Val = Builder.CreateShl(Val, HighBits, "bf.shl");
2654 if (Offset + HighBits)
2655 Val = Builder.CreateAShr(Val, Offset + HighBits, "bf.ashr");
2656 } else {
2657 if (Offset)
2658 Val = Builder.CreateLShr(Val, Offset, "bf.lshr");
2659 if (static_cast<unsigned>(Offset) + Info.Size < StorageSize)
2660 Val = Builder.CreateAnd(
2661 Val, llvm::APInt::getLowBitsSet(StorageSize, Info.Size), "bf.clear");
2662 }
2663 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
2664 EmitScalarRangeCheck(Val, LV.getType(), Loc);
2665 return RValue::get(Val);
2666}
2667
2668// If this is a reference to a subset of the elements of a vector, create an
2669// appropriate shufflevector.
2671 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
2672 LV.isVolatileQualified());
2673
2674 // HLSL allows treating scalars as one-element vectors. Converting the scalar
2675 // IR value to a vector here allows the rest of codegen to behave as normal.
2676 if (getLangOpts().HLSL && !Vec->getType()->isVectorTy()) {
2677 llvm::Type *DstTy = llvm::FixedVectorType::get(Vec->getType(), 1);
2678 llvm::Value *Zero = llvm::Constant::getNullValue(CGM.Int64Ty);
2679 Vec = Builder.CreateInsertElement(DstTy, Vec, Zero, "cast.splat");
2680 }
2681
2682 const llvm::Constant *Elts = LV.getExtVectorElts();
2683
2684 // If the result of the expression is a non-vector type, we must be extracting
2685 // a single element. Just codegen as an extractelement.
2686 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
2687 if (!ExprVT) {
2688 unsigned InIdx = getAccessedFieldNo(0, Elts);
2689 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
2690
2691 llvm::Value *Element = Builder.CreateExtractElement(Vec, Elt);
2692
2693 llvm::Type *LVTy = ConvertType(LV.getType());
2694 if (Element->getType()->getPrimitiveSizeInBits() >
2695 LVTy->getPrimitiveSizeInBits()) {
2696 if (LV.getType()->hasBooleanRepresentation() &&
2697 CGM.getCodeGenOpts().isConvertingBoolWithCmp0())
2698 Element = Builder.CreateICmpNE(
2699 Element, llvm::Constant::getNullValue(Element->getType()));
2700 else
2701 Element = Builder.CreateTrunc(Element, LVTy);
2702 }
2703
2704 return RValue::get(Element);
2705 }
2706
2707 // Always use shuffle vector to try to retain the original program structure
2708 unsigned NumResultElts = ExprVT->getNumElements();
2709
2711 for (unsigned i = 0; i != NumResultElts; ++i)
2712 Mask.push_back(getAccessedFieldNo(i, Elts));
2713
2714 Vec = Builder.CreateShuffleVector(Vec, Mask);
2715
2716 if (LV.getType()->isExtVectorBoolType()) {
2717 if (CGM.getCodeGenOpts().isConvertingBoolWithCmp0())
2718 Vec = Builder.CreateICmpNE(Vec,
2719 llvm::Constant::getNullValue(Vec->getType()));
2720 else
2721 Vec = Builder.CreateTrunc(Vec, ConvertType(LV.getType()), "truncv");
2722 }
2723
2724 return RValue::get(Vec);
2725}
2726
2727/// Generates lvalue for partial ext_vector access.
2729 Address VectorAddress = LV.getExtVectorAddress();
2730 QualType EQT = LV.getType()->castAs<VectorType>()->getElementType();
2731 llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
2732
2733 Address CastToPointerElement = VectorAddress.withElementType(VectorElementTy);
2734
2735 const llvm::Constant *Elts = LV.getExtVectorElts();
2736 unsigned ix = getAccessedFieldNo(0, Elts);
2737
2738 Address VectorBasePtrPlusIx =
2739 Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
2740 "vector.elt");
2741
2742 return VectorBasePtrPlusIx;
2743}
2744
2745/// Load of global named registers are always calls to intrinsics.
2747 assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
2748 "Bad type for register variable");
2749 llvm::MDNode *RegName = cast<llvm::MDNode>(
2750 cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
2751
2752 // We accept integer and pointer types only
2753 llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
2754 llvm::Type *Ty = OrigTy;
2755 if (OrigTy->isPointerTy())
2756 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
2757 llvm::Type *Types[] = { Ty };
2758
2759 llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
2760 llvm::Value *Call = Builder.CreateCall(
2761 F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
2762 if (OrigTy->isPointerTy())
2763 Call = Builder.CreateIntToPtr(Call, OrigTy);
2764 return RValue::get(Call);
2765}
2766
2767/// EmitStoreThroughLValue - Store the specified rvalue into the specified
2768/// lvalue, where both are guaranteed to the have the same type, and that type
2769/// is 'Ty'.
2771 bool isInit) {
2772 if (!Dst.isSimple()) {
2773 if (Dst.isVectorElt()) {
2774 if (getLangOpts().HLSL) {
2775 // HLSL allows direct access to vector elements, so storing to
2776 // individual elements of a vector through VectorElt is handled as
2777 // separate store instructions.
2778 Address DstAddr = Dst.getVectorAddress();
2779 llvm::Type *DestAddrTy = DstAddr.getElementType();
2780 llvm::Type *ElemTy = DestAddrTy->getScalarType();
2782 CGM.getDataLayout().getPrefTypeAlign(ElemTy));
2783
2784 assert(ElemTy->getScalarSizeInBits() >= 8 &&
2785 "vector element type must be at least byte-sized");
2786
2787 llvm::Value *Val = Src.getScalarVal();
2788 if (Val->getType()->getPrimitiveSizeInBits() <
2789 ElemTy->getScalarSizeInBits())
2790 Val = Builder.CreateZExt(Val, ElemTy->getScalarType());
2791
2792 llvm::Value *Idx = Dst.getVectorIdx();
2793 llvm::Value *Zero = llvm::ConstantInt::get(Int32Ty, 0);
2794 Address DstElemAddr =
2795 Builder.CreateGEP(DstAddr, {Zero, Idx}, DestAddrTy, ElemAlign);
2796 Builder.CreateStore(Val, DstElemAddr, Dst.isVolatileQualified());
2797 return;
2798 }
2799
2800 // Read/modify/write the vector, inserting the new element.
2801 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
2802 Dst.isVolatileQualified());
2803 llvm::Type *VecTy = Vec->getType();
2804 llvm::Value *SrcVal = Src.getScalarVal();
2805
2806 if (VecTy->isVectorTy() && SrcVal->getType()->getPrimitiveSizeInBits() <
2807 VecTy->getScalarSizeInBits())
2808 SrcVal = Builder.CreateZExt(SrcVal, VecTy->getScalarType());
2809
2810 auto *IRStoreTy = dyn_cast<llvm::IntegerType>(Vec->getType());
2811 if (IRStoreTy) {
2812 auto *IRVecTy = llvm::FixedVectorType::get(
2813 Builder.getInt1Ty(), IRStoreTy->getPrimitiveSizeInBits());
2814 Vec = Builder.CreateBitCast(Vec, IRVecTy);
2815 // iN --> <N x i1>.
2816 }
2817
2818 // Allow inserting `<1 x T>` into an `<N x T>`. It can happen with scalar
2819 // types which are mapped to vector LLVM IR types (e.g. for implementing
2820 // an ABI).
2821 if (auto *EltTy = dyn_cast<llvm::FixedVectorType>(SrcVal->getType());
2822 EltTy && EltTy->getNumElements() == 1)
2823 SrcVal = Builder.CreateBitCast(SrcVal, EltTy->getElementType());
2824
2825 Vec = Builder.CreateInsertElement(Vec, SrcVal, Dst.getVectorIdx(),
2826 "vecins");
2827 if (IRStoreTy) {
2828 // <N x i1> --> <iN>.
2829 Vec = Builder.CreateBitCast(Vec, IRStoreTy);
2830 }
2831
2832 auto *I = Builder.CreateStore(Vec, Dst.getVectorAddress(),
2833 Dst.isVolatileQualified());
2835 return;
2836 }
2837
2838 // If this is an update of extended vector elements, insert them as
2839 // appropriate.
2840 if (Dst.isExtVectorElt())
2842
2843 if (Dst.isGlobalReg())
2844 return EmitStoreThroughGlobalRegLValue(Src, Dst);
2845
2846 if (Dst.isMatrixElt()) {
2847 if (getLangOpts().HLSL) {
2848 // HLSL allows direct access to matrix elements, so storing to
2849 // individual elements of a matrix through MatrixElt is handled as
2850 // separate store instructions.
2851 Address DstAddr = Dst.getMatrixAddress();
2852 llvm::Type *DestAddrTy = DstAddr.getElementType();
2853 llvm::Type *ElemTy = DestAddrTy->getScalarType();
2855 CGM.getDataLayout().getPrefTypeAlign(ElemTy));
2856
2857 assert(ElemTy->getScalarSizeInBits() >= 8 &&
2858 "matrix element type must be at least byte-sized");
2859
2860 llvm::Value *Val = Src.getScalarVal();
2861 if (Val->getType()->getPrimitiveSizeInBits() <
2862 ElemTy->getScalarSizeInBits())
2863 Val = Builder.CreateZExt(Val, ElemTy->getScalarType());
2864
2865 llvm::Value *Idx = Dst.getMatrixIdx();
2866 llvm::Value *Zero = llvm::ConstantInt::get(Int32Ty, 0);
2867 Address DstElemAddr =
2868 Builder.CreateGEP(DstAddr, {Zero, Idx}, DestAddrTy, ElemAlign);
2869 Builder.CreateStore(Val, DstElemAddr, Dst.isVolatileQualified());
2870 return;
2871 }
2872
2873 llvm::Value *Idx = Dst.getMatrixIdx();
2874 if (CGM.getCodeGenOpts().isOptimizedBuild()) {
2875 const auto *const MatTy = Dst.getType()->castAs<ConstantMatrixType>();
2876 llvm::MatrixBuilder MB(Builder);
2877 MB.CreateIndexAssumption(Idx, MatTy->getNumElementsFlattened());
2878 }
2879 llvm::Instruction *Load = Builder.CreateLoad(Dst.getMatrixAddress());
2880 llvm::Value *InsertVal = Src.getScalarVal();
2881 llvm::Value *Vec =
2882 Builder.CreateInsertElement(Load, InsertVal, Idx, "matins");
2883 auto *I = Builder.CreateStore(Vec, Dst.getMatrixAddress(),
2884 Dst.isVolatileQualified());
2886 return;
2887 }
2888 if (Dst.isMatrixRow()) {
2889 // NOTE: Since there are no other languages that implement matrix single
2890 // subscripting, the logic here is specific to HLSL which allows
2891 // per-element stores to rows of matrices.
2892 assert(getLangOpts().HLSL &&
2893 "Store through matrix row LValues is only implemented for HLSL!");
2894 QualType MatTy = Dst.getType();
2895 const ConstantMatrixType *MT = MatTy->castAs<ConstantMatrixType>();
2896
2897 unsigned NumRows = MT->getNumRows();
2898 unsigned NumCols = MT->getNumColumns();
2899 unsigned NumLanes = NumCols;
2900
2901 Address DstAddr = Dst.getMatrixAddress();
2902 llvm::Type *DestAddrTy = DstAddr.getElementType();
2903 llvm::Type *ElemTy = DestAddrTy->getScalarType();
2904 CharUnits ElemAlign =
2905 CharUnits::fromQuantity(CGM.getDataLayout().getPrefTypeAlign(ElemTy));
2906
2907 assert(ElemTy->getScalarSizeInBits() >= 8 &&
2908 "matrix element type must be at least byte-sized");
2909
2910 llvm::Value *RowVal = Src.getScalarVal();
2911 if (RowVal->getType()->getScalarType()->getPrimitiveSizeInBits() <
2912 ElemTy->getScalarSizeInBits()) {
2913 auto *RowValVecTy = cast<llvm::FixedVectorType>(RowVal->getType());
2914 llvm::Type *StorageElmTy = llvm::FixedVectorType::get(
2915 ElemTy->getScalarType(), RowValVecTy->getNumElements());
2916 RowVal = Builder.CreateZExt(RowVal, StorageElmTy);
2917 }
2918
2919 llvm::MatrixBuilder MB(Builder);
2920
2921 llvm::Constant *ColConstsIndices = nullptr;
2922 if (Dst.isMatrixRowSwizzle()) {
2923 ColConstsIndices = Dst.getMatrixRowElts();
2924 NumLanes =
2925 llvm::cast<llvm::FixedVectorType>(ColConstsIndices->getType())
2926 ->getNumElements();
2927 }
2928
2929 llvm::Value *Row = Dst.getMatrixRowIdx();
2930 for (unsigned Col = 0; Col < NumLanes; ++Col) {
2931 llvm::Value *ColIdx;
2932 if (ColConstsIndices)
2933 ColIdx = ColConstsIndices->getAggregateElement(Col);
2934 else
2935 ColIdx = llvm::ConstantInt::get(Row->getType(), Col);
2936 bool IsMatrixRowMajor = isMatrixRowMajor(getLangOpts(), Dst.getType());
2937 llvm::Value *EltIndex =
2938 MB.CreateIndex(Row, ColIdx, NumRows, NumCols, IsMatrixRowMajor);
2939 llvm::Value *Lane = llvm::ConstantInt::get(Builder.getInt32Ty(), Col);
2940 llvm::Value *Zero = llvm::ConstantInt::get(Int32Ty, 0);
2941 llvm::Value *NewElt = Builder.CreateExtractElement(RowVal, Lane);
2942 Address DstElemAddr =
2943 Builder.CreateGEP(DstAddr, {Zero, EltIndex}, DestAddrTy, ElemAlign);
2944 Builder.CreateStore(NewElt, DstElemAddr, Dst.isVolatileQualified());
2945 }
2946
2947 return;
2948 }
2949
2950 assert(Dst.isBitField() && "Unknown LValue type");
2951 return EmitStoreThroughBitfieldLValue(Src, Dst);
2952 }
2953
2954 // Handle __ptrauth qualification by re-signing the value.
2955 if (PointerAuthQualifier PointerAuth = Dst.getQuals().getPointerAuth()) {
2956 Src = RValue::get(EmitPointerAuthQualify(PointerAuth, Src.getScalarVal(),
2957 Dst.getType(), Dst.getAddress(),
2958 /*known nonnull*/ false));
2959 }
2960
2961 // There's special magic for assigning into an ARC-qualified l-value.
2962 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
2963 switch (Lifetime) {
2965 llvm_unreachable("present but none");
2966
2968 // nothing special
2969 break;
2970
2972 if (isInit) {
2973 Src = RValue::get(EmitARCRetain(Dst.getType(), Src.getScalarVal()));
2974 break;
2975 }
2976 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
2977 return;
2978
2980 if (isInit)
2981 // Initialize and then skip the primitive store.
2983 else
2985 /*ignore*/ true);
2986 return;
2987
2990 Src.getScalarVal()));
2991 // fall into the normal path
2992 break;
2993 }
2994 }
2995
2996 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
2997 // load of a __weak object.
2998 Address LvalueDst = Dst.getAddress();
2999 llvm::Value *src = Src.getScalarVal();
3000 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
3001 return;
3002 }
3003
3004 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
3005 // load of a __strong object.
3006 Address LvalueDst = Dst.getAddress();
3007 llvm::Value *src = Src.getScalarVal();
3008 if (Dst.isObjCIvar()) {
3009 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
3010 llvm::Type *ResultType = IntPtrTy;
3012 llvm::Value *RHS = dst.emitRawPointer(*this);
3013 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
3014 llvm::Value *LHS = Builder.CreatePtrToInt(LvalueDst.emitRawPointer(*this),
3015 ResultType, "sub.ptr.lhs.cast");
3016 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
3017 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst, BytesBetween);
3018 } else if (Dst.isGlobalObjCRef()) {
3019 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
3020 Dst.isThreadLocalRef());
3021 }
3022 else
3023 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
3024 return;
3025 }
3026
3027 assert(Src.isScalar() && "Can't emit an agg store with this method");
3028 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
3029}
3030
3032 llvm::Value **Result) {
3033 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
3034 llvm::Type *ResLTy = convertTypeForLoadStore(Dst.getType());
3035 Address Ptr = Dst.getBitFieldAddress();
3036
3037 // Get the source value, truncated to the width of the bit-field.
3038 llvm::Value *SrcVal = Src.getScalarVal();
3039
3040 // Cast the source to the storage type and shift it into place.
3041 SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
3042 /*isSigned=*/false);
3043 llvm::Value *MaskedVal = SrcVal;
3044
3045 const bool UseVolatile =
3046 CGM.getCodeGenOpts().AAPCSBitfieldWidth && Dst.isVolatileQualified() &&
3047 Info.VolatileStorageSize != 0 && isAAPCS(CGM.getTarget());
3048 const unsigned StorageSize =
3049 UseVolatile ? Info.VolatileStorageSize : Info.StorageSize;
3050 const unsigned Offset = UseVolatile ? Info.VolatileOffset : Info.Offset;
3051 // See if there are other bits in the bitfield's storage we'll need to load
3052 // and mask together with source before storing.
3053 if (StorageSize != Info.Size) {
3054 assert(StorageSize > Info.Size && "Invalid bitfield size.");
3055 llvm::Value *Val =
3056 Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
3057
3058 // Mask the source value as needed.
3059 if (!Dst.getType()->hasBooleanRepresentation())
3060 SrcVal = Builder.CreateAnd(
3061 SrcVal, llvm::APInt::getLowBitsSet(StorageSize, Info.Size),
3062 "bf.value");
3063 MaskedVal = SrcVal;
3064 if (Offset)
3065 SrcVal = Builder.CreateShl(SrcVal, Offset, "bf.shl");
3066
3067 // Mask out the original value.
3068 Val = Builder.CreateAnd(
3069 Val, ~llvm::APInt::getBitsSet(StorageSize, Offset, Offset + Info.Size),
3070 "bf.clear");
3071
3072 // Or together the unchanged values and the source value.
3073 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
3074 } else {
3075 assert(Offset == 0);
3076 // According to the AACPS:
3077 // When a volatile bit-field is written, and its container does not overlap
3078 // with any non-bit-field member, its container must be read exactly once
3079 // and written exactly once using the access width appropriate to the type
3080 // of the container. The two accesses are not atomic.
3081 if (Dst.isVolatileQualified() && isAAPCS(CGM.getTarget()) &&
3082 CGM.getCodeGenOpts().ForceAAPCSBitfieldLoad)
3083 Builder.CreateLoad(Ptr, true, "bf.load");
3084 }
3085
3086 // Write the new value back out.
3087 auto *I = Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
3088 addInstToCurrentSourceAtom(I, SrcVal);
3089
3090 // Return the new value of the bit-field, if requested.
3091 if (Result) {
3092 llvm::Value *ResultVal = MaskedVal;
3093
3094 // Sign extend the value if needed.
3095 if (Info.IsSigned) {
3096 assert(Info.Size <= StorageSize);
3097 unsigned HighBits = StorageSize - Info.Size;
3098 if (HighBits) {
3099 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
3100 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
3101 }
3102 }
3103
3104 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
3105 "bf.result.cast");
3106 *Result = EmitFromMemory(ResultVal, Dst.getType());
3107 }
3108}
3109
3111 LValue Dst) {
3112 llvm::Value *SrcVal = Src.getScalarVal();
3113 Address DstAddr = Dst.getExtVectorAddress();
3114 const llvm::Constant *Elts = Dst.getExtVectorElts();
3115 if (DstAddr.getElementType()->getScalarSizeInBits() >
3116 SrcVal->getType()->getScalarSizeInBits())
3117 SrcVal = Builder.CreateZExt(
3118 SrcVal, convertTypeForLoadStore(Dst.getType(), SrcVal->getType()));
3119
3120 if (getLangOpts().HLSL) {
3121 llvm::Type *DestAddrTy = DstAddr.getElementType();
3122 // HLSL allows storing to scalar values through ExtVector component LValues.
3123 // To support this we need to handle the case where the destination address
3124 // is a scalar.
3125 if (!DestAddrTy->isVectorTy()) {
3126 assert(!Dst.getType()->isVectorType() &&
3127 "this should only occur for non-vector l-values");
3128 Builder.CreateStore(SrcVal, DstAddr, Dst.isVolatileQualified());
3129 return;
3130 }
3131
3132 // HLSL allows direct access to vector elements, so storing to individual
3133 // elements of a vector through ExtVector is handled as separate store
3134 // instructions.
3135 // If we are updating multiple elements, Dst and Src are vectors; for
3136 // a single element update they are scalars.
3137 const VectorType *VTy = Dst.getType()->getAs<VectorType>();
3138 unsigned NumSrcElts = VTy ? VTy->getNumElements() : 1;
3140 CGM.getDataLayout().getPrefTypeAlign(DestAddrTy->getScalarType()));
3141 llvm::Value *Zero = llvm::ConstantInt::get(Int32Ty, 0);
3142
3143 for (unsigned I = 0; I != NumSrcElts; ++I) {
3144 llvm::Value *Val = VTy ? Builder.CreateExtractElement(
3145 SrcVal, llvm::ConstantInt::get(Int32Ty, I))
3146 : SrcVal;
3147 unsigned FieldNo = getAccessedFieldNo(I, Elts);
3148 Address DstElemAddr = Address::invalid();
3149 if (FieldNo == 0)
3150 DstElemAddr = DstAddr.withAlignment(ElemAlign);
3151 else
3152 DstElemAddr = Builder.CreateGEP(
3153 DstAddr, {Zero, llvm::ConstantInt::get(Int32Ty, FieldNo)},
3154 DestAddrTy, ElemAlign);
3155 Builder.CreateStore(Val, DstElemAddr, Dst.isVolatileQualified());
3156 }
3157 return;
3158 }
3159
3160 // This access turns into a read/modify/write of the vector. Load the input
3161 // value now.
3162 llvm::Value *Vec = Builder.CreateLoad(DstAddr, Dst.isVolatileQualified());
3163 llvm::Type *VecTy = Vec->getType();
3164
3165 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
3166 unsigned NumSrcElts = VTy->getNumElements();
3167 unsigned NumDstElts = cast<llvm::FixedVectorType>(VecTy)->getNumElements();
3168 if (NumDstElts == NumSrcElts) {
3169 // Use shuffle vector is the src and destination are the same number of
3170 // elements and restore the vector mask since it is on the side it will be
3171 // stored.
3172 SmallVector<int, 4> Mask(NumDstElts);
3173 for (unsigned i = 0; i != NumSrcElts; ++i)
3174 Mask[getAccessedFieldNo(i, Elts)] = i;
3175
3176 Vec = Builder.CreateShuffleVector(SrcVal, Mask);
3177 } else if (NumDstElts > NumSrcElts) {
3178 // Extended the source vector to the same length and then shuffle it
3179 // into the destination.
3180 // FIXME: since we're shuffling with undef, can we just use the indices
3181 // into that? This could be simpler.
3182 SmallVector<int, 4> ExtMask;
3183 for (unsigned i = 0; i != NumSrcElts; ++i)
3184 ExtMask.push_back(i);
3185 ExtMask.resize(NumDstElts, -1);
3186 llvm::Value *ExtSrcVal = Builder.CreateShuffleVector(SrcVal, ExtMask);
3187 // build identity
3189 for (unsigned i = 0; i != NumDstElts; ++i)
3190 Mask.push_back(i);
3191
3192 // When the vector size is odd and .odd or .hi is used, the last element
3193 // of the Elts constant array will be one past the size of the vector.
3194 // Ignore the last element here, if it is greater than the mask size.
3195 if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
3196 NumSrcElts--;
3197
3198 // modify when what gets shuffled in
3199 for (unsigned i = 0; i != NumSrcElts; ++i)
3200 Mask[getAccessedFieldNo(i, Elts)] = i + NumDstElts;
3201 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, Mask);
3202 } else {
3203 // We should never shorten the vector
3204 llvm_unreachable("unexpected shorten vector length");
3205 }
3206 } else {
3207 // If the Src is a scalar (not a vector), and the target is a vector it must
3208 // be updating one element.
3209 unsigned InIdx = getAccessedFieldNo(0, Elts);
3210 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
3211
3212 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
3213 }
3214
3215 Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
3216 Dst.isVolatileQualified());
3217}
3218
3219/// Store of global named registers are always calls to intrinsics.
3221 assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
3222 "Bad type for register variable");
3223 llvm::MDNode *RegName = cast<llvm::MDNode>(
3224 cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
3225 assert(RegName && "Register LValue is not metadata");
3226
3227 // We accept integer and pointer types only
3228 llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
3229 llvm::Type *Ty = OrigTy;
3230 if (OrigTy->isPointerTy())
3231 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
3232 llvm::Type *Types[] = { Ty };
3233
3234 llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
3235 llvm::Value *Value = Src.getScalarVal();
3236 if (OrigTy->isPointerTy())
3237 Value = Builder.CreatePtrToInt(Value, Ty);
3238 Builder.CreateCall(
3239 F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
3240}
3241
3242// setObjCGCLValueClass - sets class of the lvalue for the purpose of
3243// generating write-barries API. It is currently a global, ivar,
3244// or neither.
3245static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
3246 LValue &LV,
3247 bool IsMemberAccess=false) {
3248 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
3249 return;
3250
3251 if (isa<ObjCIvarRefExpr>(E)) {
3252 QualType ExpTy = E->getType();
3253 if (IsMemberAccess && ExpTy->isPointerType()) {
3254 // If ivar is a structure pointer, assigning to field of
3255 // this struct follows gcc's behavior and makes it a non-ivar
3256 // writer-barrier conservatively.
3257 ExpTy = ExpTy->castAs<PointerType>()->getPointeeType();
3258 if (ExpTy->isRecordType()) {
3259 LV.setObjCIvar(false);
3260 return;
3261 }
3262 }
3263 LV.setObjCIvar(true);
3264 auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
3265 LV.setBaseIvarExp(Exp->getBase());
3266 LV.setObjCArray(E->getType()->isArrayType());
3267 return;
3268 }
3269
3270 if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
3271 if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
3272 if (VD->hasGlobalStorage()) {
3273 LV.setGlobalObjCRef(true);
3274 LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
3275 }
3276 }
3277 LV.setObjCArray(E->getType()->isArrayType());
3278 return;
3279 }
3280
3281 if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
3282 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
3283 return;
3284 }
3285
3286 if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
3287 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
3288 if (LV.isObjCIvar()) {
3289 // If cast is to a structure pointer, follow gcc's behavior and make it
3290 // a non-ivar write-barrier.
3291 QualType ExpTy = E->getType();
3292 if (ExpTy->isPointerType())
3293 ExpTy = ExpTy->castAs<PointerType>()->getPointeeType();
3294 if (ExpTy->isRecordType())
3295 LV.setObjCIvar(false);
3296 }
3297 return;
3298 }
3299
3300 if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
3301 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
3302 return;
3303 }
3304
3305 if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
3306 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
3307 return;
3308 }
3309
3310 if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
3311 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
3312 return;
3313 }
3314
3315 if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
3316 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
3317 return;
3318 }
3319
3320 if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
3321 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
3322 if (LV.isObjCIvar() && !LV.isObjCArray())
3323 // Using array syntax to assigning to what an ivar points to is not
3324 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
3325 LV.setObjCIvar(false);
3326 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
3327 // Using array syntax to assigning to what global points to is not
3328 // same as assigning to the global itself. {id *G;} G[i] = 0;
3329 LV.setGlobalObjCRef(false);
3330 return;
3331 }
3332
3333 if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
3334 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
3335 // We don't know if member is an 'ivar', but this flag is looked at
3336 // only in the context of LV.isObjCIvar().
3337 LV.setObjCArray(E->getType()->isArrayType());
3338 return;
3339 }
3340}
3341
3343 CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
3344 llvm::Type *RealVarTy, SourceLocation Loc) {
3345 if (CGF.CGM.getLangOpts().OpenMPIRBuilder)
3347 CGF, VD, Addr, Loc);
3348 else
3349 Addr =
3350 CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
3351
3352 Addr = Addr.withElementType(RealVarTy);
3354}
3355
3357 const VarDecl *VD, QualType T) {
3358 std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
3359 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
3360 // Always return an invalid address for MT_Local, and also for
3361 // MT_To/MT_Enter when unified memory is not enabled. These use direct
3362 // access (global exists in device image). Otherwise, return a valid
3363 // address.
3364 if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Local ||
3365 ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
3366 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
3368 return Address::invalid();
3369 assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
3370 ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
3371 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
3373 "Expected link clause OR to clause with unified memory enabled.");
3374 QualType PtrTy = CGF.getContext().getPointerType(VD->getType());
3376 return CGF.EmitLoadOfPointer(Addr, PtrTy->castAs<PointerType>());
3377}
3378
3379Address
3381 LValueBaseInfo *PointeeBaseInfo,
3382 TBAAAccessInfo *PointeeTBAAInfo) {
3383 llvm::LoadInst *Load =
3384 Builder.CreateLoad(RefLVal.getAddress(), RefLVal.isVolatile());
3385 CGM.DecorateInstructionWithTBAA(Load, RefLVal.getTBAAInfo());
3386 QualType PTy = RefLVal.getType()->getPointeeType();
3387 CharUnits Align = CGM.getNaturalTypeAlignment(
3388 PTy, PointeeBaseInfo, PointeeTBAAInfo, /*ForPointeeType=*/true);
3389 if (!PTy->isIncompleteType()) {
3390 llvm::LLVMContext &Ctx = getLLVMContext();
3391 llvm::MDBuilder MDB(Ctx);
3392 // Emit !nonnull metadata
3393 if (CGM.getTypes().getTargetAddressSpace(PTy) == 0 &&
3394 !CGM.getCodeGenOpts().NullPointerIsValid)
3395 Load->setMetadata(llvm::LLVMContext::MD_nonnull,
3396 llvm::MDNode::get(Ctx, {}));
3397 // Emit !align metadata
3398 if (PTy->isObjectType()) {
3399 auto AlignVal = Align.getQuantity();
3400 if (AlignVal > 1) {
3401 Load->setMetadata(
3402 llvm::LLVMContext::MD_align,
3403 llvm::MDNode::get(Ctx, MDB.createConstant(llvm::ConstantInt::get(
3404 Builder.getInt64Ty(), AlignVal))));
3405 }
3406 }
3407 }
3408 return makeNaturalAddressForPointer(Load, PTy, Align,
3409 /*ForPointeeType=*/true, PointeeBaseInfo,
3410 PointeeTBAAInfo);
3411}
3412
3414 LValueBaseInfo PointeeBaseInfo;
3415 TBAAAccessInfo PointeeTBAAInfo;
3416 Address PointeeAddr = EmitLoadOfReference(RefLVal, &PointeeBaseInfo,
3417 &PointeeTBAAInfo);
3418 return MakeAddrLValue(PointeeAddr, RefLVal.getType()->getPointeeType(),
3419 PointeeBaseInfo, PointeeTBAAInfo);
3420}
3421
3423 const PointerType *PtrTy,
3424 LValueBaseInfo *BaseInfo,
3425 TBAAAccessInfo *TBAAInfo) {
3426 llvm::Value *Addr = Builder.CreateLoad(Ptr);
3427 return makeNaturalAddressForPointer(Addr, PtrTy->getPointeeType(),
3428 CharUnits(), /*ForPointeeType=*/true,
3429 BaseInfo, TBAAInfo);
3430}
3431
3433 const PointerType *PtrTy) {
3434 LValueBaseInfo BaseInfo;
3435 TBAAAccessInfo TBAAInfo;
3436 Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &BaseInfo, &TBAAInfo);
3437 return MakeAddrLValue(Addr, PtrTy->getPointeeType(), BaseInfo, TBAAInfo);
3438}
3439
3441 const Expr *E, const VarDecl *VD) {
3442 QualType T = E->getType();
3443
3444 // If it's thread_local, emit a call to its wrapper function instead.
3445 if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
3447 return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
3448 // Check if the variable is marked as declare target with link clause in
3449 // device codegen.
3450 if (CGF.getLangOpts().OpenMPIsTargetDevice) {
3452 if (Addr.isValid())
3454 }
3455
3456 // Global HLSL resource arrays initialized on access; create a temporary with
3457 // the initialized global resource array.
3458 if (CGF.getLangOpts().HLSL && VD->getType()->isHLSLResourceRecordArray()) {
3459 std::optional<LValue> LV =
3461 if (LV.has_value())
3462 return LV.value();
3463 }
3464
3465 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
3466
3467 if (VD->getTLSKind() != VarDecl::TLS_None)
3468 V = CGF.Builder.CreateThreadLocalAddress(V);
3469
3470 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
3471 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
3472 Address Addr(V, RealVarTy, Alignment);
3473 // Emit reference to the private copy of the variable if it is an OpenMP
3474 // threadprivate variable.
3475 if (CGF.getLangOpts().OpenMP && !CGF.getLangOpts().OpenMPSimd &&
3476 VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
3477 return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
3478 E->getExprLoc());
3479 }
3480 LValue LV = VD->getType()->isReferenceType() ?
3484 setObjCGCLValueClass(CGF.getContext(), E, LV);
3485 return LV;
3486}
3487
3489 llvm::Type *Ty) {
3490 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
3491 if (FD->hasAttr<WeakRefAttr>()) {
3493 return aliasee.getPointer();
3494 }
3495
3496 llvm::Constant *V = GetAddrOfFunction(GD, Ty);
3497 return V;
3498}
3499
3500static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF, const Expr *E,
3501 GlobalDecl GD) {
3502 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
3503 llvm::Constant *V = CGF.CGM.getFunctionPointer(GD);
3504 QualType ETy = E->getType();
3506 if (auto *GV = dyn_cast<llvm::GlobalValue>(V))
3507 V = llvm::NoCFIValue::get(GV);
3508 }
3509 CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
3510 return CGF.MakeAddrLValue(V, ETy, Alignment, AlignmentSource::Decl);
3511}
3512
3514 llvm::Value *ThisValue) {
3515
3516 return CGF.EmitLValueForLambdaField(FD, ThisValue);
3517}
3518
3519/// Named Registers are named metadata pointing to the register name
3520/// which will be read from/written to as an argument to the intrinsic
3521/// @llvm.read/write_register.
3522/// So far, only the name is being passed down, but other options such as
3523/// register type, allocation type or even optimization options could be
3524/// passed down via the metadata node.
3525static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
3526 SmallString<64> Name("llvm.named.register.");
3527 AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
3528 assert(Asm->getLabel().size() < 64-Name.size() &&
3529 "Register name too big");
3530 Name.append(Asm->getLabel());
3531 llvm::NamedMDNode *M =
3532 CGM.getModule().getOrInsertNamedMetadata(Name);
3533 if (M->getNumOperands() == 0) {
3534 llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
3535 Asm->getLabel());
3536 llvm::Metadata *Ops[] = {Str};
3537 M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
3538 }
3539
3540 CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
3541
3542 llvm::Value *Ptr =
3543 llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
3544 return LValue::MakeGlobalReg(Ptr, Alignment, VD->getType());
3545}
3546
3547/// Determine whether we can emit a reference to \p VD from the current
3548/// context, despite not necessarily having seen an odr-use of the variable in
3549/// this context.
3551 const DeclRefExpr *E,
3552 const VarDecl *VD) {
3553 // For a variable declared in an enclosing scope, do not emit a spurious
3554 // reference even if we have a capture, as that will emit an unwarranted
3555 // reference to our capture state, and will likely generate worse code than
3556 // emitting a local copy.
3558 return false;
3559
3560 // For a local declaration declared in this function, we can always reference
3561 // it even if we don't have an odr-use.
3562 if (VD->hasLocalStorage()) {
3563 return VD->getDeclContext() ==
3564 dyn_cast_or_null<DeclContext>(CGF.CurCodeDecl);
3565 }
3566
3567 // For a global declaration, we can emit a reference to it if we know
3568 // for sure that we are able to emit a definition of it.
3569 VD = VD->getDefinition(CGF.getContext());
3570 if (!VD)
3571 return false;
3572
3573 // Don't emit a spurious reference if it might be to a variable that only
3574 // exists on a different device / target.
3575 // FIXME: This is unnecessarily broad. Check whether this would actually be a
3576 // cross-target reference.
3577 if (CGF.getLangOpts().OpenMP || CGF.getLangOpts().CUDA ||
3578 CGF.getLangOpts().OpenCL) {
3579 return false;
3580 }
3581
3582 // We can emit a spurious reference only if the linkage implies that we'll
3583 // be emitting a non-interposable symbol that will be retained until link
3584 // time.
3585 switch (CGF.CGM.getLLVMLinkageVarDefinition(VD)) {
3586 case llvm::GlobalValue::ExternalLinkage:
3587 case llvm::GlobalValue::LinkOnceODRLinkage:
3588 case llvm::GlobalValue::WeakODRLinkage:
3589 case llvm::GlobalValue::InternalLinkage:
3590 case llvm::GlobalValue::PrivateLinkage:
3591 return true;
3592 default:
3593 return false;
3594 }
3595}
3596
3598 const NamedDecl *ND = E->getDecl();
3599 QualType T = E->getType();
3600
3601 assert(E->isNonOdrUse() != NOUR_Unevaluated &&
3602 "should not emit an unevaluated operand");
3603
3604 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
3605 // Global Named registers access via intrinsics only
3606 if (VD->getStorageClass() == SC_Register &&
3607 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
3608 return EmitGlobalNamedRegister(VD, CGM);
3609
3610 // If this DeclRefExpr does not constitute an odr-use of the variable,
3611 // we're not permitted to emit a reference to it in general, and it might
3612 // not be captured if capture would be necessary for a use. Emit the
3613 // constant value directly instead.
3614 if (E->isNonOdrUse() == NOUR_Constant &&
3615 (VD->getType()->isReferenceType() ||
3616 !canEmitSpuriousReferenceToVariable(*this, E, VD))) {
3617 VD->getAnyInitializer(VD);
3618 llvm::Constant *Val = ConstantEmitter(*this).emitAbstract(
3619 E->getLocation(), *VD->evaluateValue(), VD->getType());
3620 assert(Val && "failed to emit constant expression");
3621
3623 if (!VD->getType()->isReferenceType()) {
3624 // Spill the constant value to a global.
3625 Addr = CGM.createUnnamedGlobalFrom(*VD, Val,
3626 getContext().getDeclAlign(VD));
3627 llvm::Type *VarTy = getTypes().ConvertTypeForMem(VD->getType());
3628 auto *PTy = llvm::PointerType::get(
3629 getLLVMContext(), getTypes().getTargetAddressSpace(VD->getType()));
3630 Addr = Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, PTy, VarTy);
3631 } else {
3632 // Should we be using the alignment of the constant pointer we emitted?
3633 CharUnits Alignment =
3634 CGM.getNaturalTypeAlignment(E->getType(),
3635 /* BaseInfo= */ nullptr,
3636 /* TBAAInfo= */ nullptr,
3637 /* forPointeeType= */ true);
3638 Addr = makeNaturalAddressForPointer(Val, T, Alignment);
3639 }
3641 }
3642
3643 // FIXME: Handle other kinds of non-odr-use DeclRefExprs.
3644
3645 // Check for captured variables.
3647 VD = VD->getCanonicalDecl();
3648 if (auto *FD = LambdaCaptureFields.lookup(VD))
3649 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
3650 if (CapturedStmtInfo) {
3651 auto I = LocalDeclMap.find(VD);
3652 if (I != LocalDeclMap.end()) {
3653 LValue CapLVal;
3654 if (VD->getType()->isReferenceType())
3655 CapLVal = EmitLoadOfReferenceLValue(I->second, VD->getType(),
3657 else
3658 CapLVal = MakeAddrLValue(I->second, T);
3659 // Mark lvalue as nontemporal if the variable is marked as nontemporal
3660 // in simd context.
3661 if (getLangOpts().OpenMP &&
3662 CGM.getOpenMPRuntime().isNontemporalDecl(VD))
3663 CapLVal.setNontemporal(/*Value=*/true);
3664 return CapLVal;
3665 }
3666 LValue CapLVal =
3667 EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
3668 CapturedStmtInfo->getContextValue());
3669 Address LValueAddress = CapLVal.getAddress();
3670 CapLVal = MakeAddrLValue(Address(LValueAddress.emitRawPointer(*this),
3671 LValueAddress.getElementType(),
3672 getContext().getDeclAlign(VD)),
3673 CapLVal.getType(),
3675 CapLVal.getTBAAInfo());
3676 // Mark lvalue as nontemporal if the variable is marked as nontemporal
3677 // in simd context.
3678 if (getLangOpts().OpenMP &&
3679 CGM.getOpenMPRuntime().isNontemporalDecl(VD))
3680 CapLVal.setNontemporal(/*Value=*/true);
3681 return CapLVal;
3682 }
3683
3684 assert(isa<BlockDecl>(CurCodeDecl));
3685 Address addr = GetAddrOfBlockDecl(VD);
3686 return MakeAddrLValue(addr, T, AlignmentSource::Decl);
3687 }
3688 }
3689
3690 // FIXME: We should be able to assert this for FunctionDecls as well!
3691 // FIXME: We should be able to assert this for all DeclRefExprs, not just
3692 // those with a valid source location.
3693 assert((ND->isUsed(false) || !isa<VarDecl>(ND) || E->isNonOdrUse() ||
3694 !E->getLocation().isValid()) &&
3695 "Should not use decl without marking it used!");
3696
3697 if (ND->hasAttr<WeakRefAttr>()) {
3698 const auto *VD = cast<ValueDecl>(ND);
3699 ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
3700 return MakeAddrLValue(Aliasee, T, AlignmentSource::Decl);
3701 }
3702
3703 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
3704 // Check if this is a global variable.
3705 if (VD->hasLinkage() || VD->isStaticDataMember())
3706 return EmitGlobalVarDeclLValue(*this, E, VD);
3707
3708 Address addr = Address::invalid();
3709
3710 // The variable should generally be present in the local decl map.
3711 auto iter = LocalDeclMap.find(VD);
3712 if (iter != LocalDeclMap.end()) {
3713 addr = iter->second;
3714
3715 // Otherwise, it might be static local we haven't emitted yet for
3716 // some reason; most likely, because it's in an outer function.
3717 } else if (VD->isStaticLocal()) {
3718 llvm::Constant *var = CGM.getOrCreateStaticVarDecl(
3719 *VD, CGM.getLLVMLinkageVarDefinition(VD));
3720 addr = Address(
3721 var, ConvertTypeForMem(VD->getType()), getContext().getDeclAlign(VD));
3722
3723 // No other cases for now.
3724 } else {
3725 llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
3726 }
3727
3728 // Handle threadlocal function locals.
3729 if (VD->getTLSKind() != VarDecl::TLS_None)
3730 addr = addr.withPointer(
3731 Builder.CreateThreadLocalAddress(addr.getBasePointer()),
3733
3734 // Check for OpenMP threadprivate variables.
3735 if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd &&
3736 VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
3738 *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
3739 E->getExprLoc());
3740 }
3741
3742 // Drill into block byref variables.
3743 bool isBlockByref = VD->isEscapingByref();
3744 if (isBlockByref) {
3745 addr = emitBlockByrefAddress(addr, VD);
3746 }
3747
3748 // Drill into reference types.
3749 LValue LV = VD->getType()->isReferenceType() ?
3752
3753 bool isLocalStorage = VD->hasLocalStorage();
3754
3755 bool NonGCable = isLocalStorage &&
3756 !VD->getType()->isReferenceType() &&
3757 !isBlockByref;
3758 if (NonGCable) {
3760 LV.setNonGC(true);
3761 }
3762
3763 bool isImpreciseLifetime =
3764 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
3765 if (isImpreciseLifetime)
3768 return LV;
3769 }
3770
3771 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
3772 return EmitFunctionDeclLValue(*this, E, FD);
3773
3774 // FIXME: While we're emitting a binding from an enclosing scope, all other
3775 // DeclRefExprs we see should be implicitly treated as if they also refer to
3776 // an enclosing scope.
3777 if (const auto *BD = dyn_cast<BindingDecl>(ND)) {
3779 auto *FD = LambdaCaptureFields.lookup(BD);
3780 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
3781 }
3782 // Suppress debug location updates when visiting the binding, since the
3783 // binding may emit instructions that would otherwise be associated with the
3784 // binding itself, rather than the expression referencing the binding. (this
3785 // leads to jumpy debug stepping behavior where the location/debugger jump
3786 // back to the binding declaration, then back to the expression referencing
3787 // the binding)
3789 return EmitLValue(BD->getBinding(), NotKnownNonNull);
3790 }
3791
3792 // We can form DeclRefExprs naming GUID declarations when reconstituting
3793 // non-type template parameters into expressions.
3794 if (const auto *GD = dyn_cast<MSGuidDecl>(ND))
3795 return MakeAddrLValue(CGM.GetAddrOfMSGuidDecl(GD), T,
3797
3798 if (const auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
3799 ConstantAddress ATPO = CGM.GetAddrOfTemplateParamObject(TPO);
3800 auto AS = getLangASFromTargetAS(ATPO.getAddressSpace());
3801
3802 if (AS != T.getAddressSpace()) {
3803 auto TargetAS = getContext().getTargetAddressSpace(T.getAddressSpace());
3804 llvm::Type *PtrTy =
3805 llvm::PointerType::get(CGM.getLLVMContext(), TargetAS);
3806 llvm::Constant *ASC = CGM.performAddrSpaceCast(ATPO.getPointer(), PtrTy);
3807 ATPO = ConstantAddress(ASC, ATPO.getElementType(), ATPO.getAlignment());
3808 }
3809
3810 return MakeAddrLValue(ATPO, T, AlignmentSource::Decl);
3811 }
3812
3813 llvm_unreachable("Unhandled DeclRefExpr");
3814}
3815
3817 // __extension__ doesn't affect lvalue-ness.
3818 if (E->getOpcode() == UO_Extension)
3819 return EmitLValue(E->getSubExpr());
3820
3822 switch (E->getOpcode()) {
3823 default: llvm_unreachable("Unknown unary operator lvalue!");
3824 case UO_Deref: {
3826 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
3827
3828 LValueBaseInfo BaseInfo;
3829 TBAAAccessInfo TBAAInfo;
3831 &TBAAInfo);
3832 LValue LV = MakeAddrLValue(Addr, T, BaseInfo, TBAAInfo);
3834
3835 // We should not generate __weak write barrier on indirect reference
3836 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
3837 // But, we continue to generate __strong write barrier on indirect write
3838 // into a pointer to object.
3839 if (getLangOpts().ObjC &&
3840 getLangOpts().getGC() != LangOptions::NonGC &&
3841 LV.isObjCWeak())
3843 return LV;
3844 }
3845 case UO_Real:
3846 case UO_Imag: {
3847 LValue LV = EmitLValue(E->getSubExpr());
3848 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
3849
3850 // __real is valid on scalars. This is a faster way of testing that.
3851 // __imag can only produce an rvalue on scalars.
3852 if (E->getOpcode() == UO_Real &&
3853 !LV.getAddress().getElementType()->isStructTy()) {
3854 assert(E->getSubExpr()->getType()->isArithmeticType());
3855 return LV;
3856 }
3857
3858 QualType T = ExprTy->castAs<ComplexType>()->getElementType();
3859
3860 Address Component =
3861 (E->getOpcode() == UO_Real
3864 LValue ElemLV = MakeAddrLValue(Component, T, LV.getBaseInfo(),
3865 CGM.getTBAAInfoForSubobject(LV, T));
3866 ElemLV.getQuals().addQualifiers(LV.getQuals());
3867 return ElemLV;
3868 }
3869 case UO_PreInc:
3870 case UO_PreDec: {
3871 LValue LV = EmitLValue(E->getSubExpr());
3872 bool isInc = E->getOpcode() == UO_PreInc;
3873
3874 if (E->getType()->isAnyComplexType())
3875 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
3876 else
3877 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
3878 return LV;
3879 }
3880 }
3881}
3882
3884 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
3886}
3887
3889 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
3891}
3892
3894 auto SL = E->getFunctionName();
3895 assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
3896 StringRef FnName = CurFn->getName();
3897 FnName.consume_front("\01");
3898 StringRef NameItems[] = {
3900 std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
3901 if (auto *BD = dyn_cast_or_null<BlockDecl>(CurCodeDecl)) {
3902 std::string Name = std::string(SL->getString());
3903 if (!Name.empty()) {
3904 unsigned Discriminator =
3905 CGM.getCXXABI().getMangleContext().getBlockId(BD, true);
3906 if (Discriminator)
3907 Name += "_" + Twine(Discriminator + 1).str();
3908 auto C = CGM.GetAddrOfConstantCString(Name, GVName);
3910 } else {
3911 auto C = CGM.GetAddrOfConstantCString(std::string(FnName), GVName);
3913 }
3914 }
3915 auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
3917}
3918
3919/// Emit a type description suitable for use by a runtime sanitizer library. The
3920/// format of a type descriptor is
3921///
3922/// \code
3923/// { i16 TypeKind, i16 TypeInfo }
3924/// \endcode
3925///
3926/// followed by an array of i8 containing the type name with extra information
3927/// for BitInt. TypeKind is TK_Integer(0) for an integer, TK_Float(1) for a
3928/// floating point value, TK_BitInt(2) for BitInt and TK_Unknown(0xFFFF) for
3929/// anything else.
3931 // Only emit each type's descriptor once.
3932 if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
3933 return C;
3934
3935 uint16_t TypeKind = TK_Unknown;
3936 uint16_t TypeInfo = 0;
3937 bool IsBitInt = false;
3938
3939 if (T->isIntegerType()) {
3940 TypeKind = TK_Integer;
3941 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
3942 (T->isSignedIntegerType() ? 1 : 0);
3943 // Follow suggestion from discussion of issue 64100.
3944 // So we can write the exact amount of bits in TypeName after '\0'
3945 // making it <diagnostic-like type name>.'\0'.<32-bit width>.
3946 if (T->isSignedIntegerType() && T->getAs<BitIntType>()) {
3947 // Do a sanity checks as we are using 32-bit type to store bit length.
3948 assert(getContext().getTypeSize(T) > 0 &&
3949 " non positive amount of bits in __BitInt type");
3950 assert(getContext().getTypeSize(T) <= 0xFFFFFFFF &&
3951 " too many bits in __BitInt type");
3952
3953 // Redefine TypeKind with the actual __BitInt type if we have signed
3954 // BitInt.
3955 TypeKind = TK_BitInt;
3956 IsBitInt = true;
3957 }
3958 } else if (T->isFloatingType()) {
3959 TypeKind = TK_Float;
3961 }
3962
3963 // Format the type name as if for a diagnostic, including quotes and
3964 // optionally an 'aka'.
3965 SmallString<32> Buffer;
3966 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
3967 (intptr_t)T.getAsOpaquePtr(), StringRef(),
3968 StringRef(), {}, Buffer, {});
3969
3970 if (IsBitInt) {
3971 // The Structure is: 0 to end the string, 32 bit unsigned integer in target
3972 // endianness, zero.
3973 char S[6] = {'\0', '\0', '\0', '\0', '\0', '\0'};
3974 const auto *EIT = T->castAs<BitIntType>();
3975 uint32_t Bits = EIT->getNumBits();
3976 llvm::support::endian::write32(S + 1, Bits,
3977 getTarget().isBigEndian()
3978 ? llvm::endianness::big
3979 : llvm::endianness::little);
3980 StringRef Str = StringRef(S, sizeof(S) / sizeof(decltype(S[0])));
3981 Buffer.append(Str);
3982 }
3983
3984 llvm::Constant *Components[] = {
3985 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
3986 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
3987 };
3988 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
3989
3990 auto *GV = new llvm::GlobalVariable(
3991 CGM.getModule(), Descriptor->getType(),
3992 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
3993 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3994 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
3995
3996 // Remember the descriptor for this type.
3997 CGM.setTypeDescriptorInMap(T, GV);
3998
3999 return GV;
4000}
4001
4002llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
4003 llvm::Type *TargetTy = IntPtrTy;
4004
4005 if (V->getType() == TargetTy)
4006 return V;
4007
4008 // Floating-point types which fit into intptr_t are bitcast to integers
4009 // and then passed directly (after zero-extension, if necessary).
4010 if (V->getType()->isFloatingPointTy()) {
4011 unsigned Bits = V->getType()->getPrimitiveSizeInBits().getFixedValue();
4012 if (Bits <= TargetTy->getIntegerBitWidth())
4013 V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
4014 Bits));
4015 }
4016
4017 // Integers which fit in intptr_t are zero-extended and passed directly.
4018 if (V->getType()->isIntegerTy() &&
4019 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
4020 return Builder.CreateZExt(V, TargetTy);
4021
4022 // Pointers are passed directly, everything else is passed by address.
4023 if (!V->getType()->isPointerTy()) {
4024 RawAddress Ptr = CreateDefaultAlignTempAlloca(V->getType());
4025 Builder.CreateStore(V, Ptr);
4026 V = Ptr.getPointer();
4027 }
4028 return Builder.CreatePtrToInt(V, TargetTy);
4029}
4030
4031/// Emit a representation of a SourceLocation for passing to a handler
4032/// in a sanitizer runtime library. The format for this data is:
4033/// \code
4034/// struct SourceLocation {
4035/// const char *Filename;
4036/// int32_t Line, Column;
4037/// };
4038/// \endcode
4039/// For an invalid SourceLocation, the Filename pointer is null.
4041 llvm::Constant *Filename;
4042 int Line, Column;
4043
4045 if (PLoc.isValid()) {
4046 StringRef FilenameString = PLoc.getFilename();
4047
4048 int PathComponentsToStrip =
4049 CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
4050 if (PathComponentsToStrip < 0) {
4051 assert(PathComponentsToStrip != INT_MIN);
4052 int PathComponentsToKeep = -PathComponentsToStrip;
4053 auto I = llvm::sys::path::rbegin(FilenameString);
4054 auto E = llvm::sys::path::rend(FilenameString);
4055 while (I != E && --PathComponentsToKeep)
4056 ++I;
4057
4058 FilenameString = FilenameString.substr(I - E);
4059 } else if (PathComponentsToStrip > 0) {
4060 auto I = llvm::sys::path::begin(FilenameString);
4061 auto E = llvm::sys::path::end(FilenameString);
4062 while (I != E && PathComponentsToStrip--)
4063 ++I;
4064
4065 if (I != E)
4066 FilenameString =
4067 FilenameString.substr(I - llvm::sys::path::begin(FilenameString));
4068 else
4069 FilenameString = llvm::sys::path::filename(FilenameString);
4070 }
4071
4072 auto FilenameGV =
4073 CGM.GetAddrOfConstantCString(std::string(FilenameString), ".src");
4074 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
4076 FilenameGV.getPointer()->stripPointerCasts()));
4077 Filename = FilenameGV.getPointer();
4078 Line = PLoc.getLine();
4079 Column = PLoc.getColumn();
4080 } else {
4081 Filename = llvm::Constant::getNullValue(Int8PtrTy);
4082 Line = Column = 0;
4083 }
4084
4085 llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
4086 Builder.getInt32(Column)};
4087
4088 return llvm::ConstantStruct::getAnon(Data);
4089}
4090
4091namespace {
4092/// Specify under what conditions this check can be recovered
4093enum class CheckRecoverableKind {
4094 /// Always terminate program execution if this check fails.
4096 /// Check supports recovering, runtime has both fatal (noreturn) and
4097 /// non-fatal handlers for this check.
4098 Recoverable,
4099 /// Runtime conditionally aborts, always need to support recovery.
4101};
4102}
4103
4104static CheckRecoverableKind
4106 if (Ordinal == SanitizerKind::SO_Vptr)
4107 return CheckRecoverableKind::AlwaysRecoverable;
4108 else if (Ordinal == SanitizerKind::SO_Return ||
4109 Ordinal == SanitizerKind::SO_Unreachable)
4110 return CheckRecoverableKind::Unrecoverable;
4111 else
4112 return CheckRecoverableKind::Recoverable;
4113}
4114
4115namespace {
4116struct SanitizerHandlerInfo {
4117 char const *const Name;
4118 unsigned Version;
4119};
4120}
4121
4122const SanitizerHandlerInfo SanitizerHandlers[] = {
4123#define SANITIZER_CHECK(Enum, Name, Version, Msg) {#Name, Version},
4125#undef SANITIZER_CHECK
4126};
4127
4129 llvm::FunctionType *FnType,
4131 SanitizerHandler CheckHandler,
4132 CheckRecoverableKind RecoverKind, bool IsFatal,
4133 llvm::BasicBlock *ContBB, bool NoMerge) {
4134 assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
4135 std::optional<ApplyDebugLocation> DL;
4136 if (!CGF.Builder.getCurrentDebugLocation()) {
4137 // Ensure that the call has at least an artificial debug location.
4138 DL.emplace(CGF, SourceLocation());
4139 }
4140 bool NeedsAbortSuffix =
4141 IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
4142 bool MinimalRuntime = CGF.CGM.getCodeGenOpts().SanitizeMinimalRuntime;
4143 bool HandlerPreserveAllRegs =
4144 CGF.CGM.getCodeGenOpts().SanitizeHandlerPreserveAllRegs;
4145 const SanitizerHandlerInfo &CheckInfo = SanitizerHandlers[CheckHandler];
4146 const StringRef CheckName = CheckInfo.Name;
4147 std::string FnName = "__ubsan_handle_" + CheckName.str();
4148 if (CheckInfo.Version && !MinimalRuntime)
4149 FnName += "_v" + llvm::utostr(CheckInfo.Version);
4150 if (MinimalRuntime)
4151 FnName += "_minimal";
4152 if (NeedsAbortSuffix)
4153 FnName += "_abort";
4154 if (HandlerPreserveAllRegs && !NeedsAbortSuffix)
4155 FnName += "_preserve";
4156 bool MayReturn =
4157 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
4158
4159 llvm::AttrBuilder B(CGF.getLLVMContext());
4160 if (!MayReturn) {
4161 B.addAttribute(llvm::Attribute::NoReturn)
4162 .addAttribute(llvm::Attribute::NoUnwind);
4163 }
4164 B.addUWTableAttr(llvm::UWTableKind::Default);
4165
4166 llvm::FunctionCallee Fn = CGF.CGM.CreateRuntimeFunction(
4167 FnType, FnName,
4168 llvm::AttributeList::get(CGF.getLLVMContext(),
4169 llvm::AttributeList::FunctionIndex, B),
4170 /*Local=*/true);
4171 llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
4172 NoMerge = NoMerge || !CGF.CGM.getCodeGenOpts().isOptimizedBuild() ||
4173 (CGF.CurCodeDecl && CGF.CurCodeDecl->hasAttr<OptimizeNoneAttr>());
4174 if (NoMerge)
4175 HandlerCall->addFnAttr(llvm::Attribute::NoMerge);
4176 if (HandlerPreserveAllRegs && !NeedsAbortSuffix) {
4177 // N.B. there is also a clang::CallingConv which is not what we want here.
4178 HandlerCall->setCallingConv(llvm::CallingConv::PreserveAll);
4179 }
4180 if (!MayReturn) {
4181 HandlerCall->setDoesNotReturn();
4182 CGF.Builder.CreateUnreachable();
4183 } else {
4184 CGF.Builder.CreateBr(ContBB);
4185 }
4186}
4187
4189 ArrayRef<std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>> Checked,
4190 SanitizerHandler CheckHandler, ArrayRef<llvm::Constant *> StaticArgs,
4191 ArrayRef<llvm::Value *> DynamicArgs, const TrapReason *TR) {
4192 assert(IsSanitizerScope);
4193 assert(Checked.size() > 0);
4194 assert(CheckHandler >= 0 &&
4195 size_t(CheckHandler) < std::size(SanitizerHandlers));
4196 const StringRef CheckName = SanitizerHandlers[CheckHandler].Name;
4197
4198 llvm::Value *FatalCond = nullptr;
4199 llvm::Value *RecoverableCond = nullptr;
4200 llvm::Value *TrapCond = nullptr;
4201 bool NoMerge = false;
4202 // Expand checks into:
4203 // (Check1 || !allow_ubsan_check) && (Check2 || !allow_ubsan_check) ...
4204 // We need separate allow_ubsan_check intrinsics because they have separately
4205 // specified cutoffs.
4206 // This expression looks expensive but will be simplified after
4207 // LowerAllowCheckPass.
4208 for (auto &[Check, Ord] : Checked) {
4209 llvm::Value *GuardedCheck = Check;
4211 (CGM.getCodeGenOpts().SanitizeSkipHotCutoffs[Ord] > 0)) {
4212 llvm::Value *Allow = Builder.CreateCall(
4213 CGM.getIntrinsic(llvm::Intrinsic::allow_ubsan_check),
4214 llvm::ConstantInt::get(CGM.Int8Ty, Ord));
4215 GuardedCheck = Builder.CreateOr(Check, Builder.CreateNot(Allow));
4216 }
4217
4218 // -fsanitize-trap= overrides -fsanitize-recover=.
4219 llvm::Value *&Cond = CGM.getCodeGenOpts().SanitizeTrap.has(Ord) ? TrapCond
4220 : CGM.getCodeGenOpts().SanitizeRecover.has(Ord)
4221 ? RecoverableCond
4222 : FatalCond;
4223 Cond = Cond ? Builder.CreateAnd(Cond, GuardedCheck) : GuardedCheck;
4224
4225 if (!CGM.getCodeGenOpts().SanitizeMergeHandlers.has(Ord))
4226 NoMerge = true;
4227 }
4228
4229 if (TrapCond)
4230 EmitTrapCheck(TrapCond, CheckHandler, NoMerge, TR);
4231 if (!FatalCond && !RecoverableCond)
4232 return;
4233
4234 llvm::Value *JointCond;
4235 if (FatalCond && RecoverableCond)
4236 JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
4237 else
4238 JointCond = FatalCond ? FatalCond : RecoverableCond;
4239 assert(JointCond);
4240
4241 CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
4242 assert(SanOpts.has(Checked[0].second));
4243#ifndef NDEBUG
4244 for (int i = 1, n = Checked.size(); i < n; ++i) {
4245 assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
4246 "All recoverable kinds in a single check must be same!");
4247 assert(SanOpts.has(Checked[i].second));
4248 }
4249#endif
4250
4251 llvm::BasicBlock *Cont = createBasicBlock("cont");
4252 llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
4253 llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
4254 // Give hint that we very much don't expect to execute the handler
4255 llvm::MDBuilder MDHelper(getLLVMContext());
4256 llvm::MDNode *Node = MDHelper.createLikelyBranchWeights();
4257 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
4258 EmitBlock(Handlers);
4259
4260 // Clear arguments for the MinimalRuntime handler.
4261 if (CGM.getCodeGenOpts().SanitizeMinimalRuntime) {
4262 StaticArgs = {};
4263 DynamicArgs = {};
4264 }
4265
4266 // Handler functions take an i8* pointing to the (handler-specific) static
4267 // information block, followed by a sequence of intptr_t arguments
4268 // representing operand values.
4271
4272 Args.reserve(DynamicArgs.size() + 1);
4273 ArgTypes.reserve(DynamicArgs.size() + 1);
4274
4275 // Emit handler arguments and create handler function type.
4276 if (!StaticArgs.empty()) {
4277 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
4278 auto *InfoPtr = new llvm::GlobalVariable(
4279 CGM.getModule(), Info->getType(),
4280 // Non-constant global is used in a handler to deduplicate reports.
4281 // TODO: change deduplication logic and make it constant.
4282 /*isConstant=*/false, llvm::GlobalVariable::PrivateLinkage, Info, "",
4283 nullptr, llvm::GlobalVariable::NotThreadLocal,
4284 CGM.getDataLayout().getDefaultGlobalsAddressSpace());
4285 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4286 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
4287 Args.push_back(InfoPtr);
4288 ArgTypes.push_back(Args.back()->getType());
4289 }
4290
4291 for (llvm::Value *DynamicArg : DynamicArgs) {
4292 Args.push_back(EmitCheckValue(DynamicArg));
4293 ArgTypes.push_back(IntPtrTy);
4294 }
4295
4296 llvm::FunctionType *FnType =
4297 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
4298
4299 if (!FatalCond || !RecoverableCond) {
4300 // Simple case: we need to generate a single handler call, either
4301 // fatal, or non-fatal.
4302 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind,
4303 (FatalCond != nullptr), Cont, NoMerge);
4304 } else {
4305 // Emit two handler calls: first one for set of unrecoverable checks,
4306 // another one for recoverable.
4307 llvm::BasicBlock *NonFatalHandlerBB =
4308 createBasicBlock("non_fatal." + CheckName);
4309 llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
4310 Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
4311 EmitBlock(FatalHandlerBB);
4312 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, true,
4313 NonFatalHandlerBB, NoMerge);
4314 EmitBlock(NonFatalHandlerBB);
4315 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, false,
4316 Cont, NoMerge);
4317 }
4318
4319 EmitBlock(Cont);
4320}
4321
4323 SanitizerKind::SanitizerOrdinal Ordinal, llvm::Value *Cond,
4324 llvm::ConstantInt *TypeId, llvm::Value *Ptr,
4325 ArrayRef<llvm::Constant *> StaticArgs) {
4326 llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
4327
4328 llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
4329 llvm::CondBrInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
4330
4331 llvm::MDBuilder MDHelper(getLLVMContext());
4332 llvm::MDNode *Node = MDHelper.createLikelyBranchWeights();
4333 BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
4334
4335 EmitBlock(CheckBB);
4336
4337 bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Ordinal);
4338
4339 llvm::CallInst *CheckCall;
4340 llvm::FunctionCallee SlowPathFn;
4341 if (WithDiag) {
4342 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
4343 auto *InfoPtr =
4344 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
4345 llvm::GlobalVariable::PrivateLinkage, Info);
4346 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4347 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
4348
4349 SlowPathFn = CGM.getModule().getOrInsertFunction(
4350 "__cfi_slowpath_diag",
4351 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
4352 false));
4353 CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr, InfoPtr});
4354 } else {
4355 SlowPathFn = CGM.getModule().getOrInsertFunction(
4356 "__cfi_slowpath",
4357 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
4358 CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
4359 }
4360
4361 CGM.setDSOLocal(
4362 cast<llvm::GlobalValue>(SlowPathFn.getCallee()->stripPointerCasts()));
4363 CheckCall->setDoesNotThrow();
4364
4365 EmitBlock(Cont);
4366}
4367
4368// Emit a stub for __cfi_check function so that the linker knows about this
4369// symbol in LTO mode.
4371 llvm::Module *M = &CGM.getModule();
4372 ASTContext &C = getContext();
4373 QualType QInt64Ty = C.getIntTypeForBitwidth(64, false);
4374
4375 auto *ArgCallsiteTypeId =
4377 auto *ArgAddr =
4379 auto *ArgCFICheckFailData =
4381 FunctionArgList FnArgs{ArgCallsiteTypeId, ArgAddr, ArgCFICheckFailData};
4382 const CGFunctionInfo &FI =
4383 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, FnArgs);
4384
4385 llvm::Function *F = llvm::Function::Create(
4386 llvm::FunctionType::get(VoidTy, {Int64Ty, VoidPtrTy, VoidPtrTy}, false),
4387 llvm::GlobalValue::WeakAnyLinkage, "__cfi_check", M);
4388 CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, F, /*IsThunk=*/false);
4389 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, F);
4390 F->setAlignment(llvm::Align(4096));
4391 CGM.setDSOLocal(F);
4392
4393 llvm::LLVMContext &Ctx = M->getContext();
4394 llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx, "entry", F);
4395 // CrossDSOCFI pass is not executed if there is no executable code.
4396 SmallVector<llvm::Value*> Args{F->getArg(2), F->getArg(1)};
4397 llvm::CallInst::Create(M->getFunction("__cfi_check_fail"), Args, "", BB);
4398 llvm::ReturnInst::Create(Ctx, nullptr, BB);
4399}
4400
4401// This function is basically a switch over the CFI failure kind, which is
4402// extracted from CFICheckFailData (1st function argument). Each case is either
4403// llvm.trap or a call to one of the two runtime handlers, based on
4404// -fsanitize-trap and -fsanitize-recover settings. Default case (invalid
4405// failure kind) traps, but this should really never happen. CFICheckFailData
4406// can be nullptr if the calling module has -fsanitize-trap behavior for this
4407// check kind; in this case __cfi_check_fail traps as well.
4409 auto CheckHandler = SanitizerHandler::CFICheckFail;
4410 // TODO: the SanitizerKind is not yet determined for this check (and might
4411 // not even be available, if Data == nullptr). However, we still want to
4412 // annotate the instrumentation. We approximate this by using all the CFI
4413 // kinds.
4414 SanitizerDebugLocation SanScope(
4415 this,
4416 {SanitizerKind::SO_CFIVCall, SanitizerKind::SO_CFINVCall,
4417 SanitizerKind::SO_CFIDerivedCast, SanitizerKind::SO_CFIUnrelatedCast,
4418 SanitizerKind::SO_CFIICall},
4419 CheckHandler);
4420 auto *ArgData = ImplicitParamDecl::Create(
4422 auto *ArgAddr = ImplicitParamDecl::Create(
4424
4425 FunctionArgList Args{ArgData, ArgAddr};
4426 const CGFunctionInfo &FI =
4427 CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args);
4428
4429 llvm::Function *F = llvm::Function::Create(
4430 llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false),
4431 llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule());
4432
4433 CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, F, /*IsThunk=*/false);
4434 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, F);
4435 F->setVisibility(llvm::GlobalValue::HiddenVisibility);
4436
4437 StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args,
4438 SourceLocation());
4439
4441
4442 // This function is not affected by NoSanitizeList. This function does
4443 // not have a source location, but "src:*" would still apply. Revert any
4444 // changes to SanOpts made in StartFunction.
4445 SanOpts = CGM.getLangOpts().Sanitize;
4446
4447 llvm::Value *Data =
4448 EmitLoadOfScalar(GetAddrOfLocalVar(ArgData), /*Volatile=*/false,
4449 CGM.getContext().VoidPtrTy, ArgData->getLocation());
4450 llvm::Value *Addr =
4451 EmitLoadOfScalar(GetAddrOfLocalVar(ArgAddr), /*Volatile=*/false,
4452 CGM.getContext().VoidPtrTy, ArgAddr->getLocation());
4453
4454 // Data == nullptr means the calling module has trap behaviour for this check.
4455 llvm::Value *DataIsNotNullPtr =
4456 Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy));
4457 // TODO: since there is no data, we don't know the CheckKind, and therefore
4458 // cannot inspect CGM.getCodeGenOpts().SanitizeMergeHandlers. We default to
4459 // NoMerge = false. Users can disable merging by disabling optimization.
4460 EmitTrapCheck(DataIsNotNullPtr, SanitizerHandler::CFICheckFail,
4461 /*NoMerge=*/false);
4462
4463 llvm::StructType *SourceLocationTy =
4464 llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty);
4465 llvm::StructType *CfiCheckFailDataTy =
4466 llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy);
4467
4468 llvm::Value *V = Builder.CreateConstGEP2_32(
4469 CfiCheckFailDataTy, Builder.CreatePointerCast(Data, DefaultPtrTy), 0, 0);
4470
4471 Address CheckKindAddr(V, Int8Ty, getIntAlign());
4472 llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr);
4473
4474 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
4475 CGM.getLLVMContext(),
4476 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
4477 llvm::Value *ValidVtable = Builder.CreateZExt(
4478 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
4479 {Addr, AllVtables}),
4480 IntPtrTy);
4481
4482 const std::pair<int, SanitizerKind::SanitizerOrdinal> CheckKinds[] = {
4483 {CFITCK_VCall, SanitizerKind::SO_CFIVCall},
4484 {CFITCK_NVCall, SanitizerKind::SO_CFINVCall},
4485 {CFITCK_DerivedCast, SanitizerKind::SO_CFIDerivedCast},
4486 {CFITCK_UnrelatedCast, SanitizerKind::SO_CFIUnrelatedCast},
4487 {CFITCK_ICall, SanitizerKind::SO_CFIICall}};
4488
4489 for (auto CheckKindOrdinalPair : CheckKinds) {
4490 int Kind = CheckKindOrdinalPair.first;
4491 SanitizerKind::SanitizerOrdinal Ordinal = CheckKindOrdinalPair.second;
4492
4493 // TODO: we could apply SanitizerAnnotateDebugInfo(Ordinal) instead of
4494 // relying on the SanitizerScope with all CFI ordinals
4495
4496 llvm::Value *Cond =
4497 Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind));
4498 if (CGM.getLangOpts().Sanitize.has(Ordinal))
4499 EmitCheck(std::make_pair(Cond, Ordinal), SanitizerHandler::CFICheckFail,
4500 {}, {Data, Addr, ValidVtable});
4501 else
4502 // TODO: we can't rely on CGM.getCodeGenOpts().SanitizeMergeHandlers.
4503 // Although the compiler allows SanitizeMergeHandlers to be set
4504 // independently of CGM.getLangOpts().Sanitize, Driver/SanitizerArgs.cpp
4505 // requires that SanitizeMergeHandlers is a subset of Sanitize.
4506 EmitTrapCheck(Cond, CheckHandler, /*NoMerge=*/false);
4507 }
4508
4510 // The only reference to this function will be created during LTO link.
4511 // Make sure it survives until then.
4512 CGM.addUsedGlobal(F);
4513}
4514
4516 if (SanOpts.has(SanitizerKind::Unreachable)) {
4517 auto CheckOrdinal = SanitizerKind::SO_Unreachable;
4518 auto CheckHandler = SanitizerHandler::BuiltinUnreachable;
4519 SanitizerDebugLocation SanScope(this, {CheckOrdinal}, CheckHandler);
4520 EmitCheck(std::make_pair(static_cast<llvm::Value *>(Builder.getFalse()),
4521 CheckOrdinal),
4522 CheckHandler, EmitCheckSourceLocation(Loc), {});
4523 }
4524 Builder.CreateUnreachable();
4525}
4526
4527void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked,
4528 SanitizerHandler CheckHandlerID,
4529 bool NoMerge, const TrapReason *TR) {
4530 llvm::BasicBlock *Cont = createBasicBlock("cont");
4531
4532 // If we're optimizing, collapse all calls to trap down to just one per
4533 // check-type per function to save on code size.
4534 if ((int)TrapBBs.size() <= CheckHandlerID)
4535 TrapBBs.resize(CheckHandlerID + 1);
4536
4537 llvm::BasicBlock *&TrapBB = TrapBBs[CheckHandlerID];
4538
4539 llvm::DILocation *TrapLocation = Builder.getCurrentDebugLocation();
4540 llvm::StringRef TrapMessage;
4541 llvm::StringRef TrapCategory;
4542 auto DebugTrapReasonKind = CGM.getCodeGenOpts().getSanitizeDebugTrapReasons();
4543 if (TR && !TR->isEmpty() &&
4544 DebugTrapReasonKind ==
4546 TrapMessage = TR->getMessage();
4547 TrapCategory = TR->getCategory();
4548 } else {
4549 TrapMessage = GetUBSanTrapForHandler(CheckHandlerID);
4550 TrapCategory = "Undefined Behavior Sanitizer";
4551 }
4552
4553 if (getDebugInfo() && !TrapMessage.empty() &&
4554 DebugTrapReasonKind !=
4556 TrapLocation) {
4557 TrapLocation = getDebugInfo()->CreateTrapFailureMessageFor(
4558 TrapLocation, TrapCategory, TrapMessage);
4559 }
4560
4561 NoMerge = NoMerge || !CGM.getCodeGenOpts().isOptimizedBuild() ||
4562 (CurCodeDecl && CurCodeDecl->hasAttr<OptimizeNoneAttr>());
4563
4564 llvm::MDBuilder MDHelper(getLLVMContext());
4565 if (TrapBB && !NoMerge) {
4566 auto Call = TrapBB->begin();
4567 assert(isa<llvm::CallInst>(Call) && "Expected call in trap BB");
4568
4569 Call->applyMergedLocation(Call->getDebugLoc(), TrapLocation);
4570
4571 Builder.CreateCondBr(Checked, Cont, TrapBB,
4572 MDHelper.createLikelyBranchWeights());
4573 } else {
4574 TrapBB = createBasicBlock("trap");
4575 Builder.CreateCondBr(Checked, Cont, TrapBB,
4576 MDHelper.createLikelyBranchWeights());
4577 EmitBlock(TrapBB);
4578
4579 ApplyDebugLocation applyTrapDI(*this, TrapLocation);
4580
4581 llvm::CallInst *TrapCall;
4582 if (CGM.getCodeGenOpts().SanitizeTrapLoop)
4583 TrapCall =
4584 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::looptrap));
4585 else
4586 TrapCall = Builder.CreateCall(
4587 CGM.getIntrinsic(llvm::Intrinsic::ubsantrap),
4588 llvm::ConstantInt::get(CGM.Int8Ty, CheckHandlerID));
4589
4590 if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
4591 auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
4592 CGM.getCodeGenOpts().TrapFuncName);
4593 TrapCall->addFnAttr(A);
4594 }
4595 if (NoMerge)
4596 TrapCall->addFnAttr(llvm::Attribute::NoMerge);
4597 TrapCall->setDoesNotReturn();
4598 TrapCall->setDoesNotThrow();
4599 Builder.CreateUnreachable();
4600 }
4601
4602 EmitBlock(Cont);
4603}
4604
4605llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
4606 llvm::CallInst *TrapCall =
4607 Builder.CreateCall(CGM.getIntrinsic(IntrID));
4608
4609 if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
4610 auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
4611 CGM.getCodeGenOpts().TrapFuncName);
4612 TrapCall->addFnAttr(A);
4613 }
4614
4616 TrapCall->addFnAttr(llvm::Attribute::NoMerge);
4617 return TrapCall;
4618}
4619
4621 LValueBaseInfo *BaseInfo,
4622 TBAAAccessInfo *TBAAInfo) {
4623 assert(E->getType()->isArrayType() &&
4624 "Array to pointer decay must have array source type!");
4625
4626 // Expressions of array type can't be bitfields or vector elements.
4627 LValue LV = EmitLValue(E);
4628 Address Addr = LV.getAddress();
4629
4630 // If the array type was an incomplete type, we need to make sure
4631 // the decay ends up being the right type.
4632 llvm::Type *NewTy = ConvertType(E->getType());
4633 Addr = Addr.withElementType(NewTy);
4634
4635 // Note that VLA pointers are always decayed, so we don't need to do
4636 // anything here.
4637 if (!E->getType()->isVariableArrayType()) {
4638 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
4639 "Expected pointer to array");
4640
4641 if (getLangOpts().EmitLogicalPointer) {
4642 // Array-to-pointer decay for an SGEP is a no-op as we don't do any
4643 // logical indexing. See #179951 for some additional context.
4644 auto *SGEP =
4645 Builder.CreateStructuredGEP(NewTy, Addr.emitRawPointer(*this), {});
4646 Addr = Address(SGEP, NewTy, Addr.getAlignment(), Addr.isKnownNonNull());
4647 } else {
4648 Addr = Builder.CreateConstArrayGEP(Addr, 0, "arraydecay");
4649 }
4650 }
4651
4652 // The result of this decay conversion points to an array element within the
4653 // base lvalue. However, since TBAA currently does not support representing
4654 // accesses to elements of member arrays, we conservatively represent accesses
4655 // to the pointee object as if it had no any base lvalue specified.
4656 // TODO: Support TBAA for member arrays.
4658 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
4659 if (TBAAInfo) *TBAAInfo = CGM.getTBAAAccessInfo(EltType);
4660
4661 return Addr.withElementType(ConvertTypeForMem(EltType));
4662}
4663
4664/// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
4665/// array to pointer, return the array subexpression.
4666static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
4667 // If this isn't just an array->pointer decay, bail out.
4668 const auto *CE = dyn_cast<CastExpr>(E);
4669 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
4670 return nullptr;
4671
4672 // If this is a decay from variable width array, bail out.
4673 const Expr *SubExpr = CE->getSubExpr();
4674 if (SubExpr->getType()->isVariableArrayType())
4675 return nullptr;
4676
4677 return SubExpr;
4678}
4679
4681 llvm::Type *elemType,
4682 llvm::Value *ptr,
4683 ArrayRef<llvm::Value*> indices,
4684 bool inbounds,
4685 bool signedIndices,
4686 SourceLocation loc,
4687 const llvm::Twine &name = "arrayidx") {
4688 if (inbounds && CGF.getLangOpts().EmitLogicalPointer)
4689 return CGF.Builder.CreateStructuredGEP(elemType, ptr, indices);
4690
4691 if (inbounds) {
4692 return CGF.EmitCheckedInBoundsGEP(elemType, ptr, indices, signedIndices,
4694 name);
4695 } else {
4696 return CGF.Builder.CreateGEP(elemType, ptr, indices, name);
4697 }
4698}
4699
4702 llvm::Type *arrayType,
4703 llvm::Type *elementType, bool inbounds,
4704 bool signedIndices, SourceLocation loc,
4705 CharUnits align,
4706 const llvm::Twine &name = "arrayidx") {
4707 if (inbounds && CGF.getLangOpts().EmitLogicalPointer)
4708 return RawAddress(CGF.Builder.CreateStructuredGEP(arrayType,
4709 addr.emitRawPointer(CGF),
4710 indices.drop_front()),
4711 elementType, align);
4712
4713 if (inbounds) {
4714 return CGF.EmitCheckedInBoundsGEP(addr, indices, elementType, signedIndices,
4716 align, name);
4717 } else {
4718 return CGF.Builder.CreateGEP(addr, indices, elementType, align, name);
4719 }
4720}
4721
4723 const VariableArrayType *vla) {
4724 QualType eltType;
4725 do {
4726 eltType = vla->getElementType();
4727 } while ((vla = ctx.getAsVariableArrayType(eltType)));
4728 return eltType;
4729}
4730
4732 return D && D->hasAttr<BPFPreserveStaticOffsetAttr>();
4733}
4734
4735static bool hasBPFPreserveStaticOffset(const Expr *E) {
4736 if (!E)
4737 return false;
4738 QualType PointeeType = E->getType()->getPointeeType();
4739 if (PointeeType.isNull())
4740 return false;
4741 if (const auto *BaseDecl = PointeeType->getAsRecordDecl())
4742 return hasBPFPreserveStaticOffset(BaseDecl);
4743 return false;
4744}
4745
4746// Wraps Addr with a call to llvm.preserve.static.offset intrinsic.
4748 Address &Addr) {
4749 if (!CGF.getTarget().getTriple().isBPF())
4750 return Addr;
4751
4752 llvm::Function *Fn =
4753 CGF.CGM.getIntrinsic(llvm::Intrinsic::preserve_static_offset);
4754 llvm::CallInst *Call = CGF.Builder.CreateCall(Fn, {Addr.emitRawPointer(CGF)});
4755 return Address(Call, Addr.getElementType(), Addr.getAlignment());
4756}
4757
4758/// Given an array base, check whether its member access belongs to a record
4759/// with preserve_access_index attribute or not.
4760static bool IsPreserveAIArrayBase(CodeGenFunction &CGF, const Expr *ArrayBase) {
4761 if (!ArrayBase || !CGF.getDebugInfo())
4762 return false;
4763
4764 // Only support base as either a MemberExpr or DeclRefExpr.
4765 // DeclRefExpr to cover cases like:
4766 // struct s { int a; int b[10]; };
4767 // struct s *p;
4768 // p[1].a
4769 // p[1] will generate a DeclRefExpr and p[1].a is a MemberExpr.
4770 // p->b[5] is a MemberExpr example.
4771 const Expr *E = ArrayBase->IgnoreImpCasts();
4772 if (const auto *ME = dyn_cast<MemberExpr>(E))
4773 return ME->getMemberDecl()->hasAttr<BPFPreserveAccessIndexAttr>();
4774
4775 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
4776 const auto *VarDef = dyn_cast<VarDecl>(DRE->getDecl());
4777 if (!VarDef)
4778 return false;
4779
4780 const auto *PtrT = VarDef->getType()->getAs<PointerType>();
4781 if (!PtrT)
4782 return false;
4783
4784 const auto *PointeeT = PtrT->getPointeeType()
4786 if (const auto *RecT = dyn_cast<RecordType>(PointeeT))
4787 return RecT->getDecl()
4788 ->getMostRecentDecl()
4789 ->hasAttr<BPFPreserveAccessIndexAttr>();
4790 return false;
4791 }
4792
4793 return false;
4794}
4795
4798 QualType eltType, bool inbounds,
4799 bool signedIndices, SourceLocation loc,
4800 QualType *arrayType = nullptr,
4801 const Expr *Base = nullptr,
4802 const llvm::Twine &name = "arrayidx") {
4803 // All the indices except that last must be zero.
4804#ifndef NDEBUG
4805 for (auto *idx : indices.drop_back())
4806 assert(isa<llvm::ConstantInt>(idx) &&
4807 cast<llvm::ConstantInt>(idx)->isZero());
4808#endif
4809
4810 // Determine the element size of the statically-sized base. This is
4811 // the thing that the indices are expressed in terms of.
4812 if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
4813 eltType = getFixedSizeElementType(CGF.getContext(), vla);
4814 }
4815
4816 // We can use that to compute the best alignment of the element.
4817 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
4818 CharUnits eltAlign =
4819 getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
4820
4822 addr = wrapWithBPFPreserveStaticOffset(CGF, addr);
4823
4824 llvm::Value *eltPtr;
4825 auto LastIndex = dyn_cast<llvm::ConstantInt>(indices.back());
4826 if (!LastIndex ||
4828 addr = emitArraySubscriptGEP(CGF, addr, indices,
4830 : nullptr,
4831 CGF.ConvertTypeForMem(eltType), inbounds,
4832 signedIndices, loc, eltAlign, name);
4833 return addr;
4834 } else {
4835 // Remember the original array subscript for bpf target
4836 unsigned idx = LastIndex->getZExtValue();
4837 llvm::DIType *DbgInfo = nullptr;
4838 if (arrayType)
4839 DbgInfo = CGF.getDebugInfo()->getOrCreateStandaloneType(*arrayType, loc);
4840 eltPtr = CGF.Builder.CreatePreserveArrayAccessIndex(
4841 addr.getElementType(), addr.emitRawPointer(CGF), indices.size() - 1,
4842 idx, DbgInfo);
4843 }
4844
4845 return Address(eltPtr, CGF.ConvertTypeForMem(eltType), eltAlign);
4846}
4847
4848namespace {
4849
4850/// StructFieldAccess is a simple visitor class to grab the first l-value to
4851/// r-value cast Expr.
4852struct StructFieldAccess
4853 : public ConstStmtVisitor<StructFieldAccess, const Expr *> {
4854 const Expr *VisitCastExpr(const CastExpr *E) {
4855 if (E->getCastKind() == CK_LValueToRValue)
4856 return E;
4857 return Visit(E->getSubExpr());
4858 }
4859 const Expr *VisitParenExpr(const ParenExpr *E) {
4860 return Visit(E->getSubExpr());
4861 }
4862};
4863
4864} // end anonymous namespace
4865
4866/// The offset of a field from the beginning of the record.
4868 const FieldDecl *Field, int64_t &Offset) {
4869 ASTContext &Ctx = CGF.getContext();
4870 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(RD);
4871 unsigned FieldNo = 0;
4872
4873 for (const FieldDecl *FD : RD->fields()) {
4874 if (FD == Field) {
4875 Offset += Layout.getFieldOffset(FieldNo);
4876 return true;
4877 }
4878
4879 QualType Ty = FD->getType();
4880 if (Ty->isRecordType())
4881 if (getFieldOffsetInBits(CGF, Ty->getAsRecordDecl(), Field, Offset)) {
4882 Offset += Layout.getFieldOffset(FieldNo);
4883 return true;
4884 }
4885
4886 if (!RD->isUnion())
4887 ++FieldNo;
4888 }
4889
4890 return false;
4891}
4892
4893/// Returns the relative offset difference between \p FD1 and \p FD2.
4894/// \code
4895/// offsetof(struct foo, FD1) - offsetof(struct foo, FD2)
4896/// \endcode
4897/// Both fields must be within the same struct.
4898static std::optional<int64_t> getOffsetDifferenceInBits(CodeGenFunction &CGF,
4899 const FieldDecl *FD1,
4900 const FieldDecl *FD2) {
4901 const RecordDecl *FD1OuterRec =
4903 const RecordDecl *FD2OuterRec =
4905
4906 if (FD1OuterRec != FD2OuterRec)
4907 // Fields must be within the same RecordDecl.
4908 return std::optional<int64_t>();
4909
4910 int64_t FD1Offset = 0;
4911 if (!getFieldOffsetInBits(CGF, FD1OuterRec, FD1, FD1Offset))
4912 return std::optional<int64_t>();
4913
4914 int64_t FD2Offset = 0;
4915 if (!getFieldOffsetInBits(CGF, FD2OuterRec, FD2, FD2Offset))
4916 return std::optional<int64_t>();
4917
4918 return std::make_optional<int64_t>(FD1Offset - FD2Offset);
4919}
4920
4921/// EmitCountedByBoundsChecking - If the array being accessed has a "counted_by"
4922/// attribute, generate bounds checking code. The "count" field is at the top
4923/// level of the struct or in an anonymous struct, that's also at the top level.
4924/// Future expansions may allow the "count" to reside at any place in the
4925/// struct, but the value of "counted_by" will be a "simple" path to the count,
4926/// i.e. "a.b.count", so we shouldn't need the full force of EmitLValue or
4927/// similar to emit the correct GEP.
4929 const Expr *ArrayExpr, QualType ArrayType, Address ArrayInst,
4930 QualType IndexType, llvm::Value *IndexVal, bool Accessed,
4931 bool FlexibleArray) {
4932 const auto *ME = dyn_cast<MemberExpr>(ArrayExpr->IgnoreImpCasts());
4933 if (!ME || !ME->getMemberDecl()->getType()->isCountAttributedType())
4934 return;
4935
4936 const LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
4937 getLangOpts().getStrictFlexArraysLevel();
4938 if (FlexibleArray &&
4939 !ME->isFlexibleArrayMemberLike(getContext(), StrictFlexArraysLevel))
4940 return;
4941
4942 const FieldDecl *FD = cast<FieldDecl>(ME->getMemberDecl());
4943 const FieldDecl *CountFD = FD->findCountedByField();
4944 if (!CountFD)
4945 return;
4946
4947 if (std::optional<int64_t> Diff =
4948 getOffsetDifferenceInBits(*this, CountFD, FD)) {
4949 if (!ArrayInst.isValid()) {
4950 // An invalid Address indicates we're checking a pointer array access.
4951 // Emit the checked L-Value here.
4952 LValue LV = EmitCheckedLValue(ArrayExpr, TCK_MemberAccess);
4953 ArrayInst = LV.getAddress();
4954 }
4955
4956 // FIXME: The 'static_cast' is necessary, otherwise the result turns into a
4957 // uint64_t, which messes things up if we have a negative offset difference.
4958 Diff = *Diff / static_cast<int64_t>(CGM.getContext().getCharWidth());
4959
4960 // Create a GEP with the byte offset between the counted object and the
4961 // count and use that to load the count value.
4962 ArrayInst = Builder.CreatePointerBitCastOrAddrSpaceCast(ArrayInst,
4963 Int8PtrTy, Int8Ty);
4964
4965 llvm::Type *BoundsType = ConvertType(CountFD->getType());
4966 llvm::Value *BoundsVal =
4967 Builder.CreateInBoundsGEP(Int8Ty, ArrayInst.emitRawPointer(*this),
4968 Builder.getInt32(*Diff), ".counted_by.gep");
4969 BoundsVal = Builder.CreateAlignedLoad(BoundsType, BoundsVal, getIntAlign(),
4970 ".counted_by.load");
4971
4972 // Now emit the bounds checking.
4973 EmitBoundsCheckImpl(ArrayExpr, ArrayType, IndexVal, IndexType, BoundsVal,
4974 CountFD->getType(), Accessed);
4975 }
4976}
4977
4979 bool Accessed) {
4980 // The index must always be an integer, which is not an aggregate. Emit it
4981 // in lexical order (this complexity is, sadly, required by C++17).
4982 llvm::Value *IdxPre =
4983 (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E->getIdx()) : nullptr;
4984 bool SignedIndices = false;
4985 auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * {
4986 auto *Idx = IdxPre;
4987 if (E->getLHS() != E->getIdx()) {
4988 assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS");
4989 Idx = EmitScalarExpr(E->getIdx());
4990 }
4991
4992 QualType IdxTy = E->getIdx()->getType();
4993 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
4994 SignedIndices |= IdxSigned;
4995
4996 if (SanOpts.has(SanitizerKind::ArrayBounds))
4997 EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
4998
4999 // Extend or truncate the index type to 32 or 64-bits.
5000 if (Promote && Idx->getType() != IntPtrTy)
5001 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
5002
5003 return Idx;
5004 };
5005 IdxPre = nullptr;
5006
5007 // If the base is a vector type, then we are forming a vector element lvalue
5008 // with this subscript.
5009 if (E->getBase()->getType()->isSubscriptableVectorType() &&
5011 // Emit the vector as an lvalue to get its address.
5012 LValue LHS = EmitLValue(E->getBase());
5013 auto *Idx = EmitIdxAfterBase(/*Promote*/false);
5014 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
5015 return LValue::MakeVectorElt(LHS.getAddress(), Idx, E->getBase()->getType(),
5016 LHS.getBaseInfo(), TBAAAccessInfo());
5017 }
5018
5019 // The HLSL runtime handles subscript expressions on global resource arrays
5020 // and objects with HLSL buffer layouts.
5021 if (getLangOpts().HLSL) {
5022 std::optional<LValue> LV;
5023 if (E->getType()->isHLSLResourceRecord() ||
5025 LV = CGM.getHLSLRuntime().emitResourceArraySubscriptExpr(E, *this);
5026 } else if (E->getType().getAddressSpace() == LangAS::hlsl_constant) {
5027 LV = CGM.getHLSLRuntime().emitBufferArraySubscriptExpr(E, *this,
5028 EmitIdxAfterBase);
5029 }
5030 if (LV.has_value())
5031 return *LV;
5032 }
5033
5034 // All the other cases basically behave like simple offsetting.
5035
5036 // Handle the extvector case we ignored above.
5038 LValue LV = EmitLValue(E->getBase());
5039 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
5041
5042 QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
5043 Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true,
5044 SignedIndices, E->getExprLoc());
5045 return MakeAddrLValue(Addr, EltType, LV.getBaseInfo(),
5046 CGM.getTBAAInfoForSubobject(LV, EltType));
5047 }
5048
5049 LValueBaseInfo EltBaseInfo;
5050 TBAAAccessInfo EltTBAAInfo;
5052 if (const VariableArrayType *vla =
5053 getContext().getAsVariableArrayType(E->getType())) {
5054 // The base must be a pointer, which is not an aggregate. Emit
5055 // it. It needs to be emitted first in case it's what captures
5056 // the VLA bounds.
5057 Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
5058 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
5059
5060 // The element count here is the total number of non-VLA elements.
5061 llvm::Value *numElements = getVLASize(vla).NumElts;
5062
5063 // Effectively, the multiply by the VLA size is part of the GEP.
5064 // GEP indexes are signed, and scaling an index isn't permitted to
5065 // signed-overflow, so we use the same semantics for our explicit
5066 // multiply. We suppress this if overflow is not undefined behavior.
5067 if (getLangOpts().PointerOverflowDefined) {
5068 Idx = Builder.CreateMul(Idx, numElements);
5069 } else {
5070 Idx = Builder.CreateNSWMul(Idx, numElements);
5071 }
5072
5073 Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
5074 !getLangOpts().PointerOverflowDefined,
5075 SignedIndices, E->getExprLoc());
5076
5077 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
5078 // Indexing over an interface, as in "NSString *P; P[4];"
5079
5080 // Emit the base pointer.
5081 Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
5082 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
5083
5084 CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
5085 llvm::Value *InterfaceSizeVal =
5086 llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());
5087
5088 llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
5089
5090 // We don't necessarily build correct LLVM struct types for ObjC
5091 // interfaces, so we can't rely on GEP to do this scaling
5092 // correctly, so we need to cast to i8*. FIXME: is this actually
5093 // true? A lot of other things in the fragile ABI would break...
5094 llvm::Type *OrigBaseElemTy = Addr.getElementType();
5095
5096 // Do the GEP.
5097 CharUnits EltAlign =
5098 getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
5099 llvm::Value *EltPtr =
5100 emitArraySubscriptGEP(*this, Int8Ty, Addr.emitRawPointer(*this),
5101 ScaledIdx, false, SignedIndices, E->getExprLoc());
5102 Addr = Address(EltPtr, OrigBaseElemTy, EltAlign);
5103 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
5104 // If this is A[i] where A is an array, the frontend will have decayed the
5105 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
5106 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
5107 // "gep x, i" here. Emit one "gep A, 0, i".
5108 assert(Array->getType()->isArrayType() &&
5109 "Array to pointer decay must have array source type!");
5110 LValue ArrayLV;
5111 // For simple multidimensional array indexing, set the 'accessed' flag for
5112 // better bounds-checking of the base expression.
5113 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
5114 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
5115 else
5116 ArrayLV = EmitLValue(Array);
5117 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
5118
5119 if (SanOpts.has(SanitizerKind::ArrayBounds))
5120 EmitCountedByBoundsChecking(Array, Array->getType(), ArrayLV.getAddress(),
5121 E->getIdx()->getType(), Idx, Accessed,
5122 /*FlexibleArray=*/true);
5123
5124 // Propagate the alignment from the array itself to the result.
5125 QualType arrayType = Array->getType();
5127 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
5128 E->getType(), !getLangOpts().PointerOverflowDefined, SignedIndices,
5129 E->getExprLoc(), &arrayType, E->getBase());
5130 EltBaseInfo = ArrayLV.getBaseInfo();
5131 if (!CGM.getCodeGenOpts().NewStructPathTBAA) {
5132 // Since CodeGenTBAA::getTypeInfoHelper only handles array types for
5133 // new struct path TBAA, we must a use a plain access.
5134 EltTBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, E->getType());
5135 } else if (ArrayLV.getTBAAInfo().isMayAlias()) {
5136 EltTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
5137 } else if (ArrayLV.getTBAAInfo().isIncomplete()) {
5138 // The array element is complete, even if the array is not.
5139 EltTBAAInfo = CGM.getTBAAAccessInfo(E->getType());
5140 } else {
5141 // The TBAA access info from the array (base) lvalue is ordinary. We will
5142 // adapt it to create access info for the element.
5143 EltTBAAInfo = ArrayLV.getTBAAInfo();
5144
5145 // We retain the TBAA struct path (BaseType and Offset members) from the
5146 // array. In the TBAA representation, we map any array access to the
5147 // element at index 0, as the index is generally a runtime value. This
5148 // element has the same offset in the base type as the array itself.
5149 // If the array lvalue had no base type, there is no point trying to
5150 // generate one, since an array itself is not a valid base type.
5151
5152 // We also retain the access type from the base lvalue, but the access
5153 // size must be updated to the size of an individual element.
5154 EltTBAAInfo.Size =
5156 }
5157 } else {
5158 // The base must be a pointer; emit it with an estimate of its alignment.
5159 Address BaseAddr =
5160 EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
5161 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
5162 QualType ptrType = E->getBase()->getType();
5163 Addr = emitArraySubscriptGEP(*this, BaseAddr, Idx, E->getType(),
5164 !getLangOpts().PointerOverflowDefined,
5165 SignedIndices, E->getExprLoc(), &ptrType,
5166 E->getBase());
5167
5168 if (SanOpts.has(SanitizerKind::ArrayBounds)) {
5169 StructFieldAccess Visitor;
5170 const Expr *Base = Visitor.Visit(E->getBase());
5171
5172 if (const auto *CE = dyn_cast_if_present<CastExpr>(Base);
5173 CE && CE->getCastKind() == CK_LValueToRValue)
5175 E->getIdx()->getType(), Idx, Accessed,
5176 /*FlexibleArray=*/false);
5177 }
5178 }
5179
5180 LValue LV = MakeAddrLValue(Addr, E->getType(), EltBaseInfo, EltTBAAInfo);
5181
5182 if (getLangOpts().ObjC &&
5183 getLangOpts().getGC() != LangOptions::NonGC) {
5186 }
5187 return LV;
5188}
5189
5191 llvm::Value *Idx = EmitScalarExpr(E);
5192 if (Idx->getType() == IntPtrTy)
5193 return Idx;
5194 bool IsSigned = E->getType()->isSignedIntegerOrEnumerationType();
5195 return Builder.CreateIntCast(Idx, IntPtrTy, IsSigned);
5196}
5197
5199 const MatrixSingleSubscriptExpr *E) {
5200 LValue Base = EmitLValue(E->getBase());
5201 llvm::Value *RowIdx = EmitMatrixIndexExpr(E->getRowIdx());
5202
5203 RawAddress MatAddr = Base.getAddress();
5204 if (getLangOpts().HLSL &&
5206 MatAddr = CGM.getHLSLRuntime().createBufferMatrixTempAddress(Base, *this);
5207
5208 return LValue::MakeMatrixRow(MaybeConvertMatrixAddress(MatAddr, *this),
5209 RowIdx, E->getBase()->getType(),
5210 Base.getBaseInfo(), TBAAAccessInfo());
5211}
5212
5214 assert(
5215 !E->isIncomplete() &&
5216 "incomplete matrix subscript expressions should be rejected during Sema");
5217 LValue Base = EmitLValue(E->getBase());
5218
5219 // Extend or truncate the index type to 32 or 64-bits if needed.
5220 llvm::Value *RowIdx = EmitMatrixIndexExpr(E->getRowIdx());
5221 llvm::Value *ColIdx = EmitMatrixIndexExpr(E->getColumnIdx());
5222 llvm::MatrixBuilder MB(Builder);
5223 const auto *MatrixTy = E->getBase()->getType()->castAs<ConstantMatrixType>();
5224 unsigned NumCols = MatrixTy->getNumColumns();
5225 unsigned NumRows = MatrixTy->getNumRows();
5226 bool IsMatrixRowMajor =
5228 llvm::Value *FinalIdx =
5229 MB.CreateIndex(RowIdx, ColIdx, NumRows, NumCols, IsMatrixRowMajor);
5230
5231 return LValue::MakeMatrixElt(
5232 MaybeConvertMatrixAddress(Base.getAddress(), *this), FinalIdx,
5233 E->getBase()->getType(), Base.getBaseInfo(), TBAAAccessInfo());
5234}
5235
5237 LValueBaseInfo &BaseInfo,
5238 TBAAAccessInfo &TBAAInfo,
5239 QualType BaseTy, QualType ElTy,
5240 bool IsLowerBound) {
5241 LValue BaseLVal;
5242 if (auto *ASE = dyn_cast<ArraySectionExpr>(Base->IgnoreParenImpCasts())) {
5243 BaseLVal = CGF.EmitArraySectionExpr(ASE, IsLowerBound);
5244 if (BaseTy->isArrayType()) {
5245 Address Addr = BaseLVal.getAddress();
5246 BaseInfo = BaseLVal.getBaseInfo();
5247
5248 // If the array type was an incomplete type, we need to make sure
5249 // the decay ends up being the right type.
5250 llvm::Type *NewTy = CGF.ConvertType(BaseTy);
5251 Addr = Addr.withElementType(NewTy);
5252
5253 // Note that VLA pointers are always decayed, so we don't need to do
5254 // anything here.
5255 if (!BaseTy->isVariableArrayType()) {
5256 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
5257 "Expected pointer to array");
5258 Addr = CGF.Builder.CreateConstArrayGEP(Addr, 0, "arraydecay");
5259 }
5260
5261 return Addr.withElementType(CGF.ConvertTypeForMem(ElTy));
5262 }
5263 LValueBaseInfo TypeBaseInfo;
5264 TBAAAccessInfo TypeTBAAInfo;
5265 CharUnits Align =
5266 CGF.CGM.getNaturalTypeAlignment(ElTy, &TypeBaseInfo, &TypeTBAAInfo);
5267 BaseInfo.mergeForCast(TypeBaseInfo);
5268 TBAAInfo = CGF.CGM.mergeTBAAInfoForCast(TBAAInfo, TypeTBAAInfo);
5269 return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress()),
5270 CGF.ConvertTypeForMem(ElTy), Align);
5271 }
5272 return CGF.EmitPointerWithAlignment(Base, &BaseInfo, &TBAAInfo);
5273}
5274
5276 bool IsLowerBound) {
5277
5278 assert(!E->isOpenACCArraySection() &&
5279 "OpenACC Array section codegen not implemented");
5280
5282 QualType ResultExprTy;
5283 if (auto *AT = getContext().getAsArrayType(BaseTy))
5284 ResultExprTy = AT->getElementType();
5285 else
5286 ResultExprTy = BaseTy->getPointeeType();
5287 llvm::Value *Idx = nullptr;
5288 if (IsLowerBound || E->getColonLocFirst().isInvalid()) {
5289 // Requesting lower bound or upper bound, but without provided length and
5290 // without ':' symbol for the default length -> length = 1.
5291 // Idx = LowerBound ?: 0;
5292 if (auto *LowerBound = E->getLowerBound()) {
5293 Idx = Builder.CreateIntCast(
5294 EmitScalarExpr(LowerBound), IntPtrTy,
5295 LowerBound->getType()->hasSignedIntegerRepresentation());
5296 } else
5297 Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
5298 } else {
5299 // Try to emit length or lower bound as constant. If this is possible, 1
5300 // is subtracted from constant length or lower bound. Otherwise, emit LLVM
5301 // IR (LB + Len) - 1.
5302 auto &C = CGM.getContext();
5303 auto *Length = E->getLength();
5304 llvm::APSInt ConstLength;
5305 if (Length) {
5306 // Idx = LowerBound + Length - 1;
5307 if (std::optional<llvm::APSInt> CL = Length->getIntegerConstantExpr(C)) {
5308 ConstLength = CL->zextOrTrunc(PointerWidthInBits);
5309 Length = nullptr;
5310 }
5311 auto *LowerBound = E->getLowerBound();
5312 llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
5313 if (LowerBound) {
5314 if (std::optional<llvm::APSInt> LB =
5315 LowerBound->getIntegerConstantExpr(C)) {
5316 ConstLowerBound = LB->zextOrTrunc(PointerWidthInBits);
5317 LowerBound = nullptr;
5318 }
5319 }
5320 if (!Length)
5321 --ConstLength;
5322 else if (!LowerBound)
5323 --ConstLowerBound;
5324
5325 if (Length || LowerBound) {
5326 auto *LowerBoundVal =
5327 LowerBound
5328 ? Builder.CreateIntCast(
5329 EmitScalarExpr(LowerBound), IntPtrTy,
5330 LowerBound->getType()->hasSignedIntegerRepresentation())
5331 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
5332 auto *LengthVal =
5333 Length
5334 ? Builder.CreateIntCast(
5335 EmitScalarExpr(Length), IntPtrTy,
5336 Length->getType()->hasSignedIntegerRepresentation())
5337 : llvm::ConstantInt::get(IntPtrTy, ConstLength);
5338 Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
5339 /*HasNUW=*/false,
5340 !getLangOpts().PointerOverflowDefined);
5341 if (Length && LowerBound) {
5342 Idx = Builder.CreateSub(
5343 Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
5344 /*HasNUW=*/false, !getLangOpts().PointerOverflowDefined);
5345 }
5346 } else
5347 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
5348 } else {
5349 // Idx = ArraySize - 1;
5350 QualType ArrayTy = BaseTy->isPointerType()
5352 : BaseTy;
5353 if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) {
5354 Length = VAT->getSizeExpr();
5355 if (std::optional<llvm::APSInt> L = Length->getIntegerConstantExpr(C)) {
5356 ConstLength = *L;
5357 Length = nullptr;
5358 }
5359 } else {
5360 auto *CAT = C.getAsConstantArrayType(ArrayTy);
5361 assert(CAT && "unexpected type for array initializer");
5362 ConstLength = CAT->getSize();
5363 }
5364 if (Length) {
5365 auto *LengthVal = Builder.CreateIntCast(
5366 EmitScalarExpr(Length), IntPtrTy,
5367 Length->getType()->hasSignedIntegerRepresentation());
5368 Idx = Builder.CreateSub(
5369 LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
5370 /*HasNUW=*/false, !getLangOpts().PointerOverflowDefined);
5371 } else {
5372 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
5373 --ConstLength;
5374 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
5375 }
5376 }
5377 }
5378 assert(Idx);
5379
5380 Address EltPtr = Address::invalid();
5381 LValueBaseInfo BaseInfo;
5382 TBAAAccessInfo TBAAInfo;
5383 if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
5384 // The base must be a pointer, which is not an aggregate. Emit
5385 // it. It needs to be emitted first in case it's what captures
5386 // the VLA bounds.
5387 Address Base =
5388 emitOMPArraySectionBase(*this, E->getBase(), BaseInfo, TBAAInfo,
5389 BaseTy, VLA->getElementType(), IsLowerBound);
5390 // The element count here is the total number of non-VLA elements.
5391 llvm::Value *NumElements = getVLASize(VLA).NumElts;
5392
5393 // Effectively, the multiply by the VLA size is part of the GEP.
5394 // GEP indexes are signed, and scaling an index isn't permitted to
5395 // signed-overflow, so we use the same semantics for our explicit
5396 // multiply. We suppress this if overflow is not undefined behavior.
5397 if (getLangOpts().PointerOverflowDefined)
5398 Idx = Builder.CreateMul(Idx, NumElements);
5399 else
5400 Idx = Builder.CreateNSWMul(Idx, NumElements);
5401 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(),
5402 !getLangOpts().PointerOverflowDefined,
5403 /*signedIndices=*/false, E->getExprLoc());
5404 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
5405 // If this is A[i] where A is an array, the frontend will have decayed the
5406 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
5407 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
5408 // "gep x, i" here. Emit one "gep A, 0, i".
5409 assert(Array->getType()->isArrayType() &&
5410 "Array to pointer decay must have array source type!");
5411 LValue ArrayLV;
5412 // For simple multidimensional array indexing, set the 'accessed' flag for
5413 // better bounds-checking of the base expression.
5414 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
5415 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
5416 else
5417 ArrayLV = EmitLValue(Array);
5418
5419 // Propagate the alignment from the array itself to the result.
5420 EltPtr = emitArraySubscriptGEP(
5421 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
5422 ResultExprTy, !getLangOpts().PointerOverflowDefined,
5423 /*signedIndices=*/false, E->getExprLoc());
5424 BaseInfo = ArrayLV.getBaseInfo();
5425 TBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, ResultExprTy);
5426 } else {
5427 Address Base =
5428 emitOMPArraySectionBase(*this, E->getBase(), BaseInfo, TBAAInfo, BaseTy,
5429 ResultExprTy, IsLowerBound);
5430 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy,
5431 !getLangOpts().PointerOverflowDefined,
5432 /*signedIndices=*/false, E->getExprLoc());
5433 }
5434
5435 return MakeAddrLValue(EltPtr, ResultExprTy, BaseInfo, TBAAInfo);
5436}
5437
5440 // Emit the base vector as an l-value.
5441 LValue Base;
5442
5443 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
5444 if (E->isArrow()) {
5445 // If it is a pointer to a vector, emit the address and form an lvalue with
5446 // it.
5447 LValueBaseInfo BaseInfo;
5448 TBAAAccessInfo TBAAInfo;
5449 Address Ptr = EmitPointerWithAlignment(E->getBase(), &BaseInfo, &TBAAInfo);
5450 const auto *PT = E->getBase()->getType()->castAs<PointerType>();
5451 Base = MakeAddrLValue(Ptr, PT->getPointeeType(), BaseInfo, TBAAInfo);
5452 Base.getQuals().removeObjCGCAttr();
5453 } else if (E->getBase()->isGLValue()) {
5454 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
5455 // emit the base as an lvalue.
5456 assert(E->getBase()->getType()->isVectorType());
5457 Base = EmitLValue(E->getBase());
5458 } else {
5459 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
5460 assert(E->getBase()->getType()->isVectorType() &&
5461 "Result must be a vector");
5462 llvm::Value *Vec = EmitScalarExpr(E->getBase());
5463
5464 // Store the vector to memory (because LValue wants an address).
5465 Address VecMem = CreateMemTemp(E->getBase()->getType());
5466 // need to zero extend an hlsl boolean vector to store it back to memory
5467 QualType Ty = E->getBase()->getType();
5468 llvm::Type *LTy = convertTypeForLoadStore(Ty, Vec->getType());
5469 if (LTy->getScalarSizeInBits() > Vec->getType()->getScalarSizeInBits())
5470 Vec = Builder.CreateZExt(Vec, LTy);
5471 Builder.CreateStore(Vec, VecMem);
5473 }
5474
5475 QualType type =
5476 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
5477
5478 // Encode the element access list into a vector of unsigned indices.
5480 E->getEncodedElementAccess(Indices);
5481
5482 if (Base.isSimple()) {
5483 llvm::Constant *CV =
5484 llvm::ConstantDataVector::get(getLLVMContext(), Indices);
5485 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
5486 Base.getBaseInfo(), TBAAAccessInfo());
5487 }
5488
5489 if (Base.isMatrixRow()) {
5490 if (auto *RowIdx =
5491 llvm::dyn_cast<llvm::ConstantInt>(Base.getMatrixRowIdx())) {
5493 QualType MatTy = Base.getType();
5494 const ConstantMatrixType *MT = MatTy->castAs<ConstantMatrixType>();
5495 unsigned NumCols = Indices.size();
5496 unsigned NumRows = MT->getNumRows();
5497 unsigned Row = RowIdx->getZExtValue();
5498 QualType VecQT = E->getBase()->getType();
5499 if (NumCols != MT->getNumColumns()) {
5500 const auto *EVT = VecQT->getAs<ExtVectorType>();
5501 QualType ElemQT = EVT->getElementType();
5502 VecQT = getContext().getExtVectorType(ElemQT, NumCols);
5503 }
5504 for (unsigned C = 0; C < NumCols; ++C) {
5505 unsigned Col = Indices[C];
5506 unsigned Linear = Col * NumRows + Row;
5507 MatIndices.push_back(llvm::ConstantInt::get(Int32Ty, Linear));
5508 }
5509
5510 llvm::Constant *ConstIdxs = llvm::ConstantVector::get(MatIndices);
5511 return LValue::MakeExtVectorElt(Base.getMatrixAddress(), ConstIdxs, VecQT,
5512 Base.getBaseInfo(), TBAAAccessInfo());
5513 }
5514 llvm::Constant *Cols =
5515 llvm::ConstantDataVector::get(getLLVMContext(), Indices);
5516 // Note: intentionally not using E.getType() so we can reuse isMatrixRow()
5517 // implementations in EmitLoadOfLValue & EmitStoreThroughLValue and don't
5518 // need the LValue to have its own number of rows and columns when the
5519 // type is a vector.
5521 Base.getMatrixAddress(), Base.getMatrixRowIdx(), Cols, Base.getType(),
5522 Base.getBaseInfo(), TBAAAccessInfo());
5523 }
5524
5525 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
5526
5527 llvm::Constant *BaseElts = Base.getExtVectorElts();
5529
5530 for (unsigned Index : Indices)
5531 CElts.push_back(BaseElts->getAggregateElement(Index));
5532 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
5533 return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
5534 Base.getBaseInfo(), TBAAAccessInfo());
5535}
5536
5538 const Expr *UnderlyingBaseExpr = E->IgnoreParens();
5539 while (auto *BaseMemberExpr = dyn_cast<MemberExpr>(UnderlyingBaseExpr))
5540 UnderlyingBaseExpr = BaseMemberExpr->getBase()->IgnoreParens();
5541 return getContext().isSentinelNullExpr(UnderlyingBaseExpr);
5542}
5543
5545 if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, E)) {
5547 return EmitDeclRefLValue(DRE);
5548 }
5549
5550 if (getLangOpts().HLSL) {
5551 QualType QT = E->getType();
5553 return CGM.getHLSLRuntime().emitBufferMemberExpr(*this, E);
5554
5556 std::optional<LValue> LV;
5557 LV = CGM.getHLSLRuntime().emitResourceMemberExpr(*this, E);
5558 if (LV.has_value())
5559 return *LV;
5560 }
5561 }
5562
5563 Expr *BaseExpr = E->getBase();
5564 // Check whether the underlying base pointer is a constant null.
5565 // If so, we do not set inbounds flag for GEP to avoid breaking some
5566 // old-style offsetof idioms.
5567 bool IsInBounds = !getLangOpts().PointerOverflowDefined &&
5569 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
5570 LValue BaseLV;
5571 if (E->isArrow()) {
5572 LValueBaseInfo BaseInfo;
5573 TBAAAccessInfo TBAAInfo;
5574 Address Addr = EmitPointerWithAlignment(BaseExpr, &BaseInfo, &TBAAInfo);
5575 QualType PtrTy = BaseExpr->getType()->getPointeeType();
5576 SanitizerSet SkippedChecks;
5577 bool IsBaseCXXThis = IsWrappedCXXThis(BaseExpr);
5578 if (IsBaseCXXThis)
5579 SkippedChecks.set(SanitizerKind::Alignment, true);
5580 if (IsBaseCXXThis || isa<DeclRefExpr>(BaseExpr))
5581 SkippedChecks.set(SanitizerKind::Null, true);
5583 /*Alignment=*/CharUnits::Zero(), SkippedChecks);
5584 BaseLV = MakeAddrLValue(Addr, PtrTy, BaseInfo, TBAAInfo);
5585 } else
5586 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
5587
5588 NamedDecl *ND = E->getMemberDecl();
5589 if (auto *Field = dyn_cast<FieldDecl>(ND)) {
5590 LValue LV = EmitLValueForField(BaseLV, Field, IsInBounds);
5592 if (getLangOpts().OpenMP) {
5593 // If the member was explicitly marked as nontemporal, mark it as
5594 // nontemporal. If the base lvalue is marked as nontemporal, mark access
5595 // to children as nontemporal too.
5596 if ((IsWrappedCXXThis(BaseExpr) &&
5597 CGM.getOpenMPRuntime().isNontemporalDecl(Field)) ||
5598 BaseLV.isNontemporal())
5599 LV.setNontemporal(/*Value=*/true);
5600 }
5601 return LV;
5602 }
5603
5604 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
5605 return EmitFunctionDeclLValue(*this, E, FD);
5606
5607 llvm_unreachable("Unhandled member declaration!");
5608}
5609
5610/// Given that we are currently emitting a lambda, emit an l-value for
5611/// one of its members.
5612///
5614 llvm::Value *ThisValue) {
5615 bool HasExplicitObjectParameter = false;
5616 const auto *MD = dyn_cast_if_present<CXXMethodDecl>(CurCodeDecl);
5617 if (MD) {
5618 HasExplicitObjectParameter = MD->isExplicitObjectMemberFunction();
5619 assert(MD->getParent()->isLambda());
5620 assert(MD->getParent() == Field->getParent());
5621 }
5622 LValue LambdaLV;
5623 if (HasExplicitObjectParameter) {
5624 const VarDecl *D = cast<CXXMethodDecl>(CurCodeDecl)->getParamDecl(0);
5625 auto It = LocalDeclMap.find(D);
5626 assert(It != LocalDeclMap.end() && "explicit parameter not loaded?");
5627 Address AddrOfExplicitObject = It->getSecond();
5628 if (D->getType()->isReferenceType())
5629 LambdaLV = EmitLoadOfReferenceLValue(AddrOfExplicitObject, D->getType(),
5631 else
5632 LambdaLV = MakeAddrLValue(AddrOfExplicitObject,
5634
5635 // Make sure we have an lvalue to the lambda itself and not a derived class.
5636 auto *ThisTy = D->getType().getNonReferenceType()->getAsCXXRecordDecl();
5637 auto *LambdaTy = cast<CXXRecordDecl>(Field->getParent());
5638 if (ThisTy != LambdaTy) {
5639 const CXXCastPath &BasePathArray = getContext().LambdaCastPaths.at(MD);
5641 LambdaLV.getAddress(), ThisTy, BasePathArray.begin(),
5642 BasePathArray.end(), /*NullCheckValue=*/false, SourceLocation());
5644 LambdaLV = MakeAddrLValue(Base, T);
5645 }
5646 } else {
5647 CanQualType LambdaTagType =
5648 getContext().getCanonicalTagType(Field->getParent());
5649 LambdaLV = MakeNaturalAlignAddrLValue(ThisValue, LambdaTagType);
5650 }
5651 return EmitLValueForField(LambdaLV, Field);
5652}
5653
5655 return EmitLValueForLambdaField(Field, CXXABIThisValue);
5656}
5657
5658/// Get the field index in the debug info. The debug info structure/union
5659/// will ignore the unnamed bitfields.
5661 unsigned FieldIndex) {
5662 unsigned I = 0, Skipped = 0;
5663
5664 for (auto *F : Rec->getDefinition()->fields()) {
5665 if (I == FieldIndex)
5666 break;
5667 if (F->isUnnamedBitField())
5668 Skipped++;
5669 I++;
5670 }
5671
5672 return FieldIndex - Skipped;
5673}
5674
5675/// Get the address of a zero-sized field within a record. The resulting
5676/// address doesn't necessarily have the right type.
5678 const FieldDecl *Field,
5679 bool IsInBounds) {
5681 CGF.getContext().getFieldOffset(Field));
5682 if (Offset.isZero())
5683 return Base;
5684 Base = Base.withElementType(CGF.Int8Ty);
5685 if (!IsInBounds)
5686 return CGF.Builder.CreateConstByteGEP(Base, Offset);
5687 return CGF.Builder.CreateConstInBoundsByteGEP(Base, Offset);
5688}
5689
5690/// Drill down to the storage of a field without walking into reference types,
5691/// and without respect for pointer field protection.
5692///
5693/// The resulting address doesn't necessarily have the right type.
5695 const FieldDecl *field,
5696 bool IsInBounds) {
5697 if (isEmptyFieldForLayout(CGF.getContext(), field))
5698 return emitAddrOfZeroSizeField(CGF, base, field, IsInBounds);
5699
5700 const RecordDecl *rec = field->getParent();
5701
5702 unsigned idx =
5703 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
5704 llvm::Type *StructType =
5706
5707 if (CGF.getLangOpts().EmitLogicalPointer)
5708 return RawAddress(
5709 CGF.Builder.CreateStructuredGEP(StructType, base.emitRawPointer(CGF),
5710 {CGF.Builder.getSize(idx)}),
5711 base.getElementType(), base.getAlignment());
5712
5713 if (!IsInBounds)
5714 return CGF.Builder.CreateConstGEP2_32(base, 0, idx, field->getName());
5715
5716 return CGF.Builder.CreateStructGEP(base, idx, field->getName());
5717}
5718
5719/// Drill down to the storage of a field without walking into reference types,
5720/// wrapping the address in an llvm.protected.field.ptr intrinsic for the
5721/// pointer field protection feature if necessary.
5722///
5723/// The resulting address doesn't necessarily have the right type.
5725 const FieldDecl *field, bool IsInBounds) {
5726 Address Addr = emitRawAddrOfFieldStorage(CGF, base, field, IsInBounds);
5727
5728 if (!CGF.getContext().isPFPField(field))
5729 return Addr;
5730
5731 return CGF.EmitAddressOfPFPField(base, Addr, field);
5732}
5733
5735 Address addr, const FieldDecl *field) {
5736 const RecordDecl *rec = field->getParent();
5737 llvm::DIType *DbgInfo = CGF.getDebugInfo()->getOrCreateStandaloneType(
5738 base.getType(), rec->getLocation());
5739
5740 unsigned idx =
5741 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
5742
5744 addr, idx, CGF.getDebugInfoFIndex(rec, field->getFieldIndex()), DbgInfo);
5745}
5746
5747static bool hasAnyVptr(const QualType Type, const ASTContext &Context) {
5748 const auto *RD = Type.getTypePtr()->getAsCXXRecordDecl();
5749 if (!RD)
5750 return false;
5751
5752 if (RD->isDynamicClass())
5753 return true;
5754
5755 for (const auto &Base : RD->bases())
5756 if (hasAnyVptr(Base.getType(), Context))
5757 return true;
5758
5759 for (const FieldDecl *Field : RD->fields())
5760 if (hasAnyVptr(Field->getType(), Context))
5761 return true;
5762
5763 return false;
5764}
5765
5767 bool IsInBounds) {
5768 LValueBaseInfo BaseInfo = base.getBaseInfo();
5769
5770 if (field->isBitField()) {
5771 const CGRecordLayout &RL =
5772 CGM.getTypes().getCGRecordLayout(field->getParent());
5773 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
5774 const bool UseVolatile = isAAPCS(CGM.getTarget()) &&
5775 CGM.getCodeGenOpts().AAPCSBitfieldWidth &&
5776 Info.VolatileStorageSize != 0 &&
5777 field->getType()
5780 Address Addr = base.getAddress();
5781 unsigned Idx = RL.getLLVMFieldNo(field);
5782 const RecordDecl *rec = field->getParent();
5785 if (!UseVolatile) {
5786 if (!IsInPreservedAIRegion &&
5787 (!getDebugInfo() || !rec->hasAttr<BPFPreserveAccessIndexAttr>())) {
5788 if (Idx != 0) {
5789 // For structs, we GEP to the field that the record layout suggests.
5790 if (!IsInBounds)
5791 Addr = Builder.CreateConstGEP2_32(Addr, 0, Idx, field->getName());
5792 else
5793 Addr = Builder.CreateStructGEP(Addr, Idx, field->getName());
5794 }
5795 } else {
5796 llvm::DIType *DbgInfo = getDebugInfo()->getOrCreateRecordType(
5797 getContext().getCanonicalTagType(rec), rec->getLocation());
5798 Addr = Builder.CreatePreserveStructAccessIndex(
5799 Addr, Idx, getDebugInfoFIndex(rec, field->getFieldIndex()),
5800 DbgInfo);
5801 }
5802 }
5803 const unsigned SS =
5804 UseVolatile ? Info.VolatileStorageSize : Info.StorageSize;
5805 // Get the access type.
5806 llvm::Type *FieldIntTy = llvm::Type::getIntNTy(getLLVMContext(), SS);
5807 Addr = Addr.withElementType(FieldIntTy);
5808 if (UseVolatile) {
5809 const unsigned VolatileOffset = Info.VolatileStorageOffset.getQuantity();
5810 if (VolatileOffset)
5811 Addr = Builder.CreateConstInBoundsGEP(Addr, VolatileOffset);
5812 }
5813
5814 QualType fieldType =
5815 field->getType().withCVRQualifiers(base.getVRQualifiers());
5816 // TODO: Support TBAA for bit fields.
5817 LValueBaseInfo FieldBaseInfo(BaseInfo.getAlignmentSource());
5818 return LValue::MakeBitfield(Addr, Info, fieldType, FieldBaseInfo,
5819 TBAAAccessInfo());
5820 }
5821
5822 // Fields of may-alias structures are may-alias themselves.
5823 // FIXME: this should get propagated down through anonymous structs
5824 // and unions.
5825 QualType FieldType = field->getType();
5826 const RecordDecl *rec = field->getParent();
5827 AlignmentSource BaseAlignSource = BaseInfo.getAlignmentSource();
5828 LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(BaseAlignSource));
5829 TBAAAccessInfo FieldTBAAInfo;
5830 if (base.getTBAAInfo().isMayAlias() ||
5831 rec->hasAttr<MayAliasAttr>() || FieldType->isVectorType()) {
5832 FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
5833 } else if (rec->isUnion()) {
5834 // TODO: Support TBAA for unions.
5835 FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
5836 } else {
5837 // If no base type been assigned for the base access, then try to generate
5838 // one for this base lvalue.
5839 FieldTBAAInfo = base.getTBAAInfo();
5840 if (!FieldTBAAInfo.BaseType) {
5841 FieldTBAAInfo.BaseType = CGM.getTBAABaseTypeInfo(base.getType());
5842 assert(!FieldTBAAInfo.Offset &&
5843 "Nonzero offset for an access with no base type!");
5844 }
5845
5846 // Adjust offset to be relative to the base type.
5847 const ASTRecordLayout &Layout =
5849 unsigned CharWidth = getContext().getCharWidth();
5850 if (FieldTBAAInfo.BaseType)
5851 FieldTBAAInfo.Offset +=
5852 Layout.getFieldOffset(field->getFieldIndex()) / CharWidth;
5853
5854 // Update the final access type and size.
5855 FieldTBAAInfo.AccessType = CGM.getTBAATypeInfo(FieldType);
5856 FieldTBAAInfo.Size =
5858 }
5859
5860 Address addr = base.getAddress();
5862 addr = wrapWithBPFPreserveStaticOffset(*this, addr);
5863 if (auto *ClassDef = dyn_cast<CXXRecordDecl>(rec)) {
5864 if (CGM.getCodeGenOpts().StrictVTablePointers &&
5865 ClassDef->isDynamicClass()) {
5866 // Getting to any field of dynamic object requires stripping dynamic
5867 // information provided by invariant.group. This is because accessing
5868 // fields may leak the real address of dynamic object, which could result
5869 // in miscompilation when leaked pointer would be compared.
5870 auto *stripped =
5871 Builder.CreateStripInvariantGroup(addr.emitRawPointer(*this));
5872 addr = Address(stripped, addr.getElementType(), addr.getAlignment());
5873 }
5874 }
5875
5876 unsigned RecordCVR = base.getVRQualifiers();
5877 if (rec->isUnion()) {
5878 // For unions, there is no pointer adjustment.
5879 if (CGM.getCodeGenOpts().StrictVTablePointers &&
5880 hasAnyVptr(FieldType, getContext()))
5881 // Because unions can easily skip invariant.barriers, we need to add
5882 // a barrier every time CXXRecord field with vptr is referenced.
5883 addr = Builder.CreateLaunderInvariantGroup(addr);
5884
5886 (getDebugInfo() && rec->hasAttr<BPFPreserveAccessIndexAttr>())) {
5887 // Remember the original union field index
5888 llvm::DIType *DbgInfo = getDebugInfo()->getOrCreateStandaloneType(base.getType(),
5889 rec->getLocation());
5890 addr =
5891 Address(Builder.CreatePreserveUnionAccessIndex(
5892 addr.emitRawPointer(*this),
5893 getDebugInfoFIndex(rec, field->getFieldIndex()), DbgInfo),
5894 addr.getElementType(), addr.getAlignment());
5895 }
5896
5897 if (FieldType->isReferenceType())
5898 addr = addr.withElementType(CGM.getTypes().ConvertTypeForMem(FieldType));
5899 } else {
5900 if (!IsInPreservedAIRegion &&
5901 (!getDebugInfo() || !rec->hasAttr<BPFPreserveAccessIndexAttr>()))
5902 // For structs, we GEP to the field that the record layout suggests.
5903 addr = emitAddrOfFieldStorage(*this, addr, field, IsInBounds);
5904 else
5905 // Remember the original struct field index
5906 addr = emitPreserveStructAccess(*this, base, addr, field);
5907 }
5908
5909 // If this is a reference field, load the reference right now.
5910 if (FieldType->isReferenceType()) {
5911 LValue RefLVal =
5912 MakeAddrLValue(addr, FieldType, FieldBaseInfo, FieldTBAAInfo);
5913 if (RecordCVR & Qualifiers::Volatile)
5914 RefLVal.getQuals().addVolatile();
5915 addr = EmitLoadOfReference(RefLVal, &FieldBaseInfo, &FieldTBAAInfo);
5916
5917 // Qualifiers on the struct don't apply to the referencee.
5918 RecordCVR = 0;
5919 FieldType = FieldType->getPointeeType();
5920 }
5921
5922 // Make sure that the address is pointing to the right type. This is critical
5923 // for both unions and structs.
5924 addr = addr.withElementType(CGM.getTypes().ConvertTypeForMem(FieldType));
5925
5926 if (field->hasAttr<AnnotateAttr>())
5927 addr = EmitFieldAnnotations(field, addr);
5928
5929 LValue LV = MakeAddrLValue(addr, FieldType, FieldBaseInfo, FieldTBAAInfo);
5930 LV.getQuals().addCVRQualifiers(RecordCVR);
5931
5932 // __weak attribute on a field is ignored.
5935
5936 return LV;
5937}
5938
5939LValue
5941 const FieldDecl *Field) {
5942 QualType FieldType = Field->getType();
5943
5944 if (!FieldType->isReferenceType())
5945 return EmitLValueForField(Base, Field);
5946
5948 *this, Base.getAddress(), Field,
5949 /*IsInBounds=*/!getLangOpts().PointerOverflowDefined);
5950
5951 // Make sure that the address is pointing to the right type.
5952 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
5953 V = V.withElementType(llvmType);
5954
5955 // TODO: Generate TBAA information that describes this access as a structure
5956 // member access and not just an access to an object of the field's type. This
5957 // should be similar to what we do in EmitLValueForField().
5958 LValueBaseInfo BaseInfo = Base.getBaseInfo();
5959 AlignmentSource FieldAlignSource = BaseInfo.getAlignmentSource();
5960 LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(FieldAlignSource));
5961 return MakeAddrLValue(V, FieldType, FieldBaseInfo,
5962 CGM.getTBAAInfoForSubobject(Base, FieldType));
5963}
5964
5966 if (E->isFileScope()) {
5967 ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
5968 return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl);
5969 }
5970 if (E->getType()->isVariablyModifiedType())
5971 // make sure to emit the VLA size.
5973
5974 Address DeclPtr = CreateMemTempWithoutCast(E->getType(), ".compoundliteral");
5975 const Expr *InitExpr = E->getInitializer();
5977
5978 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
5979 /*Init*/ true);
5980
5981 // Block-scope compound literals are destroyed at the end of the enclosing
5982 // scope in C.
5983 if (!getLangOpts().CPlusPlus)
5986 E->getType(), getDestroyer(DtorKind),
5987 DtorKind & EHCleanup);
5988
5989 return Result;
5990}
5991
5993 if (!E->isGLValue())
5994 // Initializing an aggregate temporary in C++11: T{...}.
5995 return EmitAggExprToLValue(E);
5996
5997 // An lvalue initializer list must be initializing a reference.
5998 assert(E->isTransparent() && "non-transparent glvalue init list");
5999 return EmitLValue(E->getInit(0));
6000}
6001
6002/// Emit the operand of a glvalue conditional operator. This is either a glvalue
6003/// or a (possibly-parenthesized) throw-expression. If this is a throw, no
6004/// LValue is returned and the current block has been terminated.
6005static std::optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
6006 const Expr *Operand) {
6007 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
6008 CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
6009 return std::nullopt;
6010 }
6011
6012 return CGF.EmitLValue(Operand);
6013}
6014
6015namespace {
6016// Handle the case where the condition is a constant evaluatable simple integer,
6017// which means we don't have to separately handle the true/false blocks.
6018std::optional<LValue> HandleConditionalOperatorLValueSimpleCase(
6019 CodeGenFunction &CGF, const AbstractConditionalOperator *E) {
6020 const Expr *condExpr = E->getCond();
6021 bool CondExprBool;
6022 if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
6023 const Expr *Live = E->getTrueExpr(), *Dead = E->getFalseExpr();
6024 if (!CondExprBool)
6025 std::swap(Live, Dead);
6026
6027 if (!CGF.ContainsLabel(Dead)) {
6028 // If the true case is live, we need to track its region.
6029 CGF.incrementProfileCounter(CondExprBool ? CGF.UseExecPath
6030 : CGF.UseSkipPath,
6031 E, /*UseBoth=*/true);
6032 CGF.markStmtMaybeUsed(Dead);
6033 // If a throw expression we emit it and return an undefined lvalue
6034 // because it can't be used.
6035 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Live->IgnoreParens())) {
6036 CGF.EmitCXXThrowExpr(ThrowExpr);
6037 llvm::Type *ElemTy = CGF.ConvertType(Dead->getType());
6038 llvm::Type *Ty = CGF.DefaultPtrTy;
6039 return CGF.MakeAddrLValue(
6040 Address(llvm::UndefValue::get(Ty), ElemTy, CharUnits::One()),
6041 Dead->getType());
6042 }
6043 return CGF.EmitLValue(Live);
6044 }
6045 }
6046 return std::nullopt;
6047}
6048struct ConditionalInfo {
6049 llvm::BasicBlock *lhsBlock, *rhsBlock;
6050 std::optional<LValue> LHS, RHS;
6051};
6052
6053// Create and generate the 3 blocks for a conditional operator.
6054// Leaves the 'current block' in the continuation basic block.
6055template<typename FuncTy>
6056ConditionalInfo EmitConditionalBlocks(CodeGenFunction &CGF,
6057 const AbstractConditionalOperator *E,
6058 const FuncTy &BranchGenFunc) {
6059 ConditionalInfo Info{CGF.createBasicBlock("cond.true"),
6060 CGF.createBasicBlock("cond.false"), std::nullopt,
6061 std::nullopt};
6062 llvm::BasicBlock *endBlock = CGF.createBasicBlock("cond.end");
6063
6065 CGF.EmitBranchOnBoolExpr(E->getCond(), Info.lhsBlock, Info.rhsBlock,
6066 CGF.getProfileCount(E));
6067
6068 // Any temporaries created here are conditional.
6069 CGF.EmitBlock(Info.lhsBlock);
6071 eval.begin(CGF);
6072 Info.LHS = BranchGenFunc(CGF, E->getTrueExpr());
6073 eval.end(CGF);
6074 Info.lhsBlock = CGF.Builder.GetInsertBlock();
6075
6076 if (Info.LHS)
6077 CGF.Builder.CreateBr(endBlock);
6078
6079 // Any temporaries created here are conditional.
6080 CGF.EmitBlock(Info.rhsBlock);
6082 eval.begin(CGF);
6083 Info.RHS = BranchGenFunc(CGF, E->getFalseExpr());
6084 eval.end(CGF);
6085 Info.rhsBlock = CGF.Builder.GetInsertBlock();
6086 CGF.EmitBlock(endBlock);
6087
6088 return Info;
6089}
6090} // namespace
6091
6093 const AbstractConditionalOperator *E) {
6094 if (!E->isGLValue()) {
6095 // ?: here should be an aggregate.
6096 assert(hasAggregateEvaluationKind(E->getType()) &&
6097 "Unexpected conditional operator!");
6098 return (void)EmitAggExprToLValue(E);
6099 }
6100
6101 OpaqueValueMapping binding(*this, E);
6102 if (HandleConditionalOperatorLValueSimpleCase(*this, E))
6103 return;
6104
6105 EmitConditionalBlocks(*this, E, [](CodeGenFunction &CGF, const Expr *E) {
6106 CGF.EmitIgnoredExpr(E);
6107 return LValue{};
6108 });
6109}
6112 if (!expr->isGLValue()) {
6113 // ?: here should be an aggregate.
6114 assert(hasAggregateEvaluationKind(expr->getType()) &&
6115 "Unexpected conditional operator!");
6116 return EmitAggExprToLValue(expr);
6117 }
6118
6119 OpaqueValueMapping binding(*this, expr);
6120 if (std::optional<LValue> Res =
6121 HandleConditionalOperatorLValueSimpleCase(*this, expr))
6122 return *Res;
6123
6124 ConditionalInfo Info = EmitConditionalBlocks(
6125 *this, expr, [](CodeGenFunction &CGF, const Expr *E) {
6126 return EmitLValueOrThrowExpression(CGF, E);
6127 });
6128
6129 if ((Info.LHS && !Info.LHS->isSimple()) ||
6130 (Info.RHS && !Info.RHS->isSimple()))
6131 return EmitUnsupportedLValue(expr, "conditional operator");
6132
6133 if (Info.LHS && Info.RHS) {
6134 Address lhsAddr = Info.LHS->getAddress();
6135 Address rhsAddr = Info.RHS->getAddress();
6137 lhsAddr, rhsAddr, Info.lhsBlock, Info.rhsBlock,
6138 Builder.GetInsertBlock(), expr->getType());
6139 AlignmentSource alignSource =
6140 std::max(Info.LHS->getBaseInfo().getAlignmentSource(),
6141 Info.RHS->getBaseInfo().getAlignmentSource());
6142 TBAAAccessInfo TBAAInfo = CGM.mergeTBAAInfoForConditionalOperator(
6143 Info.LHS->getTBAAInfo(), Info.RHS->getTBAAInfo());
6144 return MakeAddrLValue(result, expr->getType(), LValueBaseInfo(alignSource),
6145 TBAAInfo);
6146 } else {
6147 assert((Info.LHS || Info.RHS) &&
6148 "both operands of glvalue conditional are throw-expressions?");
6149 return Info.LHS ? *Info.LHS : *Info.RHS;
6150 }
6151}
6152
6153/// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
6154/// type. If the cast is to a reference, we can have the usual lvalue result,
6155/// otherwise if a cast is needed by the code generator in an lvalue context,
6156/// then it must mean that we need the address of an aggregate in order to
6157/// access one of its members. This can happen for all the reasons that casts
6158/// are permitted with aggregate result, including noop aggregate casts, and
6159/// cast from scalar to union.
6161 llvm::scope_exit RestoreCurCast([this, Prev = CurCast] { CurCast = Prev; });
6162 CurCast = E;
6163 switch (E->getCastKind()) {
6164 case CK_ToVoid:
6165 case CK_BitCast:
6166 case CK_LValueToRValueBitCast:
6167 case CK_ArrayToPointerDecay:
6168 case CK_FunctionToPointerDecay:
6169 case CK_NullToMemberPointer:
6170 case CK_NullToPointer:
6171 case CK_IntegralToPointer:
6172 case CK_PointerToIntegral:
6173 case CK_PointerToBoolean:
6174 case CK_IntegralCast:
6175 case CK_BooleanToSignedIntegral:
6176 case CK_IntegralToBoolean:
6177 case CK_IntegralToFloating:
6178 case CK_FloatingToIntegral:
6179 case CK_FloatingToBoolean:
6180 case CK_FloatingCast:
6181 case CK_FloatingRealToComplex:
6182 case CK_FloatingComplexToReal:
6183 case CK_FloatingComplexToBoolean:
6184 case CK_FloatingComplexCast:
6185 case CK_FloatingComplexToIntegralComplex:
6186 case CK_IntegralRealToComplex:
6187 case CK_IntegralComplexToReal:
6188 case CK_IntegralComplexToBoolean:
6189 case CK_IntegralComplexCast:
6190 case CK_IntegralComplexToFloatingComplex:
6191 case CK_DerivedToBaseMemberPointer:
6192 case CK_BaseToDerivedMemberPointer:
6193 case CK_MemberPointerToBoolean:
6194 case CK_ReinterpretMemberPointer:
6195 case CK_AnyPointerToBlockPointerCast:
6196 case CK_ARCProduceObject:
6197 case CK_ARCConsumeObject:
6198 case CK_ARCReclaimReturnedObject:
6199 case CK_ARCExtendBlockObject:
6200 case CK_CopyAndAutoreleaseBlockObject:
6201 case CK_IntToOCLSampler:
6202 case CK_FloatingToFixedPoint:
6203 case CK_FixedPointToFloating:
6204 case CK_FixedPointCast:
6205 case CK_FixedPointToBoolean:
6206 case CK_FixedPointToIntegral:
6207 case CK_IntegralToFixedPoint:
6208 case CK_MatrixCast:
6209 case CK_HLSLVectorTruncation:
6210 case CK_HLSLMatrixTruncation:
6211 case CK_HLSLArrayRValue:
6212 case CK_HLSLElementwiseCast:
6213 case CK_HLSLAggregateSplatCast:
6214 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
6215
6216 case CK_Dependent:
6217 llvm_unreachable("dependent cast kind in IR gen!");
6218
6219 case CK_BuiltinFnToFnPtr:
6220 llvm_unreachable("builtin functions are handled elsewhere");
6221
6222 // These are never l-values; just use the aggregate emission code.
6223 case CK_NonAtomicToAtomic:
6224 case CK_AtomicToNonAtomic:
6225 return EmitAggExprToLValue(E);
6226
6227 case CK_Dynamic: {
6228 LValue LV = EmitLValue(E->getSubExpr());
6229 Address V = LV.getAddress();
6230 const auto *DCE = cast<CXXDynamicCastExpr>(E);
6232 }
6233
6234 case CK_ConstructorConversion:
6235 case CK_UserDefinedConversion:
6236 case CK_CPointerToObjCPointerCast:
6237 case CK_BlockPointerToObjCPointerCast:
6238 case CK_LValueToRValue:
6239 return EmitLValue(E->getSubExpr());
6240
6241 case CK_NoOp: {
6242 // CK_NoOp can model a qualification conversion, which can remove an array
6243 // bound and change the IR type.
6244 // FIXME: Once pointee types are removed from IR, remove this.
6245 LValue LV = EmitLValue(E->getSubExpr());
6246 // Propagate the volatile qualifer to LValue, if exist in E.
6248 LV.getQuals() = E->getType().getQualifiers();
6249 if (LV.isSimple()) {
6250 Address V = LV.getAddress();
6251 if (V.isValid()) {
6252 llvm::Type *T = ConvertTypeForMem(E->getType());
6253 if (V.getElementType() != T)
6254 LV.setAddress(V.withElementType(T));
6255 }
6256 }
6257 return LV;
6258 }
6259
6260 case CK_UncheckedDerivedToBase:
6261 case CK_DerivedToBase: {
6262 auto *DerivedClassDecl = E->getSubExpr()->getType()->castAsCXXRecordDecl();
6263 LValue LV = EmitLValue(E->getSubExpr());
6264 Address This = LV.getAddress();
6265
6266 // Perform the derived-to-base conversion
6268 This, DerivedClassDecl, E->path_begin(), E->path_end(),
6269 /*NullCheckValue=*/false, E->getExprLoc());
6270
6271 // TODO: Support accesses to members of base classes in TBAA. For now, we
6272 // conservatively pretend that the complete object is of the base class
6273 // type.
6274 return MakeAddrLValue(Base, E->getType(), LV.getBaseInfo(),
6275 CGM.getTBAAInfoForSubobject(LV, E->getType()));
6276 }
6277 case CK_ToUnion:
6278 return EmitAggExprToLValue(E);
6279 case CK_BaseToDerived: {
6280 auto *DerivedClassDecl = E->getType()->castAsCXXRecordDecl();
6281 LValue LV = EmitLValue(E->getSubExpr());
6282
6283 // Perform the base-to-derived conversion
6285 LV.getAddress(), DerivedClassDecl, E->path_begin(), E->path_end(),
6286 /*NullCheckValue=*/false);
6287
6288 // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
6289 // performed and the object is not of the derived type.
6292 E->getType());
6293
6294 if (SanOpts.has(SanitizerKind::CFIDerivedCast))
6295 EmitVTablePtrCheckForCast(E->getType(), Derived,
6296 /*MayBeNull=*/false, CFITCK_DerivedCast,
6297 E->getBeginLoc());
6298
6299 return MakeAddrLValue(Derived, E->getType(), LV.getBaseInfo(),
6300 CGM.getTBAAInfoForSubobject(LV, E->getType()));
6301 }
6302 case CK_LValueBitCast: {
6303 // This must be a reinterpret_cast (or c-style equivalent).
6304 const auto *CE = cast<ExplicitCastExpr>(E);
6305
6306 CGM.EmitExplicitCastExprType(CE, this);
6307 LValue LV = EmitLValue(E->getSubExpr());
6309 ConvertTypeForMem(CE->getTypeAsWritten()->getPointeeType()));
6310
6311 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
6313 /*MayBeNull=*/false, CFITCK_UnrelatedCast,
6314 E->getBeginLoc());
6315
6316 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
6317 CGM.getTBAAInfoForSubobject(LV, E->getType()));
6318 }
6319 case CK_AddressSpaceConversion: {
6320 LValue LV = EmitLValue(E->getSubExpr());
6321 QualType DestTy = getContext().getPointerType(E->getType());
6322 llvm::Value *V =
6323 performAddrSpaceCast(LV.getPointer(*this), ConvertType(DestTy));
6325 LV.getAddress().getAlignment()),
6326 E->getType(), LV.getBaseInfo(), LV.getTBAAInfo());
6327 }
6328 case CK_ObjCObjectLValueCast: {
6329 LValue LV = EmitLValue(E->getSubExpr());
6331 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
6332 CGM.getTBAAInfoForSubobject(LV, E->getType()));
6333 }
6334 case CK_ZeroToOCLOpaqueType:
6335 llvm_unreachable("NULL to OpenCL opaque type lvalue cast is not valid");
6336
6337 case CK_VectorSplat: {
6338 // LValue results of vector splats are only supported in HLSL.
6339 if (!getLangOpts().HLSL)
6340 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
6341 return EmitLValue(E->getSubExpr());
6342 }
6343 }
6344
6345 llvm_unreachable("Unhandled lvalue cast kind?");
6346}
6347
6352
6353std::pair<LValue, LValue>
6355 // Emitting the casted temporary through an opaque value.
6356 LValue BaseLV = EmitLValue(E->getArgLValue());
6358
6359 QualType ExprTy = E->getType();
6360 Address OutTemp = CreateIRTempWithoutCast(ExprTy);
6361 LValue TempLV = MakeAddrLValue(OutTemp, ExprTy);
6362
6363 // Start the lifetime before the copy-in so that the temporary is live when
6364 // the initial value is written. This ensures the store is within the
6365 // lifetime and is not killed by a store undef inserted at lifetime.start.
6367
6368 if (E->isInOut())
6370 TempLV);
6371
6373 return std::make_pair(BaseLV, TempLV);
6374}
6375
6377 CallArgList &Args, QualType Ty) {
6378
6379 auto [BaseLV, TempLV] = EmitHLSLOutArgLValues(E, Ty);
6380
6381 llvm::Value *Addr = TempLV.getAddress().getBasePointer();
6382 llvm::Type *ElTy = ConvertTypeForMem(TempLV.getType());
6383
6384 Address TmpAddr(Addr, ElTy, TempLV.getAlignment());
6385 Args.addWriteback(BaseLV, TmpAddr, nullptr, E->getWritebackCast());
6386 Args.add(RValue::get(TmpAddr, *this), Ty);
6387 return TempLV;
6388}
6389
6390LValue
6393
6394 llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator
6395 it = OpaqueLValues.find(e);
6396
6397 if (it != OpaqueLValues.end())
6398 return it->second;
6399
6400 assert(e->isUnique() && "LValue for a nonunique OVE hasn't been emitted");
6401 return EmitLValue(e->getSourceExpr());
6402}
6403
6404RValue
6407
6408 llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator
6409 it = OpaqueRValues.find(e);
6410
6411 if (it != OpaqueRValues.end())
6412 return it->second;
6413
6414 assert(e->isUnique() && "RValue for a nonunique OVE hasn't been emitted");
6415 return EmitAnyExpr(e->getSourceExpr());
6416}
6417
6420 return OpaqueLValues.contains(E);
6421 return OpaqueRValues.contains(E);
6422}
6423
6425 const FieldDecl *FD,
6426 SourceLocation Loc) {
6427 QualType FT = FD->getType();
6428 LValue FieldLV = EmitLValueForField(LV, FD);
6429 switch (getEvaluationKind(FT)) {
6430 case TEK_Complex:
6431 return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
6432 case TEK_Aggregate:
6433 return FieldLV.asAggregateRValue();
6434 case TEK_Scalar:
6435 // This routine is used to load fields one-by-one to perform a copy, so
6436 // don't load reference fields.
6437 if (FD->getType()->isReferenceType())
6438 return RValue::get(FieldLV.getPointer(*this));
6439 // Call EmitLoadOfScalar except when the lvalue is a bitfield to emit a
6440 // primitive load.
6441 if (FieldLV.isBitField())
6442 return EmitLoadOfLValue(FieldLV, Loc);
6443 return RValue::get(EmitLoadOfScalar(FieldLV, Loc));
6444 }
6445 llvm_unreachable("bad evaluation kind");
6446}
6447
6448//===--------------------------------------------------------------------===//
6449// Expression Emission
6450//===--------------------------------------------------------------------===//
6451
6454 llvm::CallBase **CallOrInvoke) {
6455 llvm::CallBase *CallOrInvokeStorage;
6456 if (!CallOrInvoke) {
6457 CallOrInvoke = &CallOrInvokeStorage;
6458 }
6459
6460 llvm::scope_exit AddCoroElideSafeOnExit([&] {
6461 if (E->isCoroElideSafe()) {
6462 auto *I = *CallOrInvoke;
6463 if (I)
6464 I->addFnAttr(llvm::Attribute::CoroElideSafe);
6465 }
6466 });
6467
6468 // Builtins never have block type.
6469 if (E->getCallee()->getType()->isBlockPointerType())
6470 return EmitBlockCallExpr(E, ReturnValue, CallOrInvoke);
6471
6472 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
6473 return EmitCXXMemberCallExpr(CE, ReturnValue, CallOrInvoke);
6474
6475 if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
6476 return EmitCUDAKernelCallExpr(CE, ReturnValue, CallOrInvoke);
6477
6478 // A CXXOperatorCallExpr is created even for explicit object methods, but
6479 // these should be treated like static function call.
6480 if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
6481 if (const auto *MD =
6482 dyn_cast_if_present<CXXMethodDecl>(CE->getCalleeDecl());
6483 MD && MD->isImplicitObjectMemberFunction())
6484 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue, CallOrInvoke);
6485
6486 CGCallee callee = EmitCallee(E->getCallee());
6487
6488 if (callee.isBuiltin()) {
6489 return EmitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(),
6490 E, ReturnValue);
6491 }
6492
6493 if (callee.isPseudoDestructor()) {
6495 }
6496
6497 return EmitCall(E->getCallee()->getType(), callee, E, ReturnValue,
6498 /*Chain=*/nullptr, CallOrInvoke);
6499}
6500
6501/// Emit a CallExpr without considering whether it might be a subclass.
6504 llvm::CallBase **CallOrInvoke) {
6505 CGCallee Callee = EmitCallee(E->getCallee());
6506 return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue,
6507 /*Chain=*/nullptr, CallOrInvoke);
6508}
6509
6510// Detect the unusual situation where an inline version is shadowed by a
6511// non-inline version. In that case we should pick the external one
6512// everywhere. That's GCC behavior too.
6514 for (const FunctionDecl *PD = FD; PD; PD = PD->getPreviousDecl())
6515 if (!PD->isInlineBuiltinDeclaration())
6516 return false;
6517 return true;
6518}
6519
6521 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
6522
6523 if (auto builtinID = FD->getBuiltinID()) {
6524 std::string NoBuiltinFD = ("no-builtin-" + FD->getName()).str();
6525 std::string NoBuiltins = "no-builtins";
6526
6527 StringRef Ident = CGF.CGM.getMangledName(GD);
6528 std::string FDInlineName = (Ident + ".inline").str();
6529
6530 bool IsPredefinedLibFunction =
6532 bool HasAttributeNoBuiltin =
6533 CGF.CurFn->getAttributes().hasFnAttr(NoBuiltinFD) ||
6534 CGF.CurFn->getAttributes().hasFnAttr(NoBuiltins);
6535
6536 // When directing calling an inline builtin, call it through it's mangled
6537 // name to make it clear it's not the actual builtin.
6538 if (CGF.CurFn->getName() != FDInlineName &&
6540 llvm::Constant *CalleePtr = CGF.CGM.getRawFunctionPointer(GD);
6541 llvm::Function *Fn = llvm::cast<llvm::Function>(CalleePtr);
6542 llvm::Module *M = Fn->getParent();
6543 llvm::Function *Clone = M->getFunction(FDInlineName);
6544 if (!Clone) {
6545 Clone = llvm::Function::Create(Fn->getFunctionType(),
6546 llvm::GlobalValue::InternalLinkage,
6547 Fn->getAddressSpace(), FDInlineName, M);
6548 Clone->addFnAttr(llvm::Attribute::AlwaysInline);
6549 }
6550 return CGCallee::forDirect(Clone, GD);
6551 }
6552
6553 // Replaceable builtins provide their own implementation of a builtin. If we
6554 // are in an inline builtin implementation, avoid trivial infinite
6555 // recursion. Honor __attribute__((no_builtin("foo"))) or
6556 // __attribute__((no_builtin)) on the current function unless foo is
6557 // not a predefined library function which means we must generate the
6558 // builtin no matter what.
6559 else if (!IsPredefinedLibFunction || !HasAttributeNoBuiltin)
6560 return CGCallee::forBuiltin(builtinID, FD);
6561 }
6562
6563 llvm::Constant *CalleePtr = CGF.CGM.getRawFunctionPointer(GD);
6564 if (CGF.CGM.getLangOpts().CUDA && !CGF.CGM.getLangOpts().CUDAIsDevice &&
6565 FD->hasAttr<CUDAGlobalAttr>())
6566 CalleePtr = CGF.CGM.getCUDARuntime().getKernelStub(
6567 cast<llvm::GlobalValue>(CalleePtr->stripPointerCasts()));
6568
6569 return CGCallee::forDirect(CalleePtr, GD);
6570}
6571
6573 if (DeviceKernelAttr::isOpenCLSpelling(FD->getAttr<DeviceKernelAttr>()))
6575 return GlobalDecl(FD);
6576}
6577
6579 E = E->IgnoreParens();
6580
6581 // Look through function-to-pointer decay.
6582 if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) {
6583 if (ICE->getCastKind() == CK_FunctionToPointerDecay ||
6584 ICE->getCastKind() == CK_BuiltinFnToFnPtr) {
6585 return EmitCallee(ICE->getSubExpr());
6586 }
6587
6588 // Try to remember the original __ptrauth qualifier for loads of
6589 // function pointers.
6590 if (ICE->getCastKind() == CK_LValueToRValue) {
6591 const Expr *SubExpr = ICE->getSubExpr();
6592 if (const auto *PtrType = SubExpr->getType()->getAs<PointerType>()) {
6593 std::pair<llvm::Value *, CGPointerAuthInfo> Result =
6595
6597 assert(FunctionType->isFunctionType());
6598
6599 GlobalDecl GD;
6600 if (const auto *VD =
6601 dyn_cast_or_null<VarDecl>(E->getReferencedDeclOfCallee())) {
6602 GD = GlobalDecl(VD);
6603 }
6605 CGCallee Callee(CalleeInfo, Result.first, Result.second);
6606 return Callee;
6607 }
6608 }
6609
6610 // Resolve direct calls.
6611 } else if (auto DRE = dyn_cast<DeclRefExpr>(E)) {
6612 if (auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
6614 }
6615 } else if (auto ME = dyn_cast<MemberExpr>(E)) {
6616 if (auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) {
6617 EmitIgnoredExpr(ME->getBase());
6618 return EmitDirectCallee(*this, FD);
6619 }
6620
6621 // Look through template substitutions.
6622 } else if (auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
6623 return EmitCallee(NTTP->getReplacement());
6624
6625 // Treat pseudo-destructor calls differently.
6626 } else if (auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) {
6628 }
6629
6630 // Otherwise, we have an indirect reference.
6631 llvm::Value *calleePtr;
6633 if (auto ptrType = E->getType()->getAs<PointerType>()) {
6634 calleePtr = EmitScalarExpr(E);
6635 functionType = ptrType->getPointeeType();
6636 } else {
6637 functionType = E->getType();
6638 calleePtr = EmitLValue(E, KnownNonNull).getPointer(*this);
6639 }
6640 assert(functionType->isFunctionType());
6641
6642 GlobalDecl GD;
6643 if (const auto *VD =
6644 dyn_cast_or_null<VarDecl>(E->getReferencedDeclOfCallee()))
6645 GD = GlobalDecl(VD);
6646
6647 CGCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(), GD);
6648 CGPointerAuthInfo pointerAuth = CGM.getFunctionPointerAuthInfo(functionType);
6649 CGCallee callee(calleeInfo, calleePtr, pointerAuth);
6650 return callee;
6651}
6652
6654 // Comma expressions just emit their LHS then their RHS as an l-value.
6655 if (E->getOpcode() == BO_Comma) {
6656 EmitIgnoredExpr(E->getLHS());
6658 return EmitLValue(E->getRHS());
6659 }
6660
6661 if (E->getOpcode() == BO_PtrMemD ||
6662 E->getOpcode() == BO_PtrMemI)
6664
6665 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
6666
6667 // Create a Key Instructions source location atom group that covers both
6668 // LHS and RHS expressions. Nested RHS expressions may get subsequently
6669 // separately grouped (1 below):
6670 //
6671 // 1. `a = b = c` -> Two atoms.
6672 // 2. `x = new(1)` -> One atom (for both addr store and value store).
6673 // 3. Complex and agg assignment -> One atom.
6675
6676 // Note that in all of these cases, __block variables need the RHS
6677 // evaluated first just in case the variable gets moved by the RHS.
6678
6679 switch (getEvaluationKind(E->getType())) {
6680 case TEK_Scalar: {
6681 if (PointerAuthQualifier PtrAuth =
6682 E->getLHS()->getType().getPointerAuth()) {
6684 LValue CopiedLV = LV;
6685 CopiedLV.getQuals().removePointerAuth();
6686 llvm::Value *RV =
6687 EmitPointerAuthQualify(PtrAuth, E->getRHS(), CopiedLV.getAddress());
6688 EmitNullabilityCheck(CopiedLV, RV, E->getExprLoc());
6689 EmitStoreThroughLValue(RValue::get(RV), CopiedLV);
6690 return LV;
6691 }
6692
6693 switch (E->getLHS()->getType().getObjCLifetime()) {
6695 return EmitARCStoreStrong(E, /*ignored*/ false).first;
6696
6698 return EmitARCStoreAutoreleasing(E).first;
6699
6700 // No reason to do any of these differently.
6704 break;
6705 }
6706
6707 // TODO: Can we de-duplicate this code with the corresponding code in
6708 // CGExprScalar, similar to the way EmitCompoundAssignmentLValue works?
6709 RValue RV;
6710 llvm::Value *Previous = nullptr;
6711 QualType SrcType = E->getRHS()->getType();
6712 // Check if LHS is a bitfield, if RHS contains an implicit cast expression
6713 // we want to extract that value and potentially (if the bitfield sanitizer
6714 // is enabled) use it to check for an implicit conversion.
6715 if (E->getLHS()->refersToBitField()) {
6716 llvm::Value *RHS =
6718 RV = RValue::get(RHS);
6719 } else
6720 RV = EmitAnyExpr(E->getRHS());
6721
6723
6724 if (RV.isScalar())
6726
6727 if (LV.isBitField()) {
6728 llvm::Value *Result = nullptr;
6729 // If bitfield sanitizers are enabled we want to use the result
6730 // to check whether a truncation or sign change has occurred.
6731 if (SanOpts.has(SanitizerKind::ImplicitBitfieldConversion))
6733 else
6735
6736 // If the expression contained an implicit conversion, make sure
6737 // to use the value before the scalar conversion.
6738 llvm::Value *Src = Previous ? Previous : RV.getScalarVal();
6739 QualType DstType = E->getLHS()->getType();
6740 EmitBitfieldConversionCheck(Src, SrcType, Result, DstType,
6741 LV.getBitFieldInfo(), E->getExprLoc());
6742 } else
6743 EmitStoreThroughLValue(RV, LV);
6744
6745 if (getLangOpts().OpenMP)
6746 CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(*this,
6747 E->getLHS());
6748 return LV;
6749 }
6750
6751 case TEK_Complex:
6753
6754 case TEK_Aggregate:
6755 // If the lang opt is HLSL and the LHS is a constant array
6756 // then we are performing a copy assignment and call a special
6757 // function because EmitAggExprToLValue emits to a temporary LValue
6759 return EmitHLSLArrayAssignLValue(E);
6760
6761 return EmitAggExprToLValue(E);
6762 }
6763 llvm_unreachable("bad evaluation kind");
6764}
6765
6766// This function implements trivial copy assignment for HLSL's
6767// assignable constant arrays.
6769 // Don't emit an LValue for the RHS because it might not be an LValue
6770 LValue LHS = EmitLValue(E->getLHS());
6771
6772 // If the RHS is a global resource array, copy all individual resources
6773 // into LHS.
6774 if (E->getRHS()->getType()->isHLSLResourceRecordArray()) {
6779 if (CGM.getHLSLRuntime().emitGlobalResourceArray(*this, E->getRHS(), Slot))
6780 return LHS;
6781 }
6782
6783 // In C the RHS of an assignment operator is an RValue.
6784 // EmitAggregateAssign takes an LValue for the RHS. Instead we can call
6785 // EmitInitializationToLValue to emit an RValue into an LValue.
6787 return LHS;
6788}
6789
6791 llvm::CallBase **CallOrInvoke) {
6792 RValue RV = EmitCallExpr(E, ReturnValueSlot(), CallOrInvoke);
6793
6794 if (!RV.isScalar())
6795 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
6797
6798 assert(E->getCallReturnType(getContext())->isReferenceType() &&
6799 "Can't have a scalar return unless the return type is a "
6800 "reference type!");
6801
6803}
6804
6806 // FIXME: This shouldn't require another copy.
6807 return EmitAggExprToLValue(E);
6808}
6809
6812 && "binding l-value to type which needs a temporary");
6813 AggValueSlot Slot = CreateAggTemp(E->getType());
6814 EmitCXXConstructExpr(E, Slot);
6816}
6817
6818LValue
6822
6824 return CGM.GetAddrOfMSGuidDecl(E->getGuidDecl())
6825 .withElementType(ConvertType(E->getType()));
6826}
6827
6832
6833LValue
6841
6844
6845 if (!RV.isScalar())
6846 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
6848
6849 assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
6850 "Can't have a scalar return unless the return type is a "
6851 "reference type!");
6852
6854}
6855
6857 Address V =
6858 CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
6860}
6861
6863 const ObjCIvarDecl *Ivar) {
6864 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
6865}
6866
6867llvm::Value *
6869 const ObjCIvarDecl *Ivar) {
6870 llvm::Value *OffsetValue = EmitIvarOffset(Interface, Ivar);
6871 QualType PointerDiffType = getContext().getPointerDiffType();
6872 return Builder.CreateZExtOrTrunc(OffsetValue,
6873 getTypes().ConvertType(PointerDiffType));
6874}
6875
6877 llvm::Value *BaseValue,
6878 const ObjCIvarDecl *Ivar,
6879 unsigned CVRQualifiers) {
6880 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
6881 Ivar, CVRQualifiers);
6882}
6883
6885 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
6886 llvm::Value *BaseValue = nullptr;
6887 const Expr *BaseExpr = E->getBase();
6888 Qualifiers BaseQuals;
6889 QualType ObjectTy;
6890 if (E->isArrow()) {
6891 BaseValue = EmitScalarExpr(BaseExpr);
6892 ObjectTy = BaseExpr->getType()->getPointeeType();
6893 BaseQuals = ObjectTy.getQualifiers();
6894 } else {
6895 LValue BaseLV = EmitLValue(BaseExpr);
6896 BaseValue = BaseLV.getPointer(*this);
6897 ObjectTy = BaseExpr->getType();
6898 BaseQuals = ObjectTy.getQualifiers();
6899 }
6900
6901 LValue LV =
6902 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
6903 BaseQuals.getCVRQualifiers());
6905 return LV;
6906}
6907
6909 // Can only get l-value for message expression returning aggregate type
6910 RValue RV = EmitAnyExprToTemp(E);
6911 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
6913}
6914
6916 const CGCallee &OrigCallee, const CallExpr *E,
6918 llvm::Value *Chain,
6919 llvm::CallBase **CallOrInvoke,
6920 CGFunctionInfo const **ResolvedFnInfo) {
6921 // Get the actual function type. The callee type will always be a pointer to
6922 // function type or a block pointer type.
6923 assert(CalleeType->isFunctionPointerType() &&
6924 "Call must have function pointer type!");
6925
6926 const Decl *TargetDecl =
6927 OrigCallee.getAbstractInfo().getCalleeDecl().getDecl();
6928
6929 assert((!isa_and_present<FunctionDecl>(TargetDecl) ||
6930 !cast<FunctionDecl>(TargetDecl)->isImmediateFunction()) &&
6931 "trying to emit a call to an immediate function");
6932
6933 CalleeType = getContext().getCanonicalType(CalleeType);
6934
6935 auto PointeeType = cast<PointerType>(CalleeType)->getPointeeType();
6936
6937 CGCallee Callee = OrigCallee;
6938
6939 bool CFIUnchecked = CalleeType->hasPointeeToCFIUncheckedCalleeFunctionType();
6940
6941 if (SanOpts.has(SanitizerKind::Function) &&
6942 (!TargetDecl || !isa<FunctionDecl>(TargetDecl)) &&
6943 !isa<FunctionNoProtoType>(PointeeType) && !CFIUnchecked) {
6944 if (llvm::Constant *PrefixSig =
6945 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
6946 auto CheckOrdinal = SanitizerKind::SO_Function;
6947 auto CheckHandler = SanitizerHandler::FunctionTypeMismatch;
6948 SanitizerDebugLocation SanScope(this, {CheckOrdinal}, CheckHandler);
6949 auto *TypeHash = getUBSanFunctionTypeHash(PointeeType);
6950
6951 llvm::Type *PrefixSigType = PrefixSig->getType();
6952 llvm::StructType *PrefixStructTy = llvm::StructType::get(
6953 CGM.getLLVMContext(), {PrefixSigType, Int32Ty}, /*isPacked=*/true);
6954
6955 llvm::Value *CalleePtr = Callee.getFunctionPointer();
6956 if (CGM.getCodeGenOpts().PointerAuth.FunctionPointers) {
6957 // Use raw pointer since we are using the callee pointer as data here.
6958 Address Addr =
6959 Address(CalleePtr, CalleePtr->getType(),
6961 CalleePtr->getPointerAlignment(CGM.getDataLayout())),
6962 Callee.getPointerAuthInfo(), nullptr);
6963 CalleePtr = Addr.emitRawPointer(*this);
6964 }
6965
6966 // On 32-bit Arm, the low bit of a function pointer indicates whether
6967 // it's using the Arm or Thumb instruction set. The actual first
6968 // instruction lives at the same address either way, so we must clear
6969 // that low bit before using the function address to find the prefix
6970 // structure.
6971 //
6972 // This applies to both Arm and Thumb target triples, because
6973 // either one could be used in an interworking context where it
6974 // might be passed function pointers of both types.
6975 llvm::Value *AlignedCalleePtr;
6976 if (CGM.getTriple().isARM() || CGM.getTriple().isThumb()) {
6977 AlignedCalleePtr = Builder.CreateIntrinsic(
6978 CalleePtr->getType(), llvm::Intrinsic::ptrmask,
6979 {CalleePtr, llvm::ConstantInt::getSigned(IntPtrTy, ~1)});
6980 } else {
6981 AlignedCalleePtr = CalleePtr;
6982 }
6983
6984 llvm::Value *CalleePrefixStruct = AlignedCalleePtr;
6985 llvm::Value *CalleeSigPtr =
6986 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, -1, 0);
6987 llvm::Value *CalleeSig =
6988 Builder.CreateAlignedLoad(PrefixSigType, CalleeSigPtr, getIntAlign());
6989 llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
6990
6991 llvm::BasicBlock *Cont = createBasicBlock("cont");
6992 llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
6993 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
6994
6995 EmitBlock(TypeCheck);
6996 llvm::Value *CalleeTypeHash = Builder.CreateAlignedLoad(
6997 Int32Ty,
6998 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, -1, 1),
6999 getPointerAlign());
7000 llvm::Value *CalleeTypeHashMatch =
7001 Builder.CreateICmpEQ(CalleeTypeHash, TypeHash);
7002 llvm::Constant *StaticData[] = {EmitCheckSourceLocation(E->getBeginLoc()),
7003 EmitCheckTypeDescriptor(CalleeType)};
7004 EmitCheck(std::make_pair(CalleeTypeHashMatch, CheckOrdinal), CheckHandler,
7005 StaticData, {CalleePtr});
7006
7007 Builder.CreateBr(Cont);
7008 EmitBlock(Cont);
7009 }
7010 }
7011
7012 const auto *FnType = cast<FunctionType>(PointeeType);
7013
7014 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl);
7015 FD && DeviceKernelAttr::isOpenCLSpelling(FD->getAttr<DeviceKernelAttr>()))
7016 CGM.getTargetCodeGenInfo().setOCLKernelStubCallingConvention(FnType);
7017
7018 // If we are checking indirect calls and this call is indirect, check that the
7019 // function pointer is a member of the bit set for the function type.
7020 if (SanOpts.has(SanitizerKind::CFIICall) &&
7021 (!TargetDecl || !isa<FunctionDecl>(TargetDecl)) && !CFIUnchecked) {
7022 auto CheckOrdinal = SanitizerKind::SO_CFIICall;
7023 auto CheckHandler = SanitizerHandler::CFICheckFail;
7024 SanitizerDebugLocation SanScope(this, {CheckOrdinal}, CheckHandler);
7025 EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
7026
7027 llvm::Metadata *MD =
7028 CGM.CreateMetadataIdentifierForFnType(QualType(FnType, 0));
7029
7030 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
7031
7032 llvm::Value *CalleePtr = Callee.getFunctionPointer();
7033 llvm::Value *TypeTest = Builder.CreateCall(
7034 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CalleePtr, TypeId});
7035
7036 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
7037 llvm::Constant *StaticData[] = {
7038 llvm::ConstantInt::get(Int8Ty, CFITCK_ICall),
7041 };
7042 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
7043 EmitCfiSlowPathCheck(CheckOrdinal, TypeTest, CrossDsoTypeId, CalleePtr,
7044 StaticData);
7045 } else {
7046 EmitCheck(std::make_pair(TypeTest, CheckOrdinal), CheckHandler,
7047 StaticData, {CalleePtr, llvm::UndefValue::get(IntPtrTy)});
7048 }
7049 }
7050
7051 CallArgList Args;
7052 if (Chain)
7053 Args.add(RValue::get(Chain), CGM.getContext().VoidPtrTy);
7054
7055 // C++17 requires that we evaluate arguments to a call using assignment syntax
7056 // right-to-left, and that we evaluate arguments to certain other operators
7057 // left-to-right. Note that we allow this to override the order dictated by
7058 // the calling convention on the MS ABI, which means that parameter
7059 // destruction order is not necessarily reverse construction order.
7060 // FIXME: Revisit this based on C++ committee response to unimplementability.
7062 bool StaticOperator = false;
7063 if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
7064 if (OCE->isAssignmentOp())
7066 else {
7067 switch (OCE->getOperator()) {
7068 case OO_LessLess:
7069 case OO_GreaterGreater:
7070 case OO_AmpAmp:
7071 case OO_PipePipe:
7072 case OO_Comma:
7073 case OO_ArrowStar:
7075 break;
7076 default:
7077 break;
7078 }
7079 }
7080
7081 if (const auto *MD =
7082 dyn_cast_if_present<CXXMethodDecl>(OCE->getCalleeDecl());
7083 MD && MD->isStatic())
7084 StaticOperator = true;
7085 }
7086
7087 auto Arguments = E->arguments();
7088 if (StaticOperator) {
7089 // If we're calling a static operator, we need to emit the object argument
7090 // and ignore it.
7091 EmitIgnoredExpr(E->getArg(0));
7092 Arguments = drop_begin(Arguments, 1);
7093 }
7094 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), Arguments,
7095 E->getDirectCallee(), /*ParamsToSkip=*/0, Order);
7096
7097 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
7098 Args, FnType, /*ChainCall=*/Chain);
7099
7100 if (ResolvedFnInfo)
7101 *ResolvedFnInfo = &FnInfo;
7102
7103 // HIP function pointer contains kernel handle when it is used in triple
7104 // chevron. The kernel stub needs to be loaded from kernel handle and used
7105 // as callee.
7106 if (CGM.getLangOpts().HIP && !CGM.getLangOpts().CUDAIsDevice &&
7108 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
7109 llvm::Value *Handle = Callee.getFunctionPointer();
7110 auto *Stub = Builder.CreateLoad(
7111 Address(Handle, Handle->getType(), CGM.getPointerAlign()));
7112 Callee.setFunctionPointer(Stub);
7113 }
7114
7115 // Insert function pointer lookup if this is a target call
7116 //
7117 // This is used for the indirect function case, virtual function case is
7118 // handled in ItaniumCXXABI.cpp
7119 if (getLangOpts().OpenMPIsTargetDevice && CGM.getTriple().isGPU() &&
7120 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
7121 const Expr *CalleeExpr = E->getCallee()->IgnoreParenImpCasts();
7122 const DeclRefExpr *DRE = nullptr;
7123 while (CalleeExpr) {
7124 if ((DRE = dyn_cast<DeclRefExpr>(CalleeExpr)))
7125 break;
7126 if (const auto *ME = dyn_cast<MemberExpr>(CalleeExpr))
7127 CalleeExpr = ME->getBase()->IgnoreParenImpCasts();
7128 else if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(CalleeExpr))
7129 CalleeExpr = ASE->getBase()->IgnoreParenImpCasts();
7130 else
7131 break;
7132 }
7133
7134 const auto *VD = DRE ? dyn_cast<VarDecl>(DRE->getDecl()) : nullptr;
7135 if (VD && VD->hasAttr<OMPTargetIndirectCallAttr>()) {
7136 auto *FuncPtrTy = llvm::PointerType::get(
7137 CGM.getLLVMContext(), CGM.getDataLayout().getProgramAddressSpace());
7138 llvm::Type *RtlFnArgs[] = {FuncPtrTy};
7139 llvm::FunctionCallee DeviceRtlFn = CGM.CreateRuntimeFunction(
7140 llvm::FunctionType::get(FuncPtrTy, RtlFnArgs, false),
7141 "__llvm_omp_indirect_call_lookup");
7142 llvm::Value *Func = Callee.getFunctionPointer();
7143 llvm::Type *BackupTy = Func->getType();
7144 Func = Builder.CreatePointerBitCastOrAddrSpaceCast(Func, FuncPtrTy);
7145 Func = EmitRuntimeCall(DeviceRtlFn, {Func});
7146 Func = Builder.CreatePointerBitCastOrAddrSpaceCast(Func, BackupTy);
7147 Callee.setFunctionPointer(Func);
7148 }
7149 }
7150
7151 llvm::CallBase *LocalCallOrInvoke = nullptr;
7152 RValue Call = EmitCall(FnInfo, Callee, ReturnValue, Args, &LocalCallOrInvoke,
7153 E == MustTailCall, E->getExprLoc());
7154
7155 if (auto *CalleeDecl = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
7156 if (CalleeDecl->hasAttr<RestrictAttr>() ||
7157 CalleeDecl->hasAttr<MallocSpanAttr>() ||
7158 CalleeDecl->hasAttr<AllocSizeAttr>()) {
7159 // Function has 'malloc' (aka. 'restrict') or 'alloc_size' attribute.
7160 if (SanOpts.has(SanitizerKind::AllocToken)) {
7161 // Set !alloc_token metadata.
7162 EmitAllocToken(LocalCallOrInvoke, E);
7163 }
7164 }
7165 }
7166 if (CallOrInvoke)
7167 *CallOrInvoke = LocalCallOrInvoke;
7168
7169 return Call;
7170}
7171
7174 Address BaseAddr = Address::invalid();
7175 if (E->getOpcode() == BO_PtrMemI) {
7176 BaseAddr = EmitPointerWithAlignment(E->getLHS());
7177 } else {
7178 BaseAddr = EmitLValue(E->getLHS()).getAddress();
7179 }
7180
7181 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
7182 const auto *MPT = E->getRHS()->getType()->castAs<MemberPointerType>();
7183
7184 LValueBaseInfo BaseInfo;
7185 TBAAAccessInfo TBAAInfo;
7186 bool IsInBounds = !getLangOpts().PointerOverflowDefined &&
7189 E, BaseAddr, OffsetV, MPT, IsInBounds, &BaseInfo, &TBAAInfo);
7190
7191 return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), BaseInfo, TBAAInfo);
7192}
7193
7194/// Given the address of a temporary variable, produce an r-value of
7195/// its type.
7197 QualType type,
7198 SourceLocation loc) {
7200 switch (getEvaluationKind(type)) {
7201 case TEK_Complex:
7202 return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
7203 case TEK_Aggregate:
7204 return lvalue.asAggregateRValue();
7205 case TEK_Scalar:
7206 return RValue::get(EmitLoadOfScalar(lvalue, loc));
7207 }
7208 llvm_unreachable("bad evaluation kind");
7209}
7210
7211void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
7212 assert(Val->getType()->isFPOrFPVectorTy());
7213 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
7214 return;
7215
7216 llvm::MDBuilder MDHelper(getLLVMContext());
7217 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
7218
7219 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
7220}
7221
7223 llvm::Type *EltTy = Val->getType()->getScalarType();
7224 if (!EltTy->isFloatTy() && !EltTy->isHalfTy())
7225 return;
7226
7227 if ((getLangOpts().OpenCL &&
7228 !CGM.getCodeGenOpts().OpenCLCorrectlyRoundedDivSqrt) ||
7229 (getLangOpts().HIP && getLangOpts().CUDAIsDevice &&
7230 !CGM.getCodeGenOpts().HIPCorrectlyRoundedDivSqrt)) {
7231 // OpenCL v1.1 s7.4: minimum accuracy of single precision sqrt is 3 ulp.
7232 // OpenCL v3.0 s7.4: minimum accuracy of half precision sqrt is 1.5 ulp.
7233 //
7234 // OpenCL v1.2 s5.6.4.2: The -cl-fp32-correctly-rounded-divide-sqrt
7235 // build option allows an application to specify that single precision
7236 // floating-point divide (x/y and 1/x) and sqrt used in the program
7237 // source are correctly rounded.
7238 //
7239 // TODO: CUDA has a prec-sqrt flag
7240 SetFPAccuracy(Val, EltTy->isFloatTy() ? 3.0f : 1.5f);
7241 }
7242}
7243
7245 llvm::Type *EltTy = Val->getType()->getScalarType();
7246 if (!EltTy->isFloatTy() && !EltTy->isHalfTy())
7247 return;
7248
7249 if ((getLangOpts().OpenCL &&
7250 !CGM.getCodeGenOpts().OpenCLCorrectlyRoundedDivSqrt) ||
7251 (getLangOpts().HIP && getLangOpts().CUDAIsDevice &&
7252 !CGM.getCodeGenOpts().HIPCorrectlyRoundedDivSqrt)) {
7253 // OpenCL v1.1 s7.4: minimum accuracy of single precision / is 2.5 ulp.
7254 // OpenCL v3.0 s7.4: minimum accuracy of half precision / is 1 ulp.
7255 //
7256 // OpenCL v1.2 s5.6.4.2: The -cl-fp32-correctly-rounded-divide-sqrt
7257 // build option allows an application to specify that single precision
7258 // floating-point divide (x/y and 1/x) and sqrt used in the program
7259 // source are correctly rounded.
7260 //
7261 // TODO: CUDA has a prec-div flag
7262 SetFPAccuracy(Val, EltTy->isFloatTy() ? 2.5f : 1.f);
7263 }
7264}
7265
7266namespace {
7267 struct LValueOrRValue {
7268 LValue LV;
7269 RValue RV;
7270 };
7271}
7272
7273static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
7274 const PseudoObjectExpr *E,
7275 bool forLValue,
7276 AggValueSlot slot) {
7278
7279 // Find the result expression, if any.
7280 const Expr *resultExpr = E->getResultExpr();
7281 LValueOrRValue result;
7282
7284 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
7285 const Expr *semantic = *i;
7286
7287 // If this semantic expression is an opaque value, bind it
7288 // to the result of its source expression.
7289 if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
7290 // Skip unique OVEs.
7291 if (ov->isUnique()) {
7292 assert(ov != resultExpr &&
7293 "A unique OVE cannot be used as the result expression");
7294 continue;
7295 }
7296
7297 // If this is the result expression, we may need to evaluate
7298 // directly into the slot.
7300 OVMA opaqueData;
7301 if (ov == resultExpr && ov->isPRValue() && !forLValue &&
7303 CGF.EmitAggExpr(ov->getSourceExpr(), slot);
7304 LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
7306 opaqueData = OVMA::bind(CGF, ov, LV);
7307 result.RV = slot.asRValue();
7308
7309 // Otherwise, emit as normal.
7310 } else {
7311 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
7312
7313 // If this is the result, also evaluate the result now.
7314 if (ov == resultExpr) {
7315 if (forLValue)
7316 result.LV = CGF.EmitLValue(ov);
7317 else
7318 result.RV = CGF.EmitAnyExpr(ov, slot);
7319 }
7320 }
7321
7322 opaques.push_back(opaqueData);
7323
7324 // Otherwise, if the expression is the result, evaluate it
7325 // and remember the result.
7326 } else if (semantic == resultExpr) {
7327 if (forLValue)
7328 result.LV = CGF.EmitLValue(semantic);
7329 else
7330 result.RV = CGF.EmitAnyExpr(semantic, slot);
7331
7332 // Otherwise, evaluate the expression in an ignored context.
7333 } else {
7334 CGF.EmitIgnoredExpr(semantic);
7335 }
7336 }
7337
7338 // Unbind all the opaques now.
7339 for (CodeGenFunction::OpaqueValueMappingData &opaque : opaques)
7340 opaque.unbind(CGF);
7341
7342 return result;
7343}
7344
7346 AggValueSlot slot) {
7347 return emitPseudoObjectExpr(*this, E, false, slot).RV;
7348}
7349
7353
7355 LValue Val, SmallVectorImpl<LValue> &AccessList) {
7356
7358 std::tuple<LValue, QualType, llvm::SmallVector<llvm::Value *, 4>>, 16>
7359 WorkList;
7360 llvm::IntegerType *IdxTy = llvm::IntegerType::get(getLLVMContext(), 32);
7361 WorkList.push_back({Val, Val.getType(), {llvm::ConstantInt::get(IdxTy, 0)}});
7362
7363 while (!WorkList.empty()) {
7364 auto [LVal, T, IdxList] = WorkList.pop_back_val();
7365 T = T.getCanonicalType().getUnqualifiedType();
7366 if (const auto *CAT = dyn_cast<ConstantArrayType>(T)) {
7367 uint64_t Size = CAT->getZExtSize();
7368 for (int64_t I = Size - 1; I > -1; I--) {
7369 llvm::SmallVector<llvm::Value *, 4> IdxListCopy = IdxList;
7370 IdxListCopy.push_back(llvm::ConstantInt::get(IdxTy, I));
7371 WorkList.emplace_back(LVal, CAT->getElementType(), IdxListCopy);
7372 }
7373 } else if (const auto *RT = dyn_cast<RecordType>(T)) {
7374 const RecordDecl *Record = RT->getDecl()->getDefinitionOrSelf();
7375 assert(!Record->isUnion() && "Union types not supported in flat cast.");
7376
7377 const CXXRecordDecl *CXXD = dyn_cast<CXXRecordDecl>(Record);
7378
7380 std::tuple<LValue, QualType, llvm::SmallVector<llvm::Value *, 4>>, 16>
7381 ReverseList;
7382 if (CXXD && CXXD->isStandardLayout())
7384
7385 // deal with potential base classes
7386 if (CXXD && !CXXD->isStandardLayout()) {
7387 if (CXXD->getNumBases() > 0) {
7388 assert(CXXD->getNumBases() == 1 &&
7389 "HLSL doesn't support multiple inheritance.");
7390 auto Base = CXXD->bases_begin();
7391 llvm::SmallVector<llvm::Value *, 4> IdxListCopy = IdxList;
7392 IdxListCopy.push_back(llvm::ConstantInt::get(
7393 IdxTy, 0)); // base struct should be at index zero
7394 ReverseList.emplace_back(LVal, Base->getType(), IdxListCopy);
7395 }
7396 }
7397
7398 const CGRecordLayout &Layout = CGM.getTypes().getCGRecordLayout(Record);
7399
7400 llvm::Type *LLVMT = ConvertTypeForMem(T);
7402 LValue RLValue;
7403 bool createdGEP = false;
7404 for (auto *FD : Record->fields()) {
7405 if (FD->isBitField()) {
7406 if (FD->isUnnamedBitField())
7407 continue;
7408 if (!createdGEP) {
7409 createdGEP = true;
7410 Address GEP = Builder.CreateInBoundsGEP(LVal.getAddress(), IdxList,
7411 LLVMT, Align, "gep");
7412 RLValue = MakeAddrLValue(GEP, T);
7413 }
7414 LValue FieldLVal = EmitLValueForField(RLValue, FD, true);
7415 ReverseList.push_back({FieldLVal, FD->getType(), {}});
7416 } else {
7417 llvm::SmallVector<llvm::Value *, 4> IdxListCopy = IdxList;
7418 IdxListCopy.push_back(
7419 llvm::ConstantInt::get(IdxTy, Layout.getLLVMFieldNo(FD)));
7420 ReverseList.emplace_back(LVal, FD->getType(), IdxListCopy);
7421 }
7422 }
7423
7424 std::reverse(ReverseList.begin(), ReverseList.end());
7425 llvm::append_range(WorkList, ReverseList);
7426 } else if (const auto *VT = dyn_cast<VectorType>(T)) {
7427 llvm::Type *LLVMT = ConvertTypeForMem(T);
7429 Address GEP = Builder.CreateInBoundsGEP(LVal.getAddress(), IdxList, LLVMT,
7430 Align, "vector.gep");
7431 LValue Base = MakeAddrLValue(GEP, T);
7432 for (unsigned I = 0, E = VT->getNumElements(); I < E; I++) {
7433 llvm::Constant *Idx = llvm::ConstantInt::get(IdxTy, I);
7434 LValue LV =
7435 LValue::MakeVectorElt(Base.getAddress(), Idx, VT->getElementType(),
7436 Base.getBaseInfo(), TBAAAccessInfo());
7437 AccessList.emplace_back(LV);
7438 }
7439 } else if (const auto *MT = dyn_cast<ConstantMatrixType>(T)) {
7440 // Matrices are represented as flat arrays in memory, but has a vector
7441 // value type. So we use ConvertMatrixAddress to convert the address from
7442 // array to vector, and extract elements similar to the vector case above.
7443 // The matrix elements are iterated over in row-major order regardless of
7444 // the memory layout of the matrix.
7445 llvm::Type *LLVMT = ConvertTypeForMem(T);
7447 Address GEP = Builder.CreateInBoundsGEP(LVal.getAddress(), IdxList, LLVMT,
7448 Align, "matrix.gep");
7449 LValue Base = MakeAddrLValue(GEP, T);
7450 Address MatAddr = MaybeConvertMatrixAddress(Base.getAddress(), *this);
7451 unsigned NumRows = MT->getNumRows();
7452 unsigned NumCols = MT->getNumColumns();
7453 bool IsMatrixRowMajor = isMatrixRowMajor(getLangOpts(), T);
7454 llvm::MatrixBuilder MB(Builder);
7455 for (unsigned Row = 0; Row < MT->getNumRows(); Row++) {
7456 for (unsigned Col = 0; Col < MT->getNumColumns(); Col++) {
7457 llvm::Value *RowIdx = llvm::ConstantInt::get(IdxTy, Row);
7458 llvm::Value *ColIdx = llvm::ConstantInt::get(IdxTy, Col);
7459 llvm::Value *Idx = MB.CreateIndex(RowIdx, ColIdx, NumRows, NumCols,
7460 IsMatrixRowMajor);
7461 LValue LV =
7462 LValue::MakeMatrixElt(MatAddr, Idx, MT->getElementType(),
7463 Base.getBaseInfo(), TBAAAccessInfo());
7464 AccessList.emplace_back(LV);
7465 }
7466 }
7467 } else { // a scalar/builtin type
7468 if (!IdxList.empty()) {
7469 llvm::Type *LLVMT = ConvertTypeForMem(T);
7471 Address GEP = Builder.CreateInBoundsGEP(LVal.getAddress(), IdxList,
7472 LLVMT, Align, "gep");
7473 AccessList.emplace_back(MakeAddrLValue(GEP, T));
7474 } else // must be a bitfield we already created an lvalue for
7475 AccessList.emplace_back(LVal);
7476 }
7477 }
7478}
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:3245
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:3525
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:4666
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:4867
static bool hasBPFPreserveStaticOffset(const RecordDecl *D)
Definition CGExpr.cpp:4731
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:5694
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:3513
static std::optional< LValue > EmitLValueOrThrowExpression(CodeGenFunction &CGF, const Expr *Operand)
Emit the operand of a glvalue conditional operator.
Definition CGExpr.cpp:6005
static CheckRecoverableKind getRecoverableKind(SanitizerKind::SanitizerOrdinal Ordinal)
Definition CGExpr.cpp:4105
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:4680
SmallVector< llvm::Value *, 8 > RecIndicesTy
Definition CGExpr.cpp:1167
static GlobalDecl getGlobalDeclForDirectCall(const FunctionDecl *FD)
Definition CGExpr.cpp:6572
static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF, const Expr *E, GlobalDecl GD)
Definition CGExpr.cpp:3500
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:7273
static Address wrapWithBPFPreserveStaticOffset(CodeGenFunction &CGF, Address &Addr)
Definition CGExpr.cpp:4747
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:2485
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:5724
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:4898
static CGCallee EmitDirectCallee(CodeGenFunction &CGF, GlobalDecl GD)
Definition CGExpr.cpp:6520
static LValue EmitThreadPrivateVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr, llvm::Type *RealVarTy, SourceLocation Loc)
Definition CGExpr.cpp:3342
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:6513
static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF, const Expr *E, const VarDecl *VD)
Definition CGExpr.cpp:3440
static bool hasAnyVptr(const QualType Type, const ASTContext &Context)
Definition CGExpr.cpp:5747
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:4760
static Address emitDeclTargetVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD, QualType T)
Definition CGExpr.cpp:3356
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:2406
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:5734
const SanitizerHandlerInfo SanitizerHandlers[]
Definition CGExpr.cpp:4122
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:4128
static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base, LValueBaseInfo &BaseInfo, TBAAAccessInfo &TBAAInfo, QualType BaseTy, QualType ElTy, bool IsLowerBound)
Definition CGExpr.cpp:5236
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:1001
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:223
SourceManager & getSourceManager()
Definition ASTContext.h:863
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:804
const LangOptions & getLangOpts() const
Definition ASTContext.h:959
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:4359
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4537
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4543
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4549
This class represents BOTH the OpenMP Array Section and OpenACC 'subarray', with a boolean differenti...
Definition Expr.h:7222
Expr * getBase()
Get base of the array section.
Definition Expr.h:7300
Expr * getLength()
Get length of array section.
Definition Expr.h:7310
static QualType getBaseOriginalType(const Expr *Base)
Return original type of the base expression for array section.
Definition Expr.cpp:5394
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:7339
Expr * getLowerBound()
Get lower bound of array section.
Definition Expr.h:7304
bool isOpenACCArraySection() const
Definition Expr.h:7297
SourceLocation getColonLocFirst() const
Definition Expr.h:7331
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2727
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:2782
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition Expr.h:2756
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3786
QualType getElementType() const
Definition TypeBase.h:3798
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4044
Expr * getLHS() const
Definition Expr.h:4094
SourceLocation getExprLoc() const
Definition Expr.h:4085
Expr * getRHS() const
Definition Expr.h:4096
static bool isAdditiveOp(Opcode Opc)
Definition Expr.h:4130
Opcode getOpcode() const
Definition Expr.h:4089
A fixed int type of a specified bitwidth.
Definition TypeBase.h:8299
unsigned getNumBits() const
Definition TypeBase.h:8311
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:2895
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:1377
bool isStandardLayout() const
Determine whether this class is standard-layout per C++ [class]p7.
Definition DeclCXX.h:1230
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:563
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:2949
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3153
SourceLocation getBeginLoc() const
Definition Expr.h:3283
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3132
Expr * getCallee()
Definition Expr.h:3096
bool isCoroElideSafe() const
Definition Expr.h:3123
arg_range arguments()
Definition Expr.h:3201
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
Definition Expr.cpp:1609
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3682
path_iterator path_begin()
Definition Expr.h:3752
CastKind getCastKind() const
Definition Expr.h:3726
bool changesVolatileQualification() const
Return.
Definition Expr.h:3816
path_iterator path_end()
Definition Expr.h:3753
Expr * getSubExpr()
Definition Expr.h:3732
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.
std::optional< LValue > emitGlobalResourceArrayAsLValue(CodeGenFunction &CGF, const VarDecl *ArrayDecl)
RawAddress createBufferMatrixTempAddress(const LValue &LV, CodeGenFunction &CGF)
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:5213
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:3413
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:6810
llvm::Value * performAddrSpaceCast(llvm::Value *Src, llvm::Type *DestTy)
LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E)
Definition CGExpr.cpp:6110
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:7244
SanitizerSet SanOpts
Sanitizers enabled for this function.
LValue EmitInitListLValue(const InitListExpr *E)
Definition CGExpr.cpp:5992
bool isUnderlyingBasePointerConstantNull(const Expr *E)
Check whether the underlying base pointer is a constant null.
Definition CGExpr.cpp:5537
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:4978
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:6842
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:6823
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:3110
RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue, llvm::CallBase **CallOrInvoke)
LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E)
Definition CGExpr.cpp:3888
void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint=true)
LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E)
Definition CGExpr.cpp:5965
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:7196
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:3031
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:4040
LValue EmitCXXUuidofLValue(const CXXUuidofExpr *E)
Definition CGExpr.cpp:6828
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:7222
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:6502
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:7345
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:5660
const LangOptions & getLangOpts() const
void EmitCfiCheckFail()
Emit a cross-DSO CFI failure handling function.
Definition CGExpr.cpp:4408
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:7173
LValue EmitLValueForIvar(QualType ObjectTy, llvm::Value *Base, const ObjCIvarDecl *Ivar, unsigned CVRQualifiers)
Definition CGExpr.cpp:6876
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:6092
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:4928
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:3422
RValue EmitLoadOfGlobalRegLValue(LValue LV)
Load of global named registers are always calls to intrinsics.
Definition CGExpr.cpp:2746
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:6653
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:7350
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:3930
LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e)
Definition CGExpr.cpp:6348
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:6868
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:2501
LValue EmitLValueForField(LValue Base, const FieldDecl *Field, bool IsInBounds=true)
Definition CGExpr.cpp:5766
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:6376
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:6578
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:6452
RValue EmitLoadOfLValue(LValue V, SourceLocation Loc)
EmitLoadOfLValue - Given an expression that represents a value lvalue, this method emits the address ...
Definition CGExpr.cpp:2519
LValue EmitMatrixSingleSubscriptExpr(const MatrixSingleSubscriptExpr *E)
Definition CGExpr.cpp:5198
LValue EmitArraySectionExpr(const ArraySectionExpr *E, bool IsLowerBound=true)
Definition CGExpr.cpp:5275
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:4370
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:7211
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:3893
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:4188
LValue EmitDeclRefLValue(const DeclRefExpr *E)
Definition CGExpr.cpp:3597
LValue EmitStringLiteralLValue(const StringLiteral *E)
Definition CGExpr.cpp:3883
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:6405
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:5940
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:6391
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:5567
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:6768
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:6805
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:6908
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:6884
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:2770
Address EmitArrayToPointerDecay(const Expr *Array, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
Definition CGExpr.cpp:4620
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:6160
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:3432
llvm::Value * EmitCheckValue(llvm::Value *V)
Convert a value into a format suitable for passing to a runtime sanitizer handler.
Definition CGExpr.cpp:4002
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:5439
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:6354
LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E)
Definition CGExpr.cpp:6856
llvm::Type * ConvertTypeForMem(QualType T)
LValue EmitCallExprLValue(const CallExpr *E, llvm::CallBase **CallOrInvoke=nullptr)
Definition CGExpr.cpp:6790
RValue EmitLoadOfBitfieldLValue(LValue LV, SourceLocation Loc)
Definition CGExpr.cpp:2633
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:5654
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:6862
bool IsSanitizerScope
True if CodeGen currently emits code implementing sanitizer checks.
void FlattenAccessAndTypeLValue(LValue LVal, SmallVectorImpl< LValue > &AccessList)
Definition CGExpr.cpp:7354
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:4322
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:3816
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:3380
RValue EmitRValueForField(LValue LV, const FieldDecl *FD, SourceLocation Loc)
Definition CGExpr.cpp:6424
llvm::Value * EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr)
Definition CGObjC.cpp:2192
LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E)
Definition CGExpr.cpp:6834
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:2728
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:2670
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:4976
llvm::Value * EmitMatrixIndexExpr(const Expr *E)
Definition CGExpr.cpp:5190
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:4605
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:4527
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:4515
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:6819
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:5544
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:3220
bool isOpaqueValueEmitted(const OpaqueValueExpr *E)
isOpaqueValueEmitted - Return true if the opaque value expression has already been emitted.
Definition CGExpr.cpp:6418
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:3488
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:3339
QualType getElementType() const
Definition TypeBase.h:3349
CompoundLiteralExpr - [C99 6.5.2.5].
Definition Expr.h:3611
bool isFileScope() const
Definition Expr.h:3643
const Expr * getInitializer() const
Definition Expr.h:3639
ConstantExpr - An expression that occurs in a constant context and optionally the result of evaluatin...
Definition Expr.h:1088
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4451
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4470
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4467
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:1276
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition Expr.h:1480
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:494
ValueDecl * getDecl()
Definition Expr.h:1344
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition Expr.h:1474
SourceLocation getLocation() const
Definition Expr.h:1352
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:6584
ExplicitCastExpr - An explicit cast written in the source code.
Definition Expr.h:3934
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:85
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:3126
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:3099
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3095
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:1552
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:3697
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3079
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
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:3010
ExtVectorElementExpr - This represents access to specific elements of a vector, and may occur on the ...
Definition Expr.h:6613
bool isArrow() const
isArrow - Return true if the base expression is a pointer to vector, return false if the base express...
Definition Expr.cpp:4445
void getEncodedElementAccess(SmallVectorImpl< uint32_t > &Elts) const
getEncodedElementAccess - Encode the elements accessed into an llvm aggregate Constant of ConstantInt...
Definition Expr.cpp:4558
ExtVectorType - Extended vector type.
Definition TypeBase.h:4331
Represents a member of a struct/union/class.
Definition Decl.h:3190
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3293
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3275
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3426
const FieldDecl * findCountedByField() const
Find the FieldDecl specified in a FAM's "counted_by" attribute.
Definition Decl.cpp:4851
const Expr * getSubExpr() const
Definition Expr.h:1068
Represents a function declaration or definition.
Definition Decl.h:2026
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3738
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:5371
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4567
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:7400
const OpaqueValueExpr * getCastedTemporary() const
Definition Expr.h:7451
const OpaqueValueExpr * getOpaqueArgLValue() const
Definition Expr.h:7432
bool isInOut() const
returns true if the parameter is inout and false if the parameter is out.
Definition Expr.h:7459
const Expr * getWritebackCast() const
Definition Expr.h:7446
const Expr * getArgLValue() const
Return the l-value expression that was written as the argument in source.
Definition Expr.h:7441
static ImplicitParamDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, ImplicitParamKind ParamKind)
Create implicit parameter.
Definition Decl.cpp:5598
Describes an C or C++ initializer list.
Definition Expr.h:5305
bool isTransparent() const
Is this a transparent initializer list (that is, an InitListExpr that is purely syntactic,...
Definition Expr.cpp:2471
const Expr * getInit(unsigned Init) const
Definition Expr.h:5360
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:4590
MatrixSingleSubscriptExpr - Matrix single subscript expression for the MatrixType extension when you ...
Definition Expr.h:2801
MatrixSubscriptExpr - Matrix subscript expression for the MatrixType extension.
Definition Expr.h:2871
bool isIncomplete() const
Definition Expr.h:2891
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4415
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3370
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3453
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition Expr.h:3594
Expr * getBase() const
Definition Expr.h:3447
bool isArrow() const
Definition Expr.h:3554
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:3565
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3717
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:1184
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Definition Expr.h:1234
bool isUnique() const
Definition Expr.h:1242
const Expr * getSubExpr() const
Definition Expr.h:2205
Pointer-authentication qualifiers.
Definition TypeBase.h:152
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3392
QualType getPointeeType() const
Definition TypeBase.h:3402
[C99 6.4.2.2] - A predefined identifier such as func.
Definition Expr.h:2011
StringRef getIdentKindName() const
Definition Expr.h:2068
PredefinedIdentKind getIdentKind() const
Definition Expr.h:2046
StringLiteral * getFunctionName()
Definition Expr.h:2055
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:6807
semantics_iterator semantics_end()
Definition Expr.h:6872
semantics_iterator semantics_begin()
Definition Expr.h:6868
const Expr *const * const_semantics_iterator
Definition Expr.h:6867
Expr * getResultExpr()
Return the result-bearing expression, or null if there is none.
Definition Expr.h:6855
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8531
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:8573
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8487
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:8632
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8541
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:4355
field_range fields() const
Definition Decl.h:4558
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4539
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition Decl.h:4407
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:4601
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:1805
bool isUnion() const
Definition Decl.h:3958
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:8704
bool isVoidType() const
Definition TypeBase.h:9050
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:9353
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:8787
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isArrayType() const
Definition TypeBase.h:8783
bool isFunctionPointerType() const
Definition TypeBase.h:8751
CXXRecordDecl * castAsCXXRecordDecl() const
Definition Type.h:36
bool isArithmeticType() const
Definition Type.cpp:2422
bool isConstantMatrixType() const
Definition TypeBase.h:8851
bool isPointerType() const
Definition TypeBase.h:8684
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9094
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9344
bool isReferenceType() const
Definition TypeBase.h:8708
bool isEnumeralType() const
Definition TypeBase.h:8815
bool isVariableArrayType() const
Definition TypeBase.h:8795
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:8831
bool isBitIntType() const
Definition TypeBase.h:8959
bool isConstantMatrixBoolType() const
Definition TypeBase.h:8837
bool isAnyComplexType() const
Definition TypeBase.h:8819
bool hasPointeeToCFIUncheckedCalleeFunctionType() const
Definition TypeBase.h:8736
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition TypeBase.h:9230
bool isAtomicType() const
Definition TypeBase.h:8876
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2864
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2570
bool isHLSLResourceRecord() const
Definition Type.cpp:5510
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:8680
bool isObjCObjectPointerType() const
Definition TypeBase.h:8863
bool isVectorType() const
Definition TypeBase.h:8823
bool isAnyPointerType() const
Definition TypeBase.h:8692
bool isSubscriptableVectorType() const
Definition TypeBase.h:8843
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9277
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:8811
bool isHLSLResourceRecordArray() const
Definition Type.cpp:5514
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:8730
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2250
SourceLocation getExprLoc() const
Definition Expr.h:2374
Expr * getSubExpr() const
Definition Expr.h:2291
Opcode getOpcode() const
Definition Expr.h:2286
Represents a call to the builtin function __builtin_va_arg.
Definition Expr.h:4963
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:238
Represents a variable declaration or definition.
Definition Decl.h:932
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:1190
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition Decl.h:958
@ TLS_None
Not a TLS variable.
Definition Decl.h:952
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:4030
Represents a GCC generic vector type.
Definition TypeBase.h:4239
unsigned getNumElements() const
Definition TypeBase.h:4254
#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:147
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:5975
bool isLambdaMethod(const DeclContext *DC)
Definition ASTLambda.h:39
@ Other
Other implicit parameter.
Definition Decl.h:1771
@ 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,...
__packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 __packed_splat4 uint16_t
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:652
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:654
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