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