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