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