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