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