1 //===--- CGExpr.cpp - Emit LLVM Code from Expressions ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This contains code to emit Expr nodes as LLVM code.
12 //===----------------------------------------------------------------------===//
16 #include "CGCleanup.h"
17 #include "CGDebugInfo.h"
18 #include "CGObjCRuntime.h"
19 #include "CGOpenMPRuntime.h"
20 #include "CGRecordLayout.h"
21 #include "CodeGenFunction.h"
22 #include "CodeGenModule.h"
23 #include "ConstantEmitter.h"
24 #include "TargetInfo.h"
25 #include "clang/AST/ASTContext.h"
26 #include "clang/AST/Attr.h"
27 #include "clang/AST/DeclObjC.h"
28 #include "clang/AST/NSAPI.h"
29 #include "clang/Frontend/CodeGenOptions.h"
30 #include "llvm/ADT/Hashing.h"
31 #include "llvm/ADT/StringExtras.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/Intrinsics.h"
34 #include "llvm/IR/LLVMContext.h"
35 #include "llvm/IR/MDBuilder.h"
36 #include "llvm/Support/ConvertUTF.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/Path.h"
39 #include "llvm/Transforms/Utils/SanitizerStats.h"
43 using namespace clang;
44 using namespace CodeGen;
46 //===--------------------------------------------------------------------===//
47 // Miscellaneous Helper Methods
48 //===--------------------------------------------------------------------===//
50 llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) {
51 unsigned addressSpace =
52 cast<llvm::PointerType>(value->getType())->getAddressSpace();
54 llvm::PointerType *destType = Int8PtrTy;
56 destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace);
58 if (value->getType() == destType) return value;
59 return Builder.CreateBitCast(value, destType);
62 /// CreateTempAlloca - This creates a alloca and inserts it into the entry
64 Address CodeGenFunction::CreateTempAlloca(llvm::Type *Ty, CharUnits Align,
66 llvm::Value *ArraySize,
67 bool CastToDefaultAddrSpace) {
68 auto Alloca = CreateTempAlloca(Ty, Name, ArraySize);
69 Alloca->setAlignment(Align.getQuantity());
70 llvm::Value *V = Alloca;
71 // Alloca always returns a pointer in alloca address space, which may
72 // be different from the type defined by the language. For example,
73 // in C++ the auto variables are in the default address space. Therefore
74 // cast alloca to the default address space when necessary.
75 if (CastToDefaultAddrSpace && getASTAllocaAddressSpace() != LangAS::Default) {
76 auto DestAddrSpace = getContext().getTargetAddressSpace(LangAS::Default);
77 llvm::IRBuilderBase::InsertPointGuard IPG(Builder);
78 // When ArraySize is nullptr, alloca is inserted at AllocaInsertPt,
79 // otherwise alloca is inserted at the current insertion point of the
82 Builder.SetInsertPoint(AllocaInsertPt);
83 V = getTargetHooks().performAddrSpaceCast(
84 *this, V, getASTAllocaAddressSpace(), LangAS::Default,
85 Ty->getPointerTo(DestAddrSpace), /*non-null*/ true);
88 return Address(V, Align);
91 /// CreateTempAlloca - This creates an alloca and inserts it into the entry
92 /// block if \p ArraySize is nullptr, otherwise inserts it at the current
93 /// insertion point of the builder.
94 llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
96 llvm::Value *ArraySize) {
98 return Builder.CreateAlloca(Ty, ArraySize, Name);
99 return new llvm::AllocaInst(Ty, CGM.getDataLayout().getAllocaAddrSpace(),
100 ArraySize, Name, AllocaInsertPt);
103 /// CreateDefaultAlignTempAlloca - This creates an alloca with the
104 /// default alignment of the corresponding LLVM type, which is *not*
105 /// guaranteed to be related in any way to the expected alignment of
106 /// an AST type that might have been lowered to Ty.
107 Address CodeGenFunction::CreateDefaultAlignTempAlloca(llvm::Type *Ty,
110 CharUnits::fromQuantity(CGM.getDataLayout().getABITypeAlignment(Ty));
111 return CreateTempAlloca(Ty, Align, Name);
114 void CodeGenFunction::InitTempAlloca(Address Var, llvm::Value *Init) {
115 assert(isa<llvm::AllocaInst>(Var.getPointer()));
116 auto *Store = new llvm::StoreInst(Init, Var.getPointer());
117 Store->setAlignment(Var.getAlignment().getQuantity());
118 llvm::BasicBlock *Block = AllocaInsertPt->getParent();
119 Block->getInstList().insertAfter(AllocaInsertPt->getIterator(), Store);
122 Address CodeGenFunction::CreateIRTemp(QualType Ty, const Twine &Name) {
123 CharUnits Align = getContext().getTypeAlignInChars(Ty);
124 return CreateTempAlloca(ConvertType(Ty), Align, Name);
127 Address CodeGenFunction::CreateMemTemp(QualType Ty, const Twine &Name,
128 bool CastToDefaultAddrSpace) {
129 // FIXME: Should we prefer the preferred type alignment here?
130 return CreateMemTemp(Ty, getContext().getTypeAlignInChars(Ty), Name,
131 CastToDefaultAddrSpace);
134 Address CodeGenFunction::CreateMemTemp(QualType Ty, CharUnits Align,
136 bool CastToDefaultAddrSpace) {
137 return CreateTempAlloca(ConvertTypeForMem(Ty), Align, Name, nullptr,
138 CastToDefaultAddrSpace);
141 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
142 /// expression and compare the result against zero, returning an Int1Ty value.
143 llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
144 PGO.setCurrentStmt(E);
145 if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
146 llvm::Value *MemPtr = EmitScalarExpr(E);
147 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
150 QualType BoolTy = getContext().BoolTy;
151 SourceLocation Loc = E->getExprLoc();
152 if (!E->getType()->isAnyComplexType())
153 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy, Loc);
155 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(), BoolTy,
159 /// EmitIgnoredExpr - Emit code to compute the specified expression,
160 /// ignoring the result.
161 void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
163 return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
165 // Just emit it as an l-value and drop the result.
169 /// EmitAnyExpr - Emit code to compute the specified expression which
170 /// can have any type. The result is returned as an RValue struct.
171 /// If this is an aggregate expression, AggSlot indicates where the
172 /// result should be returned.
173 RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
174 AggValueSlot aggSlot,
176 switch (getEvaluationKind(E->getType())) {
178 return RValue::get(EmitScalarExpr(E, ignoreResult));
180 return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
182 if (!ignoreResult && aggSlot.isIgnored())
183 aggSlot = CreateAggTemp(E->getType(), "agg-temp");
184 EmitAggExpr(E, aggSlot);
185 return aggSlot.asRValue();
187 llvm_unreachable("bad evaluation kind");
190 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
191 /// always be accessible even if no aggregate location is provided.
192 RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
193 AggValueSlot AggSlot = AggValueSlot::ignored();
195 if (hasAggregateEvaluationKind(E->getType()))
196 AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
197 return EmitAnyExpr(E, AggSlot);
200 /// EmitAnyExprToMem - Evaluate an expression into a given memory
202 void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
206 // FIXME: This function should take an LValue as an argument.
207 switch (getEvaluationKind(E->getType())) {
209 EmitComplexExprIntoLValue(E, MakeAddrLValue(Location, E->getType()),
213 case TEK_Aggregate: {
214 EmitAggExpr(E, AggValueSlot::forAddr(Location, Quals,
215 AggValueSlot::IsDestructed_t(IsInit),
216 AggValueSlot::DoesNotNeedGCBarriers,
217 AggValueSlot::IsAliased_t(!IsInit)));
222 RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
223 LValue LV = MakeAddrLValue(Location, E->getType());
224 EmitStoreThroughLValue(RV, LV);
228 llvm_unreachable("bad evaluation kind");
232 pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M,
233 const Expr *E, Address ReferenceTemporary) {
234 // Objective-C++ ARC:
235 // If we are binding a reference to a temporary that has ownership, we
236 // need to perform retain/release operations on the temporary.
238 // FIXME: This should be looking at E, not M.
239 if (auto Lifetime = M->getType().getObjCLifetime()) {
241 case Qualifiers::OCL_None:
242 case Qualifiers::OCL_ExplicitNone:
243 // Carry on to normal cleanup handling.
246 case Qualifiers::OCL_Autoreleasing:
247 // Nothing to do; cleaned up by an autorelease pool.
250 case Qualifiers::OCL_Strong:
251 case Qualifiers::OCL_Weak:
252 switch (StorageDuration Duration = M->getStorageDuration()) {
254 // Note: we intentionally do not register a cleanup to release
255 // the object on program termination.
259 // FIXME: We should probably register a cleanup in this case.
263 case SD_FullExpression:
264 CodeGenFunction::Destroyer *Destroy;
265 CleanupKind CleanupKind;
266 if (Lifetime == Qualifiers::OCL_Strong) {
267 const ValueDecl *VD = M->getExtendingDecl();
269 VD && isa<VarDecl>(VD) && VD->hasAttr<ObjCPreciseLifetimeAttr>();
270 CleanupKind = CGF.getARCCleanupKind();
271 Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise
272 : &CodeGenFunction::destroyARCStrongImprecise;
274 // __weak objects always get EH cleanups; otherwise, exceptions
275 // could cause really nasty crashes instead of mere leaks.
276 CleanupKind = NormalAndEHCleanup;
277 Destroy = &CodeGenFunction::destroyARCWeak;
279 if (Duration == SD_FullExpression)
280 CGF.pushDestroy(CleanupKind, ReferenceTemporary,
281 M->getType(), *Destroy,
282 CleanupKind & EHCleanup);
284 CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
286 *Destroy, CleanupKind & EHCleanup);
290 llvm_unreachable("temporary cannot have dynamic storage duration");
292 llvm_unreachable("unknown storage duration");
296 CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
297 if (const RecordType *RT =
298 E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
299 // Get the destructor for the reference temporary.
300 auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
301 if (!ClassDecl->hasTrivialDestructor())
302 ReferenceTemporaryDtor = ClassDecl->getDestructor();
305 if (!ReferenceTemporaryDtor)
308 // Call the destructor for the temporary.
309 switch (M->getStorageDuration()) {
312 llvm::Constant *CleanupFn;
313 llvm::Constant *CleanupArg;
314 if (E->getType()->isArrayType()) {
315 CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper(
316 ReferenceTemporary, E->getType(),
317 CodeGenFunction::destroyCXXObject, CGF.getLangOpts().Exceptions,
318 dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
319 CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
321 CleanupFn = CGF.CGM.getAddrOfCXXStructor(ReferenceTemporaryDtor,
322 StructorType::Complete);
323 CleanupArg = cast<llvm::Constant>(ReferenceTemporary.getPointer());
325 CGF.CGM.getCXXABI().registerGlobalDtor(
326 CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
330 case SD_FullExpression:
331 CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(),
332 CodeGenFunction::destroyCXXObject,
333 CGF.getLangOpts().Exceptions);
337 CGF.pushLifetimeExtendedDestroy(NormalAndEHCleanup,
338 ReferenceTemporary, E->getType(),
339 CodeGenFunction::destroyCXXObject,
340 CGF.getLangOpts().Exceptions);
344 llvm_unreachable("temporary cannot have dynamic storage duration");
348 static Address createReferenceTemporary(CodeGenFunction &CGF,
349 const MaterializeTemporaryExpr *M,
351 auto &TCG = CGF.getTargetHooks();
352 switch (M->getStorageDuration()) {
353 case SD_FullExpression:
355 // If we have a constant temporary array or record try to promote it into a
356 // constant global under the same rules a normal constant would've been
357 // promoted. This is easier on the optimizer and generally emits fewer
359 QualType Ty = Inner->getType();
360 if (CGF.CGM.getCodeGenOpts().MergeAllConstants &&
361 (Ty->isArrayType() || Ty->isRecordType()) &&
362 CGF.CGM.isTypeConstant(Ty, true))
363 if (auto Init = ConstantEmitter(CGF).tryEmitAbstract(Inner, Ty)) {
364 if (auto AddrSpace = CGF.getTarget().getConstantAddressSpace()) {
365 auto AS = AddrSpace.getValue();
366 auto *GV = new llvm::GlobalVariable(
367 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
368 llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp", nullptr,
369 llvm::GlobalValue::NotThreadLocal,
370 CGF.getContext().getTargetAddressSpace(AS));
371 CharUnits alignment = CGF.getContext().getTypeAlignInChars(Ty);
372 GV->setAlignment(alignment.getQuantity());
373 llvm::Constant *C = GV;
374 if (AS != LangAS::Default)
375 C = TCG.performAddrSpaceCast(
376 CGF.CGM, GV, AS, LangAS::Default,
377 GV->getValueType()->getPointerTo(
378 CGF.getContext().getTargetAddressSpace(LangAS::Default)));
379 // FIXME: Should we put the new global into a COMDAT?
380 return Address(C, alignment);
383 return CGF.CreateMemTemp(Ty, "ref.tmp");
387 return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
390 llvm_unreachable("temporary can't have dynamic storage duration");
392 llvm_unreachable("unknown storage duration");
395 LValue CodeGenFunction::
396 EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *M) {
397 const Expr *E = M->GetTemporaryExpr();
399 // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
400 // as that will cause the lifetime adjustment to be lost for ARC
401 auto ownership = M->getType().getObjCLifetime();
402 if (ownership != Qualifiers::OCL_None &&
403 ownership != Qualifiers::OCL_ExplicitNone) {
404 Address Object = createReferenceTemporary(*this, M, E);
405 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
406 Object = Address(llvm::ConstantExpr::getBitCast(Var,
407 ConvertTypeForMem(E->getType())
408 ->getPointerTo(Object.getAddressSpace())),
409 Object.getAlignment());
411 // createReferenceTemporary will promote the temporary to a global with a
412 // constant initializer if it can. It can only do this to a value of
413 // ARC-manageable type if the value is global and therefore "immune" to
414 // ref-counting operations. Therefore we have no need to emit either a
415 // dynamic initialization or a cleanup and we can just return the address
417 if (Var->hasInitializer())
418 return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
420 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
422 LValue RefTempDst = MakeAddrLValue(Object, M->getType(),
423 AlignmentSource::Decl);
425 switch (getEvaluationKind(E->getType())) {
426 default: llvm_unreachable("expected scalar or aggregate expression");
428 EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
430 case TEK_Aggregate: {
431 EmitAggExpr(E, AggValueSlot::forAddr(Object,
432 E->getType().getQualifiers(),
433 AggValueSlot::IsDestructed,
434 AggValueSlot::DoesNotNeedGCBarriers,
435 AggValueSlot::IsNotAliased));
440 pushTemporaryCleanup(*this, M, E, Object);
444 SmallVector<const Expr *, 2> CommaLHSs;
445 SmallVector<SubobjectAdjustment, 2> Adjustments;
446 E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
448 for (const auto &Ignored : CommaLHSs)
449 EmitIgnoredExpr(Ignored);
451 if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
452 if (opaque->getType()->isRecordType()) {
453 assert(Adjustments.empty());
454 return EmitOpaqueValueLValue(opaque);
458 // Create and initialize the reference temporary.
459 Address Object = createReferenceTemporary(*this, M, E);
460 if (auto *Var = dyn_cast<llvm::GlobalVariable>(
461 Object.getPointer()->stripPointerCasts())) {
462 Object = Address(llvm::ConstantExpr::getBitCast(
463 cast<llvm::Constant>(Object.getPointer()),
464 ConvertTypeForMem(E->getType())->getPointerTo()),
465 Object.getAlignment());
466 // If the temporary is a global and has a constant initializer or is a
467 // constant temporary that we promoted to a global, we may have already
469 if (!Var->hasInitializer()) {
470 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
471 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
474 switch (M->getStorageDuration()) {
476 case SD_FullExpression:
477 if (auto *Size = EmitLifetimeStart(
478 CGM.getDataLayout().getTypeAllocSize(Object.getElementType()),
479 Object.getPointer())) {
480 if (M->getStorageDuration() == SD_Automatic)
481 pushCleanupAfterFullExpr<CallLifetimeEnd>(NormalEHLifetimeMarker,
484 pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, Object,
491 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
493 pushTemporaryCleanup(*this, M, E, Object);
495 // Perform derived-to-base casts and/or field accesses, to get from the
496 // temporary object we created (and, potentially, for which we extended
497 // the lifetime) to the subobject we're binding the reference to.
498 for (unsigned I = Adjustments.size(); I != 0; --I) {
499 SubobjectAdjustment &Adjustment = Adjustments[I-1];
500 switch (Adjustment.Kind) {
501 case SubobjectAdjustment::DerivedToBaseAdjustment:
503 GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
504 Adjustment.DerivedToBase.BasePath->path_begin(),
505 Adjustment.DerivedToBase.BasePath->path_end(),
506 /*NullCheckValue=*/ false, E->getExprLoc());
509 case SubobjectAdjustment::FieldAdjustment: {
510 LValue LV = MakeAddrLValue(Object, E->getType(), AlignmentSource::Decl);
511 LV = EmitLValueForField(LV, Adjustment.Field);
512 assert(LV.isSimple() &&
513 "materialized temporary field is not a simple lvalue");
514 Object = LV.getAddress();
518 case SubobjectAdjustment::MemberPointerAdjustment: {
519 llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
520 Object = EmitCXXMemberDataPointerAddress(E, Object, Ptr,
527 return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
531 CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) {
532 // Emit the expression as an lvalue.
533 LValue LV = EmitLValue(E);
534 assert(LV.isSimple());
535 llvm::Value *Value = LV.getPointer();
537 if (sanitizePerformTypeCheck() && !E->getType()->isFunctionType()) {
538 // C++11 [dcl.ref]p5 (as amended by core issue 453):
539 // If a glvalue to which a reference is directly bound designates neither
540 // an existing object or function of an appropriate type nor a region of
541 // storage of suitable size and alignment to contain an object of the
542 // reference's type, the behavior is undefined.
543 QualType Ty = E->getType();
544 EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
547 return RValue::get(Value);
551 /// getAccessedFieldNo - Given an encoded value and a result number, return the
552 /// input field number being accessed.
553 unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
554 const llvm::Constant *Elts) {
555 return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
559 /// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
560 static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
562 llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
563 llvm::Value *K47 = Builder.getInt64(47);
564 llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
565 llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
566 llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
567 llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
568 return Builder.CreateMul(B1, KMul);
571 bool CodeGenFunction::isNullPointerAllowed(TypeCheckKind TCK) {
572 return TCK == TCK_DowncastPointer || TCK == TCK_Upcast ||
573 TCK == TCK_UpcastToVirtualBase || TCK == TCK_DynamicOperation;
576 bool CodeGenFunction::isVptrCheckRequired(TypeCheckKind TCK, QualType Ty) {
577 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
578 return (RD && RD->hasDefinition() && RD->isDynamicClass()) &&
579 (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
580 TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
581 TCK == TCK_UpcastToVirtualBase || TCK == TCK_DynamicOperation);
584 bool CodeGenFunction::sanitizePerformTypeCheck() const {
585 return SanOpts.has(SanitizerKind::Null) |
586 SanOpts.has(SanitizerKind::Alignment) |
587 SanOpts.has(SanitizerKind::ObjectSize) |
588 SanOpts.has(SanitizerKind::Vptr);
591 void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
592 llvm::Value *Ptr, QualType Ty,
594 SanitizerSet SkippedChecks) {
595 if (!sanitizePerformTypeCheck())
598 // Don't check pointers outside the default address space. The null check
599 // isn't correct, the object-size check isn't supported by LLVM, and we can't
600 // communicate the addresses to the runtime handler for the vptr check.
601 if (Ptr->getType()->getPointerAddressSpace())
604 // Don't check pointers to volatile data. The behavior here is implementation-
606 if (Ty.isVolatileQualified())
609 SanitizerScope SanScope(this);
611 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 3> Checks;
612 llvm::BasicBlock *Done = nullptr;
614 // Quickly determine whether we have a pointer to an alloca. It's possible
615 // to skip null checks, and some alignment checks, for these pointers. This
616 // can reduce compile-time significantly.
618 dyn_cast<llvm::AllocaInst>(Ptr->stripPointerCastsNoFollowAliases());
620 llvm::Value *True = llvm::ConstantInt::getTrue(getLLVMContext());
621 llvm::Value *IsNonNull = nullptr;
622 bool IsGuaranteedNonNull =
623 SkippedChecks.has(SanitizerKind::Null) || PtrToAlloca;
624 bool AllowNullPointers = isNullPointerAllowed(TCK);
625 if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
626 !IsGuaranteedNonNull) {
627 // The glvalue must not be an empty glvalue.
628 IsNonNull = Builder.CreateIsNotNull(Ptr);
630 // The IR builder can constant-fold the null check if the pointer points to
632 IsGuaranteedNonNull = IsNonNull == True;
634 // Skip the null check if the pointer is known to be non-null.
635 if (!IsGuaranteedNonNull) {
636 if (AllowNullPointers) {
637 // When performing pointer casts, it's OK if the value is null.
638 // Skip the remaining checks in that case.
639 Done = createBasicBlock("null");
640 llvm::BasicBlock *Rest = createBasicBlock("not.null");
641 Builder.CreateCondBr(IsNonNull, Rest, Done);
644 Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null));
649 if (SanOpts.has(SanitizerKind::ObjectSize) &&
650 !SkippedChecks.has(SanitizerKind::ObjectSize) &&
651 !Ty->isIncompleteType()) {
652 uint64_t Size = getContext().getTypeSizeInChars(Ty).getQuantity();
654 // The glvalue must refer to a large enough storage region.
655 // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
657 // FIXME: Get object address space
658 llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
659 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
660 llvm::Value *Min = Builder.getFalse();
661 llvm::Value *NullIsUnknown = Builder.getFalse();
662 llvm::Value *CastAddr = Builder.CreateBitCast(Ptr, Int8PtrTy);
663 llvm::Value *LargeEnough = Builder.CreateICmpUGE(
664 Builder.CreateCall(F, {CastAddr, Min, NullIsUnknown}),
665 llvm::ConstantInt::get(IntPtrTy, Size));
666 Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
669 uint64_t AlignVal = 0;
670 llvm::Value *PtrAsInt = nullptr;
672 if (SanOpts.has(SanitizerKind::Alignment) &&
673 !SkippedChecks.has(SanitizerKind::Alignment)) {
674 AlignVal = Alignment.getQuantity();
675 if (!Ty->isIncompleteType() && !AlignVal)
676 AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity();
678 // The glvalue must be suitably aligned.
680 (!PtrToAlloca || PtrToAlloca->getAlignment() < AlignVal)) {
681 PtrAsInt = Builder.CreatePtrToInt(Ptr, IntPtrTy);
682 llvm::Value *Align = Builder.CreateAnd(
683 PtrAsInt, llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
684 llvm::Value *Aligned =
685 Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
687 Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
691 if (Checks.size() > 0) {
692 // Make sure we're not losing information. Alignment needs to be a power of
694 assert(!AlignVal || (uint64_t)1 << llvm::Log2_64(AlignVal) == AlignVal);
695 llvm::Constant *StaticData[] = {
696 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(Ty),
697 llvm::ConstantInt::get(Int8Ty, AlignVal ? llvm::Log2_64(AlignVal) : 1),
698 llvm::ConstantInt::get(Int8Ty, TCK)};
699 EmitCheck(Checks, SanitizerHandler::TypeMismatch, StaticData,
700 PtrAsInt ? PtrAsInt : Ptr);
703 // If possible, check that the vptr indicates that there is a subobject of
704 // type Ty at offset zero within this object.
706 // C++11 [basic.life]p5,6:
707 // [For storage which does not refer to an object within its lifetime]
708 // The program has undefined behavior if:
709 // -- the [pointer or glvalue] is used to access a non-static data member
710 // or call a non-static member function
711 if (SanOpts.has(SanitizerKind::Vptr) &&
712 !SkippedChecks.has(SanitizerKind::Vptr) && isVptrCheckRequired(TCK, Ty)) {
713 // Ensure that the pointer is non-null before loading it. If there is no
714 // compile-time guarantee, reuse the run-time null check or emit a new one.
715 if (!IsGuaranteedNonNull) {
717 IsNonNull = Builder.CreateIsNotNull(Ptr);
719 Done = createBasicBlock("vptr.null");
720 llvm::BasicBlock *VptrNotNull = createBasicBlock("vptr.not.null");
721 Builder.CreateCondBr(IsNonNull, VptrNotNull, Done);
722 EmitBlock(VptrNotNull);
725 // Compute a hash of the mangled name of the type.
727 // FIXME: This is not guaranteed to be deterministic! Move to a
728 // fingerprinting mechanism once LLVM provides one. For the time
729 // being the implementation happens to be deterministic.
730 SmallString<64> MangledName;
731 llvm::raw_svector_ostream Out(MangledName);
732 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
735 // Blacklist based on the mangled type.
736 if (!CGM.getContext().getSanitizerBlacklist().isBlacklistedType(
737 SanitizerKind::Vptr, Out.str())) {
738 llvm::hash_code TypeHash = hash_value(Out.str());
740 // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
741 llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
742 llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
743 Address VPtrAddr(Builder.CreateBitCast(Ptr, VPtrTy), getPointerAlign());
744 llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
745 llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
747 llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
748 Hash = Builder.CreateTrunc(Hash, IntPtrTy);
750 // Look the hash up in our cache.
751 const int CacheSize = 128;
752 llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
753 llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
754 "__ubsan_vptr_type_cache");
755 llvm::Value *Slot = Builder.CreateAnd(Hash,
756 llvm::ConstantInt::get(IntPtrTy,
758 llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
759 llvm::Value *CacheVal =
760 Builder.CreateAlignedLoad(Builder.CreateInBoundsGEP(Cache, Indices),
763 // If the hash isn't in the cache, call a runtime handler to perform the
764 // hard work of checking whether the vptr is for an object of the right
765 // type. This will either fill in the cache and return, or produce a
767 llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
768 llvm::Constant *StaticData[] = {
769 EmitCheckSourceLocation(Loc),
770 EmitCheckTypeDescriptor(Ty),
771 CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
772 llvm::ConstantInt::get(Int8Ty, TCK)
774 llvm::Value *DynamicData[] = { Ptr, Hash };
775 EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
776 SanitizerHandler::DynamicTypeCacheMiss, StaticData,
782 Builder.CreateBr(Done);
787 /// Determine whether this expression refers to a flexible array member in a
788 /// struct. We disable array bounds checks for such members.
789 static bool isFlexibleArrayMemberExpr(const Expr *E) {
790 // For compatibility with existing code, we treat arrays of length 0 or
791 // 1 as flexible array members.
792 const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe();
793 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
794 if (CAT->getSize().ugt(1))
796 } else if (!isa<IncompleteArrayType>(AT))
799 E = E->IgnoreParens();
801 // A flexible array member must be the last member in the class.
802 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
803 // FIXME: If the base type of the member expr is not FD->getParent(),
804 // this should not be treated as a flexible array member access.
805 if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
806 RecordDecl::field_iterator FI(
807 DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
808 return ++FI == FD->getParent()->field_end();
810 } else if (const auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) {
811 return IRE->getDecl()->getNextIvar() == nullptr;
817 llvm::Value *CodeGenFunction::LoadPassedObjectSize(const Expr *E,
819 ASTContext &C = getContext();
820 uint64_t EltSize = C.getTypeSizeInChars(EltTy).getQuantity();
824 auto *ArrayDeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
828 auto *ParamDecl = dyn_cast<ParmVarDecl>(ArrayDeclRef->getDecl());
832 auto *POSAttr = ParamDecl->getAttr<PassObjectSizeAttr>();
836 // Don't load the size if it's a lower bound.
837 int POSType = POSAttr->getType();
838 if (POSType != 0 && POSType != 1)
841 // Find the implicit size parameter.
842 auto PassedSizeIt = SizeArguments.find(ParamDecl);
843 if (PassedSizeIt == SizeArguments.end())
846 const ImplicitParamDecl *PassedSizeDecl = PassedSizeIt->second;
847 assert(LocalDeclMap.count(PassedSizeDecl) && "Passed size not loadable");
848 Address AddrOfSize = LocalDeclMap.find(PassedSizeDecl)->second;
849 llvm::Value *SizeInBytes = EmitLoadOfScalar(AddrOfSize, /*Volatile=*/false,
850 C.getSizeType(), E->getExprLoc());
851 llvm::Value *SizeOfElement =
852 llvm::ConstantInt::get(SizeInBytes->getType(), EltSize);
853 return Builder.CreateUDiv(SizeInBytes, SizeOfElement);
856 /// If Base is known to point to the start of an array, return the length of
857 /// that array. Return 0 if the length cannot be determined.
858 static llvm::Value *getArrayIndexingBound(
859 CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType) {
860 // For the vector indexing extension, the bound is the number of elements.
861 if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
862 IndexedType = Base->getType();
863 return CGF.Builder.getInt32(VT->getNumElements());
866 Base = Base->IgnoreParens();
868 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
869 if (CE->getCastKind() == CK_ArrayToPointerDecay &&
870 !isFlexibleArrayMemberExpr(CE->getSubExpr())) {
871 IndexedType = CE->getSubExpr()->getType();
872 const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
873 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
874 return CGF.Builder.getInt(CAT->getSize());
875 else if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
876 return CGF.getVLASize(VAT).first;
877 // Ignore pass_object_size here. It's not applicable on decayed pointers.
881 QualType EltTy{Base->getType()->getPointeeOrArrayElementType(), 0};
882 if (llvm::Value *POS = CGF.LoadPassedObjectSize(Base, EltTy)) {
883 IndexedType = Base->getType();
890 void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
891 llvm::Value *Index, QualType IndexType,
893 assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
894 "should not be called unless adding bounds checks");
895 SanitizerScope SanScope(this);
897 QualType IndexedType;
898 llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType);
902 bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
903 llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
904 llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
906 llvm::Constant *StaticData[] = {
907 EmitCheckSourceLocation(E->getExprLoc()),
908 EmitCheckTypeDescriptor(IndexedType),
909 EmitCheckTypeDescriptor(IndexType)
911 llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
912 : Builder.CreateICmpULE(IndexVal, BoundVal);
913 EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds),
914 SanitizerHandler::OutOfBounds, StaticData, Index);
918 CodeGenFunction::ComplexPairTy CodeGenFunction::
919 EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
920 bool isInc, bool isPre) {
921 ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
923 llvm::Value *NextVal;
924 if (isa<llvm::IntegerType>(InVal.first->getType())) {
925 uint64_t AmountVal = isInc ? 1 : -1;
926 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
928 // Add the inc/dec to the real part.
929 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
931 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
932 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
935 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
937 // Add the inc/dec to the real part.
938 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
941 ComplexPairTy IncVal(NextVal, InVal.second);
943 // Store the updated result through the lvalue.
944 EmitStoreOfComplex(IncVal, LV, /*init*/ false);
946 // If this is a postinc, return the value read from memory, otherwise use the
948 return isPre ? IncVal : InVal;
951 void CodeGenModule::EmitExplicitCastExprType(const ExplicitCastExpr *E,
952 CodeGenFunction *CGF) {
953 // Bind VLAs in the cast type.
954 if (CGF && E->getType()->isVariablyModifiedType())
955 CGF->EmitVariablyModifiedType(E->getType());
957 if (CGDebugInfo *DI = getModuleDebugInfo())
958 DI->EmitExplicitCastType(E->getType());
961 //===----------------------------------------------------------------------===//
962 // LValue Expression Emission
963 //===----------------------------------------------------------------------===//
965 /// EmitPointerWithAlignment - Given an expression of pointer type, try to
966 /// derive a more accurate bound on the alignment of the pointer.
967 Address CodeGenFunction::EmitPointerWithAlignment(const Expr *E,
968 LValueBaseInfo *BaseInfo,
969 TBAAAccessInfo *TBAAInfo) {
970 // We allow this with ObjC object pointers because of fragile ABIs.
971 assert(E->getType()->isPointerType() ||
972 E->getType()->isObjCObjectPointerType());
973 E = E->IgnoreParens();
976 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
977 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
978 CGM.EmitExplicitCastExprType(ECE, this);
980 switch (CE->getCastKind()) {
981 // Non-converting casts (but not C's implicit conversion from void*).
984 case CK_AddressSpaceConversion:
985 if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) {
986 if (PtrTy->getPointeeType()->isVoidType())
989 LValueBaseInfo InnerBaseInfo;
990 TBAAAccessInfo InnerTBAAInfo;
991 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(),
994 if (BaseInfo) *BaseInfo = InnerBaseInfo;
995 if (TBAAInfo) *TBAAInfo = InnerTBAAInfo;
997 if (isa<ExplicitCastExpr>(CE)) {
998 LValueBaseInfo TargetTypeBaseInfo;
999 TBAAAccessInfo TargetTypeTBAAInfo;
1000 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(),
1001 &TargetTypeBaseInfo,
1002 &TargetTypeTBAAInfo);
1004 *TBAAInfo = CGM.mergeTBAAInfoForCast(*TBAAInfo,
1005 TargetTypeTBAAInfo);
1006 // If the source l-value is opaque, honor the alignment of the
1008 if (InnerBaseInfo.getAlignmentSource() != AlignmentSource::Decl) {
1010 BaseInfo->mergeForCast(TargetTypeBaseInfo);
1011 Addr = Address(Addr.getPointer(), Align);
1015 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast) &&
1016 CE->getCastKind() == CK_BitCast) {
1017 if (auto PT = E->getType()->getAs<PointerType>())
1018 EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr.getPointer(),
1020 CodeGenFunction::CFITCK_UnrelatedCast,
1023 return CE->getCastKind() != CK_AddressSpaceConversion
1024 ? Builder.CreateBitCast(Addr, ConvertType(E->getType()))
1025 : Builder.CreateAddrSpaceCast(Addr,
1026 ConvertType(E->getType()));
1030 // Array-to-pointer decay.
1031 case CK_ArrayToPointerDecay:
1032 return EmitArrayToPointerDecay(CE->getSubExpr(), BaseInfo, TBAAInfo);
1034 // Derived-to-base conversions.
1035 case CK_UncheckedDerivedToBase:
1036 case CK_DerivedToBase: {
1037 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), BaseInfo,
1039 auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
1040 return GetAddressOfBaseClass(Addr, Derived,
1041 CE->path_begin(), CE->path_end(),
1042 ShouldNullCheckClassCastValue(CE),
1046 // TODO: Is there any reason to treat base-to-derived conversions
1054 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1055 if (UO->getOpcode() == UO_AddrOf) {
1056 LValue LV = EmitLValue(UO->getSubExpr());
1057 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
1058 if (TBAAInfo) *TBAAInfo = LV.getTBAAInfo();
1059 return LV.getAddress();
1063 // TODO: conditional operators, comma.
1065 // Otherwise, use the alignment of the type.
1066 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(), BaseInfo,
1068 return Address(EmitScalarExpr(E), Align);
1071 RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
1072 if (Ty->isVoidType())
1073 return RValue::get(nullptr);
1075 switch (getEvaluationKind(Ty)) {
1078 ConvertType(Ty->castAs<ComplexType>()->getElementType());
1079 llvm::Value *U = llvm::UndefValue::get(EltTy);
1080 return RValue::getComplex(std::make_pair(U, U));
1083 // If this is a use of an undefined aggregate type, the aggregate must have an
1084 // identifiable address. Just because the contents of the value are undefined
1085 // doesn't mean that the address can't be taken and compared.
1086 case TEK_Aggregate: {
1087 Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
1088 return RValue::getAggregate(DestPtr);
1092 return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
1094 llvm_unreachable("bad evaluation kind");
1097 RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
1099 ErrorUnsupported(E, Name);
1100 return GetUndefRValue(E->getType());
1103 LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
1105 ErrorUnsupported(E, Name);
1106 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
1107 return MakeAddrLValue(Address(llvm::UndefValue::get(Ty), CharUnits::One()),
1111 bool CodeGenFunction::IsWrappedCXXThis(const Expr *Obj) {
1112 const Expr *Base = Obj;
1113 while (!isa<CXXThisExpr>(Base)) {
1114 // The result of a dynamic_cast can be null.
1115 if (isa<CXXDynamicCastExpr>(Base))
1118 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
1119 Base = CE->getSubExpr();
1120 } else if (const auto *PE = dyn_cast<ParenExpr>(Base)) {
1121 Base = PE->getSubExpr();
1122 } else if (const auto *UO = dyn_cast<UnaryOperator>(Base)) {
1123 if (UO->getOpcode() == UO_Extension)
1124 Base = UO->getSubExpr();
1134 LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
1136 if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
1137 LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
1140 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple()) {
1141 SanitizerSet SkippedChecks;
1142 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
1143 bool IsBaseCXXThis = IsWrappedCXXThis(ME->getBase());
1145 SkippedChecks.set(SanitizerKind::Alignment, true);
1146 if (IsBaseCXXThis || isa<DeclRefExpr>(ME->getBase()))
1147 SkippedChecks.set(SanitizerKind::Null, true);
1149 EmitTypeCheck(TCK, E->getExprLoc(), LV.getPointer(),
1150 E->getType(), LV.getAlignment(), SkippedChecks);
1155 /// EmitLValue - Emit code to compute a designator that specifies the location
1156 /// of the expression.
1158 /// This can return one of two things: a simple address or a bitfield reference.
1159 /// In either case, the LLVM Value* in the LValue structure is guaranteed to be
1160 /// an LLVM pointer type.
1162 /// If this returns a bitfield reference, nothing about the pointee type of the
1163 /// LLVM value is known: For example, it may not be a pointer to an integer.
1165 /// If this returns a normal address, and if the lvalue's C type is fixed size,
1166 /// this method guarantees that the returned pointer type will point to an LLVM
1167 /// type of the same size of the lvalue's type. If the lvalue has a variable
1168 /// length type, this is not possible.
1170 LValue CodeGenFunction::EmitLValue(const Expr *E) {
1171 ApplyDebugLocation DL(*this, E);
1172 switch (E->getStmtClass()) {
1173 default: return EmitUnsupportedLValue(E, "l-value expression");
1175 case Expr::ObjCPropertyRefExprClass:
1176 llvm_unreachable("cannot emit a property reference directly");
1178 case Expr::ObjCSelectorExprClass:
1179 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
1180 case Expr::ObjCIsaExprClass:
1181 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
1182 case Expr::BinaryOperatorClass:
1183 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
1184 case Expr::CompoundAssignOperatorClass: {
1185 QualType Ty = E->getType();
1186 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1187 Ty = AT->getValueType();
1188 if (!Ty->isAnyComplexType())
1189 return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
1190 return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
1192 case Expr::CallExprClass:
1193 case Expr::CXXMemberCallExprClass:
1194 case Expr::CXXOperatorCallExprClass:
1195 case Expr::UserDefinedLiteralClass:
1196 return EmitCallExprLValue(cast<CallExpr>(E));
1197 case Expr::VAArgExprClass:
1198 return EmitVAArgExprLValue(cast<VAArgExpr>(E));
1199 case Expr::DeclRefExprClass:
1200 return EmitDeclRefLValue(cast<DeclRefExpr>(E));
1201 case Expr::ParenExprClass:
1202 return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
1203 case Expr::GenericSelectionExprClass:
1204 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
1205 case Expr::PredefinedExprClass:
1206 return EmitPredefinedLValue(cast<PredefinedExpr>(E));
1207 case Expr::StringLiteralClass:
1208 return EmitStringLiteralLValue(cast<StringLiteral>(E));
1209 case Expr::ObjCEncodeExprClass:
1210 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
1211 case Expr::PseudoObjectExprClass:
1212 return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
1213 case Expr::InitListExprClass:
1214 return EmitInitListLValue(cast<InitListExpr>(E));
1215 case Expr::CXXTemporaryObjectExprClass:
1216 case Expr::CXXConstructExprClass:
1217 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
1218 case Expr::CXXBindTemporaryExprClass:
1219 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
1220 case Expr::CXXUuidofExprClass:
1221 return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
1222 case Expr::LambdaExprClass:
1223 return EmitLambdaLValue(cast<LambdaExpr>(E));
1225 case Expr::ExprWithCleanupsClass: {
1226 const auto *cleanups = cast<ExprWithCleanups>(E);
1227 enterFullExpression(cleanups);
1228 RunCleanupsScope Scope(*this);
1229 LValue LV = EmitLValue(cleanups->getSubExpr());
1230 if (LV.isSimple()) {
1231 // Defend against branches out of gnu statement expressions surrounded by
1233 llvm::Value *V = LV.getPointer();
1234 Scope.ForceCleanup({&V});
1235 return LValue::MakeAddr(Address(V, LV.getAlignment()), LV.getType(),
1236 getContext(), LV.getBaseInfo(), LV.getTBAAInfo());
1238 // FIXME: Is it possible to create an ExprWithCleanups that produces a
1239 // bitfield lvalue or some other non-simple lvalue?
1243 case Expr::CXXDefaultArgExprClass:
1244 return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
1245 case Expr::CXXDefaultInitExprClass: {
1246 CXXDefaultInitExprScope Scope(*this);
1247 return EmitLValue(cast<CXXDefaultInitExpr>(E)->getExpr());
1249 case Expr::CXXTypeidExprClass:
1250 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
1252 case Expr::ObjCMessageExprClass:
1253 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
1254 case Expr::ObjCIvarRefExprClass:
1255 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
1256 case Expr::StmtExprClass:
1257 return EmitStmtExprLValue(cast<StmtExpr>(E));
1258 case Expr::UnaryOperatorClass:
1259 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
1260 case Expr::ArraySubscriptExprClass:
1261 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
1262 case Expr::OMPArraySectionExprClass:
1263 return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E));
1264 case Expr::ExtVectorElementExprClass:
1265 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
1266 case Expr::MemberExprClass:
1267 return EmitMemberExpr(cast<MemberExpr>(E));
1268 case Expr::CompoundLiteralExprClass:
1269 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
1270 case Expr::ConditionalOperatorClass:
1271 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
1272 case Expr::BinaryConditionalOperatorClass:
1273 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
1274 case Expr::ChooseExprClass:
1275 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr());
1276 case Expr::OpaqueValueExprClass:
1277 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
1278 case Expr::SubstNonTypeTemplateParmExprClass:
1279 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
1280 case Expr::ImplicitCastExprClass:
1281 case Expr::CStyleCastExprClass:
1282 case Expr::CXXFunctionalCastExprClass:
1283 case Expr::CXXStaticCastExprClass:
1284 case Expr::CXXDynamicCastExprClass:
1285 case Expr::CXXReinterpretCastExprClass:
1286 case Expr::CXXConstCastExprClass:
1287 case Expr::ObjCBridgedCastExprClass:
1288 return EmitCastLValue(cast<CastExpr>(E));
1290 case Expr::MaterializeTemporaryExprClass:
1291 return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
1293 case Expr::CoawaitExprClass:
1294 return EmitCoawaitLValue(cast<CoawaitExpr>(E));
1295 case Expr::CoyieldExprClass:
1296 return EmitCoyieldLValue(cast<CoyieldExpr>(E));
1300 /// Given an object of the given canonical type, can we safely copy a
1301 /// value out of it based on its initializer?
1302 static bool isConstantEmittableObjectType(QualType type) {
1303 assert(type.isCanonical());
1304 assert(!type->isReferenceType());
1306 // Must be const-qualified but non-volatile.
1307 Qualifiers qs = type.getLocalQualifiers();
1308 if (!qs.hasConst() || qs.hasVolatile()) return false;
1310 // Otherwise, all object types satisfy this except C++ classes with
1311 // mutable subobjects or non-trivial copy/destroy behavior.
1312 if (const auto *RT = dyn_cast<RecordType>(type))
1313 if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
1314 if (RD->hasMutableFields() || !RD->isTrivial())
1320 /// Can we constant-emit a load of a reference to a variable of the
1321 /// given type? This is different from predicates like
1322 /// Decl::isUsableInConstantExpressions because we do want it to apply
1323 /// in situations that don't necessarily satisfy the language's rules
1324 /// for this (e.g. C++'s ODR-use rules). For example, we want to able
1325 /// to do this with const float variables even if those variables
1326 /// aren't marked 'constexpr'.
1327 enum ConstantEmissionKind {
1329 CEK_AsReferenceOnly,
1330 CEK_AsValueOrReference,
1333 static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
1334 type = type.getCanonicalType();
1335 if (const auto *ref = dyn_cast<ReferenceType>(type)) {
1336 if (isConstantEmittableObjectType(ref->getPointeeType()))
1337 return CEK_AsValueOrReference;
1338 return CEK_AsReferenceOnly;
1340 if (isConstantEmittableObjectType(type))
1341 return CEK_AsValueOnly;
1345 /// Try to emit a reference to the given value without producing it as
1346 /// an l-value. This is actually more than an optimization: we can't
1347 /// produce an l-value for variables that we never actually captured
1348 /// in a block or lambda, which means const int variables or constexpr
1349 /// literals or similar.
1350 CodeGenFunction::ConstantEmission
1351 CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
1352 ValueDecl *value = refExpr->getDecl();
1354 // The value needs to be an enum constant or a constant variable.
1355 ConstantEmissionKind CEK;
1356 if (isa<ParmVarDecl>(value)) {
1358 } else if (auto *var = dyn_cast<VarDecl>(value)) {
1359 CEK = checkVarTypeForConstantEmission(var->getType());
1360 } else if (isa<EnumConstantDecl>(value)) {
1361 CEK = CEK_AsValueOnly;
1365 if (CEK == CEK_None) return ConstantEmission();
1367 Expr::EvalResult result;
1368 bool resultIsReference;
1369 QualType resultType;
1371 // It's best to evaluate all the way as an r-value if that's permitted.
1372 if (CEK != CEK_AsReferenceOnly &&
1373 refExpr->EvaluateAsRValue(result, getContext())) {
1374 resultIsReference = false;
1375 resultType = refExpr->getType();
1377 // Otherwise, try to evaluate as an l-value.
1378 } else if (CEK != CEK_AsValueOnly &&
1379 refExpr->EvaluateAsLValue(result, getContext())) {
1380 resultIsReference = true;
1381 resultType = value->getType();
1385 return ConstantEmission();
1388 // In any case, if the initializer has side-effects, abandon ship.
1389 if (result.HasSideEffects)
1390 return ConstantEmission();
1392 // Emit as a constant.
1393 auto C = ConstantEmitter(*this).emitAbstract(refExpr->getLocation(),
1394 result.Val, resultType);
1396 // Make sure we emit a debug reference to the global variable.
1397 // This should probably fire even for
1398 if (isa<VarDecl>(value)) {
1399 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
1400 EmitDeclRefExprDbgValue(refExpr, result.Val);
1402 assert(isa<EnumConstantDecl>(value));
1403 EmitDeclRefExprDbgValue(refExpr, result.Val);
1406 // If we emitted a reference constant, we need to dereference that.
1407 if (resultIsReference)
1408 return ConstantEmission::forReference(C);
1410 return ConstantEmission::forValue(C);
1413 static DeclRefExpr *tryToConvertMemberExprToDeclRefExpr(CodeGenFunction &CGF,
1414 const MemberExpr *ME) {
1415 if (auto *VD = dyn_cast<VarDecl>(ME->getMemberDecl())) {
1416 // Try to emit static variable member expressions as DREs.
1417 return DeclRefExpr::Create(
1418 CGF.getContext(), NestedNameSpecifierLoc(), SourceLocation(), VD,
1419 /*RefersToEnclosingVariableOrCapture=*/false, ME->getExprLoc(),
1420 ME->getType(), ME->getValueKind());
1425 CodeGenFunction::ConstantEmission
1426 CodeGenFunction::tryEmitAsConstant(const MemberExpr *ME) {
1427 if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, ME))
1428 return tryEmitAsConstant(DRE);
1429 return ConstantEmission();
1432 llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
1433 SourceLocation Loc) {
1434 return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
1435 lvalue.getType(), Loc, lvalue.getBaseInfo(),
1436 lvalue.getTBAAInfo(), lvalue.isNontemporal());
1439 static bool hasBooleanRepresentation(QualType Ty) {
1440 if (Ty->isBooleanType())
1443 if (const EnumType *ET = Ty->getAs<EnumType>())
1444 return ET->getDecl()->getIntegerType()->isBooleanType();
1446 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1447 return hasBooleanRepresentation(AT->getValueType());
1452 static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
1453 llvm::APInt &Min, llvm::APInt &End,
1454 bool StrictEnums, bool IsBool) {
1455 const EnumType *ET = Ty->getAs<EnumType>();
1456 bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
1457 ET && !ET->getDecl()->isFixed();
1458 if (!IsBool && !IsRegularCPlusPlusEnum)
1462 Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
1463 End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
1465 const EnumDecl *ED = ET->getDecl();
1466 llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
1467 unsigned Bitwidth = LTy->getScalarSizeInBits();
1468 unsigned NumNegativeBits = ED->getNumNegativeBits();
1469 unsigned NumPositiveBits = ED->getNumPositiveBits();
1471 if (NumNegativeBits) {
1472 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
1473 assert(NumBits <= Bitwidth);
1474 End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
1477 assert(NumPositiveBits <= Bitwidth);
1478 End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
1479 Min = llvm::APInt(Bitwidth, 0);
1485 llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
1486 llvm::APInt Min, End;
1487 if (!getRangeForType(*this, Ty, Min, End, CGM.getCodeGenOpts().StrictEnums,
1488 hasBooleanRepresentation(Ty)))
1491 llvm::MDBuilder MDHelper(getLLVMContext());
1492 return MDHelper.createRange(Min, End);
1495 bool CodeGenFunction::EmitScalarRangeCheck(llvm::Value *Value, QualType Ty,
1496 SourceLocation Loc) {
1497 bool HasBoolCheck = SanOpts.has(SanitizerKind::Bool);
1498 bool HasEnumCheck = SanOpts.has(SanitizerKind::Enum);
1499 if (!HasBoolCheck && !HasEnumCheck)
1502 bool IsBool = hasBooleanRepresentation(Ty) ||
1503 NSAPI(CGM.getContext()).isObjCBOOLType(Ty);
1504 bool NeedsBoolCheck = HasBoolCheck && IsBool;
1505 bool NeedsEnumCheck = HasEnumCheck && Ty->getAs<EnumType>();
1506 if (!NeedsBoolCheck && !NeedsEnumCheck)
1509 // Single-bit booleans don't need to be checked. Special-case this to avoid
1510 // a bit width mismatch when handling bitfield values. This is handled by
1511 // EmitFromMemory for the non-bitfield case.
1513 cast<llvm::IntegerType>(Value->getType())->getBitWidth() == 1)
1516 llvm::APInt Min, End;
1517 if (!getRangeForType(*this, Ty, Min, End, /*StrictEnums=*/true, IsBool))
1520 auto &Ctx = getLLVMContext();
1521 SanitizerScope SanScope(this);
1525 Check = Builder.CreateICmpULE(Value, llvm::ConstantInt::get(Ctx, End));
1527 llvm::Value *Upper =
1528 Builder.CreateICmpSLE(Value, llvm::ConstantInt::get(Ctx, End));
1529 llvm::Value *Lower =
1530 Builder.CreateICmpSGE(Value, llvm::ConstantInt::get(Ctx, Min));
1531 Check = Builder.CreateAnd(Upper, Lower);
1533 llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc),
1534 EmitCheckTypeDescriptor(Ty)};
1535 SanitizerMask Kind =
1536 NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
1537 EmitCheck(std::make_pair(Check, Kind), SanitizerHandler::LoadInvalidValue,
1538 StaticArgs, EmitCheckValue(Value));
1542 llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile,
1545 LValueBaseInfo BaseInfo,
1546 TBAAAccessInfo TBAAInfo,
1547 bool isNontemporal) {
1548 if (!CGM.getCodeGenOpts().PreserveVec3Type) {
1549 // For better performance, handle vector loads differently.
1550 if (Ty->isVectorType()) {
1551 const llvm::Type *EltTy = Addr.getElementType();
1553 const auto *VTy = cast<llvm::VectorType>(EltTy);
1555 // Handle vectors of size 3 like size 4 for better performance.
1556 if (VTy->getNumElements() == 3) {
1558 // Bitcast to vec4 type.
1559 llvm::VectorType *vec4Ty =
1560 llvm::VectorType::get(VTy->getElementType(), 4);
1561 Address Cast = Builder.CreateElementBitCast(Addr, vec4Ty, "castToVec4");
1563 llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4");
1565 // Shuffle vector to get vec3.
1566 V = Builder.CreateShuffleVector(V, llvm::UndefValue::get(vec4Ty),
1567 {0, 1, 2}, "extractVec");
1568 return EmitFromMemory(V, Ty);
1573 // Atomic operations have to be done on integral types.
1574 LValue AtomicLValue =
1575 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
1576 if (Ty->isAtomicType() || LValueIsSuitableForInlineAtomic(AtomicLValue)) {
1577 return EmitAtomicLoad(AtomicLValue, Loc).getScalarVal();
1580 llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
1581 if (isNontemporal) {
1582 llvm::MDNode *Node = llvm::MDNode::get(
1583 Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1584 Load->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1587 CGM.DecorateInstructionWithTBAA(Load, TBAAInfo);
1589 if (EmitScalarRangeCheck(Load, Ty, Loc)) {
1590 // In order to prevent the optimizer from throwing away the check, don't
1591 // attach range metadata to the load.
1592 } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
1593 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
1594 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
1596 return EmitFromMemory(Load, Ty);
1599 llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
1600 // Bool has a different representation in memory than in registers.
1601 if (hasBooleanRepresentation(Ty)) {
1602 // This should really always be an i1, but sometimes it's already
1603 // an i8, and it's awkward to track those cases down.
1604 if (Value->getType()->isIntegerTy(1))
1605 return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
1606 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1607 "wrong value rep of bool");
1613 llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
1614 // Bool has a different representation in memory than in registers.
1615 if (hasBooleanRepresentation(Ty)) {
1616 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1617 "wrong value rep of bool");
1618 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
1624 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr,
1625 bool Volatile, QualType Ty,
1626 LValueBaseInfo BaseInfo,
1627 TBAAAccessInfo TBAAInfo,
1628 bool isInit, bool isNontemporal) {
1629 if (!CGM.getCodeGenOpts().PreserveVec3Type) {
1630 // Handle vectors differently to get better performance.
1631 if (Ty->isVectorType()) {
1632 llvm::Type *SrcTy = Value->getType();
1633 auto *VecTy = dyn_cast<llvm::VectorType>(SrcTy);
1634 // Handle vec3 special.
1635 if (VecTy && VecTy->getNumElements() == 3) {
1636 // Our source is a vec3, do a shuffle vector to make it a vec4.
1637 llvm::Constant *Mask[] = {Builder.getInt32(0), Builder.getInt32(1),
1638 Builder.getInt32(2),
1639 llvm::UndefValue::get(Builder.getInt32Ty())};
1640 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1641 Value = Builder.CreateShuffleVector(Value, llvm::UndefValue::get(VecTy),
1642 MaskV, "extractVec");
1643 SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
1645 if (Addr.getElementType() != SrcTy) {
1646 Addr = Builder.CreateElementBitCast(Addr, SrcTy, "storetmp");
1651 Value = EmitToMemory(Value, Ty);
1653 LValue AtomicLValue =
1654 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
1655 if (Ty->isAtomicType() ||
1656 (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) {
1657 EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit);
1661 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
1662 if (isNontemporal) {
1663 llvm::MDNode *Node =
1664 llvm::MDNode::get(Store->getContext(),
1665 llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1666 Store->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1669 CGM.DecorateInstructionWithTBAA(Store, TBAAInfo);
1672 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
1674 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
1675 lvalue.getType(), lvalue.getBaseInfo(),
1676 lvalue.getTBAAInfo(), isInit, lvalue.isNontemporal());
1679 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1680 /// method emits the address of the lvalue, then loads the result as an rvalue,
1681 /// returning the rvalue.
1682 RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
1683 if (LV.isObjCWeak()) {
1684 // load of a __weak object.
1685 Address AddrWeakObj = LV.getAddress();
1686 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1689 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
1690 // In MRC mode, we do a load+autorelease.
1691 if (!getLangOpts().ObjCAutoRefCount) {
1692 return RValue::get(EmitARCLoadWeak(LV.getAddress()));
1695 // In ARC mode, we load retained and then consume the value.
1696 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
1697 Object = EmitObjCConsumeObject(LV.getType(), Object);
1698 return RValue::get(Object);
1701 if (LV.isSimple()) {
1702 assert(!LV.getType()->isFunctionType());
1704 // Everything needs a load.
1705 return RValue::get(EmitLoadOfScalar(LV, Loc));
1708 if (LV.isVectorElt()) {
1709 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
1710 LV.isVolatileQualified());
1711 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
1715 // If this is a reference to a subset of the elements of a vector, either
1716 // shuffle the input or extract/insert them as appropriate.
1717 if (LV.isExtVectorElt())
1718 return EmitLoadOfExtVectorElementLValue(LV);
1720 // Global Register variables always invoke intrinsics
1721 if (LV.isGlobalReg())
1722 return EmitLoadOfGlobalRegLValue(LV);
1724 assert(LV.isBitField() && "Unknown LValue type!");
1725 return EmitLoadOfBitfieldLValue(LV, Loc);
1728 RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
1729 SourceLocation Loc) {
1730 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
1732 // Get the output type.
1733 llvm::Type *ResLTy = ConvertType(LV.getType());
1735 Address Ptr = LV.getBitFieldAddress();
1736 llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
1738 if (Info.IsSigned) {
1739 assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
1740 unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
1742 Val = Builder.CreateShl(Val, HighBits, "bf.shl");
1743 if (Info.Offset + HighBits)
1744 Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
1747 Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
1748 if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
1749 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
1753 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
1754 EmitScalarRangeCheck(Val, LV.getType(), Loc);
1755 return RValue::get(Val);
1758 // If this is a reference to a subset of the elements of a vector, create an
1759 // appropriate shufflevector.
1760 RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
1761 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
1762 LV.isVolatileQualified());
1764 const llvm::Constant *Elts = LV.getExtVectorElts();
1766 // If the result of the expression is a non-vector type, we must be extracting
1767 // a single element. Just codegen as an extractelement.
1768 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1770 unsigned InIdx = getAccessedFieldNo(0, Elts);
1771 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
1772 return RValue::get(Builder.CreateExtractElement(Vec, Elt));
1775 // Always use shuffle vector to try to retain the original program structure
1776 unsigned NumResultElts = ExprVT->getNumElements();
1778 SmallVector<llvm::Constant*, 4> Mask;
1779 for (unsigned i = 0; i != NumResultElts; ++i)
1780 Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
1782 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1783 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
1785 return RValue::get(Vec);
1788 /// @brief Generates lvalue for partial ext_vector access.
1789 Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
1790 Address VectorAddress = LV.getExtVectorAddress();
1791 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1792 QualType EQT = ExprVT->getElementType();
1793 llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
1795 Address CastToPointerElement =
1796 Builder.CreateElementBitCast(VectorAddress, VectorElementTy,
1797 "conv.ptr.element");
1799 const llvm::Constant *Elts = LV.getExtVectorElts();
1800 unsigned ix = getAccessedFieldNo(0, Elts);
1802 Address VectorBasePtrPlusIx =
1803 Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
1804 getContext().getTypeSizeInChars(EQT),
1807 return VectorBasePtrPlusIx;
1810 /// @brief Load of global gamed gegisters are always calls to intrinsics.
1811 RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
1812 assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
1813 "Bad type for register variable");
1814 llvm::MDNode *RegName = cast<llvm::MDNode>(
1815 cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
1817 // We accept integer and pointer types only
1818 llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
1819 llvm::Type *Ty = OrigTy;
1820 if (OrigTy->isPointerTy())
1821 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1822 llvm::Type *Types[] = { Ty };
1824 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
1825 llvm::Value *Call = Builder.CreateCall(
1826 F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
1827 if (OrigTy->isPointerTy())
1828 Call = Builder.CreateIntToPtr(Call, OrigTy);
1829 return RValue::get(Call);
1833 /// EmitStoreThroughLValue - Store the specified rvalue into the specified
1834 /// lvalue, where both are guaranteed to the have the same type, and that type
1836 void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
1838 if (!Dst.isSimple()) {
1839 if (Dst.isVectorElt()) {
1840 // Read/modify/write the vector, inserting the new element.
1841 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
1842 Dst.isVolatileQualified());
1843 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
1844 Dst.getVectorIdx(), "vecins");
1845 Builder.CreateStore(Vec, Dst.getVectorAddress(),
1846 Dst.isVolatileQualified());
1850 // If this is an update of extended vector elements, insert them as
1852 if (Dst.isExtVectorElt())
1853 return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
1855 if (Dst.isGlobalReg())
1856 return EmitStoreThroughGlobalRegLValue(Src, Dst);
1858 assert(Dst.isBitField() && "Unknown LValue type");
1859 return EmitStoreThroughBitfieldLValue(Src, Dst);
1862 // There's special magic for assigning into an ARC-qualified l-value.
1863 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
1865 case Qualifiers::OCL_None:
1866 llvm_unreachable("present but none");
1868 case Qualifiers::OCL_ExplicitNone:
1872 case Qualifiers::OCL_Strong:
1874 Src = RValue::get(EmitARCRetain(Dst.getType(), Src.getScalarVal()));
1877 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
1880 case Qualifiers::OCL_Weak:
1882 // Initialize and then skip the primitive store.
1883 EmitARCInitWeak(Dst.getAddress(), Src.getScalarVal());
1885 EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
1888 case Qualifiers::OCL_Autoreleasing:
1889 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
1890 Src.getScalarVal()));
1891 // fall into the normal path
1896 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
1897 // load of a __weak object.
1898 Address LvalueDst = Dst.getAddress();
1899 llvm::Value *src = Src.getScalarVal();
1900 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
1904 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
1905 // load of a __strong object.
1906 Address LvalueDst = Dst.getAddress();
1907 llvm::Value *src = Src.getScalarVal();
1908 if (Dst.isObjCIvar()) {
1909 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
1910 llvm::Type *ResultType = IntPtrTy;
1911 Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp());
1912 llvm::Value *RHS = dst.getPointer();
1913 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1915 Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType,
1916 "sub.ptr.lhs.cast");
1917 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
1918 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
1920 } else if (Dst.isGlobalObjCRef()) {
1921 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
1922 Dst.isThreadLocalRef());
1925 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
1929 assert(Src.isScalar() && "Can't emit an agg store with this method");
1930 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
1933 void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
1934 llvm::Value **Result) {
1935 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
1936 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
1937 Address Ptr = Dst.getBitFieldAddress();
1939 // Get the source value, truncated to the width of the bit-field.
1940 llvm::Value *SrcVal = Src.getScalarVal();
1942 // Cast the source to the storage type and shift it into place.
1943 SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
1944 /*IsSigned=*/false);
1945 llvm::Value *MaskedVal = SrcVal;
1947 // See if there are other bits in the bitfield's storage we'll need to load
1948 // and mask together with source before storing.
1949 if (Info.StorageSize != Info.Size) {
1950 assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
1952 Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
1954 // Mask the source value as needed.
1955 if (!hasBooleanRepresentation(Dst.getType()))
1956 SrcVal = Builder.CreateAnd(SrcVal,
1957 llvm::APInt::getLowBitsSet(Info.StorageSize,
1962 SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
1964 // Mask out the original value.
1965 Val = Builder.CreateAnd(Val,
1966 ~llvm::APInt::getBitsSet(Info.StorageSize,
1968 Info.Offset + Info.Size),
1971 // Or together the unchanged values and the source value.
1972 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
1974 assert(Info.Offset == 0);
1977 // Write the new value back out.
1978 Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
1980 // Return the new value of the bit-field, if requested.
1982 llvm::Value *ResultVal = MaskedVal;
1984 // Sign extend the value if needed.
1985 if (Info.IsSigned) {
1986 assert(Info.Size <= Info.StorageSize);
1987 unsigned HighBits = Info.StorageSize - Info.Size;
1989 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
1990 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
1994 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
1996 *Result = EmitFromMemory(ResultVal, Dst.getType());
2000 void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
2002 // This access turns into a read/modify/write of the vector. Load the input
2004 llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(),
2005 Dst.isVolatileQualified());
2006 const llvm::Constant *Elts = Dst.getExtVectorElts();
2008 llvm::Value *SrcVal = Src.getScalarVal();
2010 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
2011 unsigned NumSrcElts = VTy->getNumElements();
2012 unsigned NumDstElts = Vec->getType()->getVectorNumElements();
2013 if (NumDstElts == NumSrcElts) {
2014 // Use shuffle vector is the src and destination are the same number of
2015 // elements and restore the vector mask since it is on the side it will be
2017 SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
2018 for (unsigned i = 0; i != NumSrcElts; ++i)
2019 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
2021 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
2022 Vec = Builder.CreateShuffleVector(SrcVal,
2023 llvm::UndefValue::get(Vec->getType()),
2025 } else if (NumDstElts > NumSrcElts) {
2026 // Extended the source vector to the same length and then shuffle it
2027 // into the destination.
2028 // FIXME: since we're shuffling with undef, can we just use the indices
2029 // into that? This could be simpler.
2030 SmallVector<llvm::Constant*, 4> ExtMask;
2031 for (unsigned i = 0; i != NumSrcElts; ++i)
2032 ExtMask.push_back(Builder.getInt32(i));
2033 ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
2034 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
2035 llvm::Value *ExtSrcVal =
2036 Builder.CreateShuffleVector(SrcVal,
2037 llvm::UndefValue::get(SrcVal->getType()),
2040 SmallVector<llvm::Constant*, 4> Mask;
2041 for (unsigned i = 0; i != NumDstElts; ++i)
2042 Mask.push_back(Builder.getInt32(i));
2044 // When the vector size is odd and .odd or .hi is used, the last element
2045 // of the Elts constant array will be one past the size of the vector.
2046 // Ignore the last element here, if it is greater than the mask size.
2047 if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
2050 // modify when what gets shuffled in
2051 for (unsigned i = 0; i != NumSrcElts; ++i)
2052 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
2053 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
2054 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
2056 // We should never shorten the vector
2057 llvm_unreachable("unexpected shorten vector length");
2060 // If the Src is a scalar (not a vector) it must be updating one element.
2061 unsigned InIdx = getAccessedFieldNo(0, Elts);
2062 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
2063 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
2066 Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
2067 Dst.isVolatileQualified());
2070 /// @brief Store of global named registers are always calls to intrinsics.
2071 void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
2072 assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
2073 "Bad type for register variable");
2074 llvm::MDNode *RegName = cast<llvm::MDNode>(
2075 cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
2076 assert(RegName && "Register LValue is not metadata");
2078 // We accept integer and pointer types only
2079 llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
2080 llvm::Type *Ty = OrigTy;
2081 if (OrigTy->isPointerTy())
2082 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
2083 llvm::Type *Types[] = { Ty };
2085 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
2086 llvm::Value *Value = Src.getScalarVal();
2087 if (OrigTy->isPointerTy())
2088 Value = Builder.CreatePtrToInt(Value, Ty);
2090 F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
2093 // setObjCGCLValueClass - sets class of the lvalue for the purpose of
2094 // generating write-barries API. It is currently a global, ivar,
2096 static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
2098 bool IsMemberAccess=false) {
2099 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
2102 if (isa<ObjCIvarRefExpr>(E)) {
2103 QualType ExpTy = E->getType();
2104 if (IsMemberAccess && ExpTy->isPointerType()) {
2105 // If ivar is a structure pointer, assigning to field of
2106 // this struct follows gcc's behavior and makes it a non-ivar
2107 // writer-barrier conservatively.
2108 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
2109 if (ExpTy->isRecordType()) {
2110 LV.setObjCIvar(false);
2114 LV.setObjCIvar(true);
2115 auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
2116 LV.setBaseIvarExp(Exp->getBase());
2117 LV.setObjCArray(E->getType()->isArrayType());
2121 if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
2122 if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
2123 if (VD->hasGlobalStorage()) {
2124 LV.setGlobalObjCRef(true);
2125 LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
2128 LV.setObjCArray(E->getType()->isArrayType());
2132 if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
2133 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2137 if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
2138 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2139 if (LV.isObjCIvar()) {
2140 // If cast is to a structure pointer, follow gcc's behavior and make it
2141 // a non-ivar write-barrier.
2142 QualType ExpTy = E->getType();
2143 if (ExpTy->isPointerType())
2144 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
2145 if (ExpTy->isRecordType())
2146 LV.setObjCIvar(false);
2151 if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
2152 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
2156 if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
2157 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2161 if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
2162 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2166 if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
2167 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2171 if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
2172 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
2173 if (LV.isObjCIvar() && !LV.isObjCArray())
2174 // Using array syntax to assigning to what an ivar points to is not
2175 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
2176 LV.setObjCIvar(false);
2177 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
2178 // Using array syntax to assigning to what global points to is not
2179 // same as assigning to the global itself. {id *G;} G[i] = 0;
2180 LV.setGlobalObjCRef(false);
2184 if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
2185 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
2186 // We don't know if member is an 'ivar', but this flag is looked at
2187 // only in the context of LV.isObjCIvar().
2188 LV.setObjCArray(E->getType()->isArrayType());
2193 static llvm::Value *
2194 EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
2195 llvm::Value *V, llvm::Type *IRType,
2196 StringRef Name = StringRef()) {
2197 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
2198 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
2201 static LValue EmitThreadPrivateVarDeclLValue(
2202 CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
2203 llvm::Type *RealVarTy, SourceLocation Loc) {
2204 Addr = CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
2205 Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy);
2206 return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
2210 CodeGenFunction::EmitLoadOfReference(LValue RefLVal,
2211 LValueBaseInfo *PointeeBaseInfo,
2212 TBAAAccessInfo *PointeeTBAAInfo) {
2213 llvm::LoadInst *Load = Builder.CreateLoad(RefLVal.getAddress(),
2214 RefLVal.isVolatile());
2215 CGM.DecorateInstructionWithTBAA(Load, RefLVal.getTBAAInfo());
2217 CharUnits Align = getNaturalTypeAlignment(RefLVal.getType()->getPointeeType(),
2218 PointeeBaseInfo, PointeeTBAAInfo,
2219 /* forPointeeType= */ true);
2220 return Address(Load, Align);
2223 LValue CodeGenFunction::EmitLoadOfReferenceLValue(LValue RefLVal) {
2224 LValueBaseInfo PointeeBaseInfo;
2225 TBAAAccessInfo PointeeTBAAInfo;
2226 Address PointeeAddr = EmitLoadOfReference(RefLVal, &PointeeBaseInfo,
2228 return MakeAddrLValue(PointeeAddr, RefLVal.getType()->getPointeeType(),
2229 PointeeBaseInfo, PointeeTBAAInfo);
2232 Address CodeGenFunction::EmitLoadOfPointer(Address Ptr,
2233 const PointerType *PtrTy,
2234 LValueBaseInfo *BaseInfo,
2235 TBAAAccessInfo *TBAAInfo) {
2236 llvm::Value *Addr = Builder.CreateLoad(Ptr);
2237 return Address(Addr, getNaturalTypeAlignment(PtrTy->getPointeeType(),
2239 /*forPointeeType=*/true));
2242 LValue CodeGenFunction::EmitLoadOfPointerLValue(Address PtrAddr,
2243 const PointerType *PtrTy) {
2244 LValueBaseInfo BaseInfo;
2245 TBAAAccessInfo TBAAInfo;
2246 Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &BaseInfo, &TBAAInfo);
2247 return MakeAddrLValue(Addr, PtrTy->getPointeeType(), BaseInfo, TBAAInfo);
2250 static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
2251 const Expr *E, const VarDecl *VD) {
2252 QualType T = E->getType();
2254 // If it's thread_local, emit a call to its wrapper function instead.
2255 if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
2256 CGF.CGM.getCXXABI().usesThreadWrapperFunction())
2257 return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
2259 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
2260 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
2261 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
2262 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
2263 Address Addr(V, Alignment);
2264 // Emit reference to the private copy of the variable if it is an OpenMP
2265 // threadprivate variable.
2266 if (CGF.getLangOpts().OpenMP && !CGF.getLangOpts().OpenMPSimd &&
2267 VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
2268 return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
2271 LValue LV = VD->getType()->isReferenceType() ?
2272 CGF.EmitLoadOfReferenceLValue(Addr, VD->getType(),
2273 AlignmentSource::Decl) :
2274 CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
2275 setObjCGCLValueClass(CGF.getContext(), E, LV);
2279 static llvm::Constant *EmitFunctionDeclPointer(CodeGenModule &CGM,
2280 const FunctionDecl *FD) {
2281 if (FD->hasAttr<WeakRefAttr>()) {
2282 ConstantAddress aliasee = CGM.GetWeakRefReference(FD);
2283 return aliasee.getPointer();
2286 llvm::Constant *V = CGM.GetAddrOfFunction(FD);
2287 if (!FD->hasPrototype()) {
2288 if (const FunctionProtoType *Proto =
2289 FD->getType()->getAs<FunctionProtoType>()) {
2290 // Ugly case: for a K&R-style definition, the type of the definition
2291 // isn't the same as the type of a use. Correct for this with a
2293 QualType NoProtoType =
2294 CGM.getContext().getFunctionNoProtoType(Proto->getReturnType());
2295 NoProtoType = CGM.getContext().getPointerType(NoProtoType);
2296 V = llvm::ConstantExpr::getBitCast(V,
2297 CGM.getTypes().ConvertType(NoProtoType));
2303 static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
2304 const Expr *E, const FunctionDecl *FD) {
2305 llvm::Value *V = EmitFunctionDeclPointer(CGF.CGM, FD);
2306 CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
2307 return CGF.MakeAddrLValue(V, E->getType(), Alignment,
2308 AlignmentSource::Decl);
2311 static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
2312 llvm::Value *ThisValue) {
2313 QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
2314 LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
2315 return CGF.EmitLValueForField(LV, FD);
2318 /// Named Registers are named metadata pointing to the register name
2319 /// which will be read from/written to as an argument to the intrinsic
2320 /// @llvm.read/write_register.
2321 /// So far, only the name is being passed down, but other options such as
2322 /// register type, allocation type or even optimization options could be
2323 /// passed down via the metadata node.
2324 static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
2325 SmallString<64> Name("llvm.named.register.");
2326 AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
2327 assert(Asm->getLabel().size() < 64-Name.size() &&
2328 "Register name too big");
2329 Name.append(Asm->getLabel());
2330 llvm::NamedMDNode *M =
2331 CGM.getModule().getOrInsertNamedMetadata(Name);
2332 if (M->getNumOperands() == 0) {
2333 llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
2335 llvm::Metadata *Ops[] = {Str};
2336 M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2339 CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
2342 llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
2343 return LValue::MakeGlobalReg(Address(Ptr, Alignment), VD->getType());
2346 LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
2347 const NamedDecl *ND = E->getDecl();
2348 QualType T = E->getType();
2350 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2351 // Global Named registers access via intrinsics only
2352 if (VD->getStorageClass() == SC_Register &&
2353 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
2354 return EmitGlobalNamedRegister(VD, CGM);
2356 // A DeclRefExpr for a reference initialized by a constant expression can
2357 // appear without being odr-used. Directly emit the constant initializer.
2358 const Expr *Init = VD->getAnyInitializer(VD);
2359 if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() &&
2360 VD->isUsableInConstantExpressions(getContext()) &&
2361 VD->checkInitIsICE() &&
2362 // Do not emit if it is private OpenMP variable.
2363 !(E->refersToEnclosingVariableOrCapture() &&
2364 ((CapturedStmtInfo &&
2365 (LocalDeclMap.count(VD->getCanonicalDecl()) ||
2366 CapturedStmtInfo->lookup(VD->getCanonicalDecl()))) ||
2367 LambdaCaptureFields.lookup(VD->getCanonicalDecl()) ||
2368 isa<BlockDecl>(CurCodeDecl)))) {
2369 llvm::Constant *Val =
2370 ConstantEmitter(*this).emitAbstract(E->getLocation(),
2371 *VD->evaluateValue(),
2373 assert(Val && "failed to emit reference constant expression");
2374 // FIXME: Eventually we will want to emit vector element references.
2376 // Should we be using the alignment of the constant pointer we emitted?
2377 CharUnits Alignment = getNaturalTypeAlignment(E->getType(),
2378 /* BaseInfo= */ nullptr,
2379 /* TBAAInfo= */ nullptr,
2380 /* forPointeeType= */ true);
2381 return MakeAddrLValue(Address(Val, Alignment), T, AlignmentSource::Decl);
2384 // Check for captured variables.
2385 if (E->refersToEnclosingVariableOrCapture()) {
2386 VD = VD->getCanonicalDecl();
2387 if (auto *FD = LambdaCaptureFields.lookup(VD))
2388 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
2389 else if (CapturedStmtInfo) {
2390 auto I = LocalDeclMap.find(VD);
2391 if (I != LocalDeclMap.end()) {
2392 if (VD->getType()->isReferenceType())
2393 return EmitLoadOfReferenceLValue(I->second, VD->getType(),
2394 AlignmentSource::Decl);
2395 return MakeAddrLValue(I->second, T);
2398 EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
2399 CapturedStmtInfo->getContextValue());
2400 return MakeAddrLValue(
2401 Address(CapLVal.getPointer(), getContext().getDeclAlign(VD)),
2402 CapLVal.getType(), LValueBaseInfo(AlignmentSource::Decl),
2403 CapLVal.getTBAAInfo());
2406 assert(isa<BlockDecl>(CurCodeDecl));
2407 Address addr = GetAddrOfBlockDecl(VD, VD->hasAttr<BlocksAttr>());
2408 return MakeAddrLValue(addr, T, AlignmentSource::Decl);
2412 // FIXME: We should be able to assert this for FunctionDecls as well!
2413 // FIXME: We should be able to assert this for all DeclRefExprs, not just
2414 // those with a valid source location.
2415 assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
2416 !E->getLocation().isValid()) &&
2417 "Should not use decl without marking it used!");
2419 if (ND->hasAttr<WeakRefAttr>()) {
2420 const auto *VD = cast<ValueDecl>(ND);
2421 ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
2422 return MakeAddrLValue(Aliasee, T, AlignmentSource::Decl);
2425 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2426 // Check if this is a global variable.
2427 if (VD->hasLinkage() || VD->isStaticDataMember())
2428 return EmitGlobalVarDeclLValue(*this, E, VD);
2430 Address addr = Address::invalid();
2432 // The variable should generally be present in the local decl map.
2433 auto iter = LocalDeclMap.find(VD);
2434 if (iter != LocalDeclMap.end()) {
2435 addr = iter->second;
2437 // Otherwise, it might be static local we haven't emitted yet for
2438 // some reason; most likely, because it's in an outer function.
2439 } else if (VD->isStaticLocal()) {
2440 addr = Address(CGM.getOrCreateStaticVarDecl(
2441 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false)),
2442 getContext().getDeclAlign(VD));
2444 // No other cases for now.
2446 llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
2450 // Check for OpenMP threadprivate variables.
2451 if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd &&
2452 VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
2453 return EmitThreadPrivateVarDeclLValue(
2454 *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
2458 // Drill into block byref variables.
2459 bool isBlockByref = VD->hasAttr<BlocksAttr>();
2461 addr = emitBlockByrefAddress(addr, VD);
2464 // Drill into reference types.
2465 LValue LV = VD->getType()->isReferenceType() ?
2466 EmitLoadOfReferenceLValue(addr, VD->getType(), AlignmentSource::Decl) :
2467 MakeAddrLValue(addr, T, AlignmentSource::Decl);
2469 bool isLocalStorage = VD->hasLocalStorage();
2471 bool NonGCable = isLocalStorage &&
2472 !VD->getType()->isReferenceType() &&
2475 LV.getQuals().removeObjCGCAttr();
2479 bool isImpreciseLifetime =
2480 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
2481 if (isImpreciseLifetime)
2482 LV.setARCPreciseLifetime(ARCImpreciseLifetime);
2483 setObjCGCLValueClass(getContext(), E, LV);
2487 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
2488 return EmitFunctionDeclLValue(*this, E, FD);
2490 // FIXME: While we're emitting a binding from an enclosing scope, all other
2491 // DeclRefExprs we see should be implicitly treated as if they also refer to
2492 // an enclosing scope.
2493 if (const auto *BD = dyn_cast<BindingDecl>(ND))
2494 return EmitLValue(BD->getBinding());
2496 llvm_unreachable("Unhandled DeclRefExpr");
2499 LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
2500 // __extension__ doesn't affect lvalue-ness.
2501 if (E->getOpcode() == UO_Extension)
2502 return EmitLValue(E->getSubExpr());
2504 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
2505 switch (E->getOpcode()) {
2506 default: llvm_unreachable("Unknown unary operator lvalue!");
2508 QualType T = E->getSubExpr()->getType()->getPointeeType();
2509 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
2511 LValueBaseInfo BaseInfo;
2512 TBAAAccessInfo TBAAInfo;
2513 Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &BaseInfo,
2515 LValue LV = MakeAddrLValue(Addr, T, BaseInfo, TBAAInfo);
2516 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
2518 // We should not generate __weak write barrier on indirect reference
2519 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
2520 // But, we continue to generate __strong write barrier on indirect write
2521 // into a pointer to object.
2522 if (getLangOpts().ObjC1 &&
2523 getLangOpts().getGC() != LangOptions::NonGC &&
2525 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
2530 LValue LV = EmitLValue(E->getSubExpr());
2531 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
2533 // __real is valid on scalars. This is a faster way of testing that.
2534 // __imag can only produce an rvalue on scalars.
2535 if (E->getOpcode() == UO_Real &&
2536 !LV.getAddress().getElementType()->isStructTy()) {
2537 assert(E->getSubExpr()->getType()->isArithmeticType());
2541 QualType T = ExprTy->castAs<ComplexType>()->getElementType();
2544 (E->getOpcode() == UO_Real
2545 ? emitAddrOfRealComponent(LV.getAddress(), LV.getType())
2546 : emitAddrOfImagComponent(LV.getAddress(), LV.getType()));
2547 LValue ElemLV = MakeAddrLValue(Component, T, LV.getBaseInfo(),
2548 CGM.getTBAAInfoForSubobject(LV, T));
2549 ElemLV.getQuals().addQualifiers(LV.getQuals());
2554 LValue LV = EmitLValue(E->getSubExpr());
2555 bool isInc = E->getOpcode() == UO_PreInc;
2557 if (E->getType()->isAnyComplexType())
2558 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
2560 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
2566 LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
2567 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
2568 E->getType(), AlignmentSource::Decl);
2571 LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
2572 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
2573 E->getType(), AlignmentSource::Decl);
2576 LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
2577 auto SL = E->getFunctionName();
2578 assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
2579 StringRef FnName = CurFn->getName();
2580 if (FnName.startswith("\01"))
2581 FnName = FnName.substr(1);
2582 StringRef NameItems[] = {
2583 PredefinedExpr::getIdentTypeName(E->getIdentType()), FnName};
2584 std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
2585 if (auto *BD = dyn_cast<BlockDecl>(CurCodeDecl)) {
2586 std::string Name = SL->getString();
2587 if (!Name.empty()) {
2588 unsigned Discriminator =
2589 CGM.getCXXABI().getMangleContext().getBlockId(BD, true);
2591 Name += "_" + Twine(Discriminator + 1).str();
2592 auto C = CGM.GetAddrOfConstantCString(Name, GVName.c_str());
2593 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
2595 auto C = CGM.GetAddrOfConstantCString(FnName, GVName.c_str());
2596 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
2599 auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
2600 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
2603 /// Emit a type description suitable for use by a runtime sanitizer library. The
2604 /// format of a type descriptor is
2607 /// { i16 TypeKind, i16 TypeInfo }
2610 /// followed by an array of i8 containing the type name. TypeKind is 0 for an
2611 /// integer, 1 for a floating point value, and -1 for anything else.
2612 llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
2613 // Only emit each type's descriptor once.
2614 if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
2617 uint16_t TypeKind = -1;
2618 uint16_t TypeInfo = 0;
2620 if (T->isIntegerType()) {
2622 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
2623 (T->isSignedIntegerType() ? 1 : 0);
2624 } else if (T->isFloatingType()) {
2626 TypeInfo = getContext().getTypeSize(T);
2629 // Format the type name as if for a diagnostic, including quotes and
2630 // optionally an 'aka'.
2631 SmallString<32> Buffer;
2632 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
2633 (intptr_t)T.getAsOpaquePtr(),
2634 StringRef(), StringRef(), None, Buffer,
2637 llvm::Constant *Components[] = {
2638 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
2639 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
2641 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
2643 auto *GV = new llvm::GlobalVariable(
2644 CGM.getModule(), Descriptor->getType(),
2645 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
2646 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2647 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
2649 // Remember the descriptor for this type.
2650 CGM.setTypeDescriptorInMap(T, GV);
2655 llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
2656 llvm::Type *TargetTy = IntPtrTy;
2658 if (V->getType() == TargetTy)
2661 // Floating-point types which fit into intptr_t are bitcast to integers
2662 // and then passed directly (after zero-extension, if necessary).
2663 if (V->getType()->isFloatingPointTy()) {
2664 unsigned Bits = V->getType()->getPrimitiveSizeInBits();
2665 if (Bits <= TargetTy->getIntegerBitWidth())
2666 V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
2670 // Integers which fit in intptr_t are zero-extended and passed directly.
2671 if (V->getType()->isIntegerTy() &&
2672 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
2673 return Builder.CreateZExt(V, TargetTy);
2675 // Pointers are passed directly, everything else is passed by address.
2676 if (!V->getType()->isPointerTy()) {
2677 Address Ptr = CreateDefaultAlignTempAlloca(V->getType());
2678 Builder.CreateStore(V, Ptr);
2679 V = Ptr.getPointer();
2681 return Builder.CreatePtrToInt(V, TargetTy);
2684 /// \brief Emit a representation of a SourceLocation for passing to a handler
2685 /// in a sanitizer runtime library. The format for this data is:
2687 /// struct SourceLocation {
2688 /// const char *Filename;
2689 /// int32_t Line, Column;
2692 /// For an invalid SourceLocation, the Filename pointer is null.
2693 llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
2694 llvm::Constant *Filename;
2697 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
2698 if (PLoc.isValid()) {
2699 StringRef FilenameString = PLoc.getFilename();
2701 int PathComponentsToStrip =
2702 CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
2703 if (PathComponentsToStrip < 0) {
2704 assert(PathComponentsToStrip != INT_MIN);
2705 int PathComponentsToKeep = -PathComponentsToStrip;
2706 auto I = llvm::sys::path::rbegin(FilenameString);
2707 auto E = llvm::sys::path::rend(FilenameString);
2708 while (I != E && --PathComponentsToKeep)
2711 FilenameString = FilenameString.substr(I - E);
2712 } else if (PathComponentsToStrip > 0) {
2713 auto I = llvm::sys::path::begin(FilenameString);
2714 auto E = llvm::sys::path::end(FilenameString);
2715 while (I != E && PathComponentsToStrip--)
2720 FilenameString.substr(I - llvm::sys::path::begin(FilenameString));
2722 FilenameString = llvm::sys::path::filename(FilenameString);
2725 auto FilenameGV = CGM.GetAddrOfConstantCString(FilenameString, ".src");
2726 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
2727 cast<llvm::GlobalVariable>(FilenameGV.getPointer()));
2728 Filename = FilenameGV.getPointer();
2729 Line = PLoc.getLine();
2730 Column = PLoc.getColumn();
2732 Filename = llvm::Constant::getNullValue(Int8PtrTy);
2736 llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
2737 Builder.getInt32(Column)};
2739 return llvm::ConstantStruct::getAnon(Data);
2743 /// \brief Specify under what conditions this check can be recovered
2744 enum class CheckRecoverableKind {
2745 /// Always terminate program execution if this check fails.
2747 /// Check supports recovering, runtime has both fatal (noreturn) and
2748 /// non-fatal handlers for this check.
2750 /// Runtime conditionally aborts, always need to support recovery.
2755 static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
2756 assert(llvm::countPopulation(Kind) == 1);
2758 case SanitizerKind::Vptr:
2759 return CheckRecoverableKind::AlwaysRecoverable;
2760 case SanitizerKind::Return:
2761 case SanitizerKind::Unreachable:
2762 return CheckRecoverableKind::Unrecoverable;
2764 return CheckRecoverableKind::Recoverable;
2769 struct SanitizerHandlerInfo {
2770 char const *const Name;
2775 const SanitizerHandlerInfo SanitizerHandlers[] = {
2776 #define SANITIZER_CHECK(Enum, Name, Version) {#Name, Version},
2777 LIST_SANITIZER_CHECKS
2778 #undef SANITIZER_CHECK
2781 static void emitCheckHandlerCall(CodeGenFunction &CGF,
2782 llvm::FunctionType *FnType,
2783 ArrayRef<llvm::Value *> FnArgs,
2784 SanitizerHandler CheckHandler,
2785 CheckRecoverableKind RecoverKind, bool IsFatal,
2786 llvm::BasicBlock *ContBB) {
2787 assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
2788 bool NeedsAbortSuffix =
2789 IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
2790 bool MinimalRuntime = CGF.CGM.getCodeGenOpts().SanitizeMinimalRuntime;
2791 const SanitizerHandlerInfo &CheckInfo = SanitizerHandlers[CheckHandler];
2792 const StringRef CheckName = CheckInfo.Name;
2793 std::string FnName = "__ubsan_handle_" + CheckName.str();
2794 if (CheckInfo.Version && !MinimalRuntime)
2795 FnName += "_v" + llvm::utostr(CheckInfo.Version);
2797 FnName += "_minimal";
2798 if (NeedsAbortSuffix)
2801 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
2803 llvm::AttrBuilder B;
2805 B.addAttribute(llvm::Attribute::NoReturn)
2806 .addAttribute(llvm::Attribute::NoUnwind);
2808 B.addAttribute(llvm::Attribute::UWTable);
2810 llvm::Value *Fn = CGF.CGM.CreateRuntimeFunction(
2812 llvm::AttributeList::get(CGF.getLLVMContext(),
2813 llvm::AttributeList::FunctionIndex, B),
2815 llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
2817 HandlerCall->setDoesNotReturn();
2818 CGF.Builder.CreateUnreachable();
2820 CGF.Builder.CreateBr(ContBB);
2824 void CodeGenFunction::EmitCheck(
2825 ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
2826 SanitizerHandler CheckHandler, ArrayRef<llvm::Constant *> StaticArgs,
2827 ArrayRef<llvm::Value *> DynamicArgs) {
2828 assert(IsSanitizerScope);
2829 assert(Checked.size() > 0);
2830 assert(CheckHandler >= 0 &&
2831 size_t(CheckHandler) < llvm::array_lengthof(SanitizerHandlers));
2832 const StringRef CheckName = SanitizerHandlers[CheckHandler].Name;
2834 llvm::Value *FatalCond = nullptr;
2835 llvm::Value *RecoverableCond = nullptr;
2836 llvm::Value *TrapCond = nullptr;
2837 for (int i = 0, n = Checked.size(); i < n; ++i) {
2838 llvm::Value *Check = Checked[i].first;
2839 // -fsanitize-trap= overrides -fsanitize-recover=.
2840 llvm::Value *&Cond =
2841 CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
2843 : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
2846 Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
2850 EmitTrapCheck(TrapCond);
2851 if (!FatalCond && !RecoverableCond)
2854 llvm::Value *JointCond;
2855 if (FatalCond && RecoverableCond)
2856 JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
2858 JointCond = FatalCond ? FatalCond : RecoverableCond;
2861 CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
2862 assert(SanOpts.has(Checked[0].second));
2864 for (int i = 1, n = Checked.size(); i < n; ++i) {
2865 assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
2866 "All recoverable kinds in a single check must be same!");
2867 assert(SanOpts.has(Checked[i].second));
2871 llvm::BasicBlock *Cont = createBasicBlock("cont");
2872 llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
2873 llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
2874 // Give hint that we very much don't expect to execute the handler
2875 // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
2876 llvm::MDBuilder MDHelper(getLLVMContext());
2877 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2878 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
2879 EmitBlock(Handlers);
2881 // Handler functions take an i8* pointing to the (handler-specific) static
2882 // information block, followed by a sequence of intptr_t arguments
2883 // representing operand values.
2884 SmallVector<llvm::Value *, 4> Args;
2885 SmallVector<llvm::Type *, 4> ArgTypes;
2886 if (!CGM.getCodeGenOpts().SanitizeMinimalRuntime) {
2887 Args.reserve(DynamicArgs.size() + 1);
2888 ArgTypes.reserve(DynamicArgs.size() + 1);
2890 // Emit handler arguments and create handler function type.
2891 if (!StaticArgs.empty()) {
2892 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2894 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2895 llvm::GlobalVariable::PrivateLinkage, Info);
2896 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2897 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2898 Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
2899 ArgTypes.push_back(Int8PtrTy);
2902 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
2903 Args.push_back(EmitCheckValue(DynamicArgs[i]));
2904 ArgTypes.push_back(IntPtrTy);
2908 llvm::FunctionType *FnType =
2909 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
2911 if (!FatalCond || !RecoverableCond) {
2912 // Simple case: we need to generate a single handler call, either
2913 // fatal, or non-fatal.
2914 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind,
2915 (FatalCond != nullptr), Cont);
2917 // Emit two handler calls: first one for set of unrecoverable checks,
2918 // another one for recoverable.
2919 llvm::BasicBlock *NonFatalHandlerBB =
2920 createBasicBlock("non_fatal." + CheckName);
2921 llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
2922 Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
2923 EmitBlock(FatalHandlerBB);
2924 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, true,
2926 EmitBlock(NonFatalHandlerBB);
2927 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, false,
2934 void CodeGenFunction::EmitCfiSlowPathCheck(
2935 SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId,
2936 llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) {
2937 llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
2939 llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
2940 llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
2942 llvm::MDBuilder MDHelper(getLLVMContext());
2943 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2944 BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
2948 bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind);
2950 llvm::CallInst *CheckCall;
2952 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2954 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2955 llvm::GlobalVariable::PrivateLinkage, Info);
2956 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2957 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2959 llvm::Constant *SlowPathDiagFn = CGM.getModule().getOrInsertFunction(
2960 "__cfi_slowpath_diag",
2961 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
2963 CheckCall = Builder.CreateCall(
2965 {TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)});
2967 llvm::Constant *SlowPathFn = CGM.getModule().getOrInsertFunction(
2969 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
2970 CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
2973 CheckCall->setDoesNotThrow();
2978 // Emit a stub for __cfi_check function so that the linker knows about this
2979 // symbol in LTO mode.
2980 void CodeGenFunction::EmitCfiCheckStub() {
2981 llvm::Module *M = &CGM.getModule();
2982 auto &Ctx = M->getContext();
2983 llvm::Function *F = llvm::Function::Create(
2984 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy}, false),
2985 llvm::GlobalValue::WeakAnyLinkage, "__cfi_check", M);
2986 llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx, "entry", F);
2987 // FIXME: consider emitting an intrinsic call like
2988 // call void @llvm.cfi_check(i64 %0, i8* %1, i8* %2)
2989 // which can be lowered in CrossDSOCFI pass to the actual contents of
2990 // __cfi_check. This would allow inlining of __cfi_check calls.
2991 llvm::CallInst::Create(
2992 llvm::Intrinsic::getDeclaration(M, llvm::Intrinsic::trap), "", BB);
2993 llvm::ReturnInst::Create(Ctx, nullptr, BB);
2996 // This function is basically a switch over the CFI failure kind, which is
2997 // extracted from CFICheckFailData (1st function argument). Each case is either
2998 // llvm.trap or a call to one of the two runtime handlers, based on
2999 // -fsanitize-trap and -fsanitize-recover settings. Default case (invalid
3000 // failure kind) traps, but this should really never happen. CFICheckFailData
3001 // can be nullptr if the calling module has -fsanitize-trap behavior for this
3002 // check kind; in this case __cfi_check_fail traps as well.
3003 void CodeGenFunction::EmitCfiCheckFail() {
3004 SanitizerScope SanScope(this);
3005 FunctionArgList Args;
3006 ImplicitParamDecl ArgData(getContext(), getContext().VoidPtrTy,
3007 ImplicitParamDecl::Other);
3008 ImplicitParamDecl ArgAddr(getContext(), getContext().VoidPtrTy,
3009 ImplicitParamDecl::Other);
3010 Args.push_back(&ArgData);
3011 Args.push_back(&ArgAddr);
3013 const CGFunctionInfo &FI =
3014 CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args);
3016 llvm::Function *F = llvm::Function::Create(
3017 llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false),
3018 llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule());
3019 F->setVisibility(llvm::GlobalValue::HiddenVisibility);
3021 StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args,
3025 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false,
3026 CGM.getContext().VoidPtrTy, ArgData.getLocation());
3028 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false,
3029 CGM.getContext().VoidPtrTy, ArgAddr.getLocation());
3031 // Data == nullptr means the calling module has trap behaviour for this check.
3032 llvm::Value *DataIsNotNullPtr =
3033 Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy));
3034 EmitTrapCheck(DataIsNotNullPtr);
3036 llvm::StructType *SourceLocationTy =
3037 llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty);
3038 llvm::StructType *CfiCheckFailDataTy =
3039 llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy);
3041 llvm::Value *V = Builder.CreateConstGEP2_32(
3043 Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0,
3045 Address CheckKindAddr(V, getIntAlign());
3046 llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr);
3048 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
3049 CGM.getLLVMContext(),
3050 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
3051 llvm::Value *ValidVtable = Builder.CreateZExt(
3052 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
3053 {Addr, AllVtables}),
3056 const std::pair<int, SanitizerMask> CheckKinds[] = {
3057 {CFITCK_VCall, SanitizerKind::CFIVCall},
3058 {CFITCK_NVCall, SanitizerKind::CFINVCall},
3059 {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast},
3060 {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast},
3061 {CFITCK_ICall, SanitizerKind::CFIICall}};
3063 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 5> Checks;
3064 for (auto CheckKindMaskPair : CheckKinds) {
3065 int Kind = CheckKindMaskPair.first;
3066 SanitizerMask Mask = CheckKindMaskPair.second;
3068 Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind));
3069 if (CGM.getLangOpts().Sanitize.has(Mask))
3070 EmitCheck(std::make_pair(Cond, Mask), SanitizerHandler::CFICheckFail, {},
3071 {Data, Addr, ValidVtable});
3073 EmitTrapCheck(Cond);
3077 // The only reference to this function will be created during LTO link.
3078 // Make sure it survives until then.
3079 CGM.addUsedGlobal(F);
3082 void CodeGenFunction::EmitUnreachable(SourceLocation Loc) {
3083 if (SanOpts.has(SanitizerKind::Unreachable)) {
3084 SanitizerScope SanScope(this);
3085 EmitCheck(std::make_pair(static_cast<llvm::Value *>(Builder.getFalse()),
3086 SanitizerKind::Unreachable),
3087 SanitizerHandler::BuiltinUnreachable,
3088 EmitCheckSourceLocation(Loc), None);
3090 Builder.CreateUnreachable();
3093 void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) {
3094 llvm::BasicBlock *Cont = createBasicBlock("cont");
3096 // If we're optimizing, collapse all calls to trap down to just one per
3097 // function to save on code size.
3098 if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
3099 TrapBB = createBasicBlock("trap");
3100 Builder.CreateCondBr(Checked, Cont, TrapBB);
3102 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
3103 TrapCall->setDoesNotReturn();
3104 TrapCall->setDoesNotThrow();
3105 Builder.CreateUnreachable();
3107 Builder.CreateCondBr(Checked, Cont, TrapBB);
3113 llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
3114 llvm::CallInst *TrapCall = Builder.CreateCall(CGM.getIntrinsic(IntrID));
3116 if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
3117 auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
3118 CGM.getCodeGenOpts().TrapFuncName);
3119 TrapCall->addAttribute(llvm::AttributeList::FunctionIndex, A);
3125 Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E,
3126 LValueBaseInfo *BaseInfo,
3127 TBAAAccessInfo *TBAAInfo) {
3128 assert(E->getType()->isArrayType() &&
3129 "Array to pointer decay must have array source type!");
3131 // Expressions of array type can't be bitfields or vector elements.
3132 LValue LV = EmitLValue(E);
3133 Address Addr = LV.getAddress();
3135 // If the array type was an incomplete type, we need to make sure
3136 // the decay ends up being the right type.
3137 llvm::Type *NewTy = ConvertType(E->getType());
3138 Addr = Builder.CreateElementBitCast(Addr, NewTy);
3140 // Note that VLA pointers are always decayed, so we don't need to do
3142 if (!E->getType()->isVariableArrayType()) {
3143 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3144 "Expected pointer to array");
3145 Addr = Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(), "arraydecay");
3148 // The result of this decay conversion points to an array element within the
3149 // base lvalue. However, since TBAA currently does not support representing
3150 // accesses to elements of member arrays, we conservatively represent accesses
3151 // to the pointee object as if it had no any base lvalue specified.
3152 // TODO: Support TBAA for member arrays.
3153 QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
3154 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
3155 if (TBAAInfo) *TBAAInfo = CGM.getTBAAAccessInfo(EltType);
3157 return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType));
3160 /// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
3161 /// array to pointer, return the array subexpression.
3162 static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
3163 // If this isn't just an array->pointer decay, bail out.
3164 const auto *CE = dyn_cast<CastExpr>(E);
3165 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
3168 // If this is a decay from variable width array, bail out.
3169 const Expr *SubExpr = CE->getSubExpr();
3170 if (SubExpr->getType()->isVariableArrayType())
3176 static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF,
3178 ArrayRef<llvm::Value*> indices,
3182 const llvm::Twine &name = "arrayidx") {
3184 return CGF.EmitCheckedInBoundsGEP(ptr, indices, signedIndices,
3185 CodeGenFunction::NotSubtraction, loc,
3188 return CGF.Builder.CreateGEP(ptr, indices, name);
3192 static CharUnits getArrayElementAlign(CharUnits arrayAlign,
3194 CharUnits eltSize) {
3195 // If we have a constant index, we can use the exact offset of the
3196 // element we're accessing.
3197 if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
3198 CharUnits offset = constantIdx->getZExtValue() * eltSize;
3199 return arrayAlign.alignmentAtOffset(offset);
3201 // Otherwise, use the worst-case alignment for any element.
3203 return arrayAlign.alignmentOfArrayElement(eltSize);
3207 static QualType getFixedSizeElementType(const ASTContext &ctx,
3208 const VariableArrayType *vla) {
3211 eltType = vla->getElementType();
3212 } while ((vla = ctx.getAsVariableArrayType(eltType)));
3216 static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
3217 ArrayRef<llvm::Value *> indices,
3218 QualType eltType, bool inbounds,
3219 bool signedIndices, SourceLocation loc,
3220 const llvm::Twine &name = "arrayidx") {
3221 // All the indices except that last must be zero.
3223 for (auto idx : indices.drop_back())
3224 assert(isa<llvm::ConstantInt>(idx) &&
3225 cast<llvm::ConstantInt>(idx)->isZero());
3228 // Determine the element size of the statically-sized base. This is
3229 // the thing that the indices are expressed in terms of.
3230 if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
3231 eltType = getFixedSizeElementType(CGF.getContext(), vla);
3234 // We can use that to compute the best alignment of the element.
3235 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
3236 CharUnits eltAlign =
3237 getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
3239 llvm::Value *eltPtr = emitArraySubscriptGEP(
3240 CGF, addr.getPointer(), indices, inbounds, signedIndices, loc, name);
3241 return Address(eltPtr, eltAlign);
3244 LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
3246 // The index must always be an integer, which is not an aggregate. Emit it
3247 // in lexical order (this complexity is, sadly, required by C++17).
3248 llvm::Value *IdxPre =
3249 (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E->getIdx()) : nullptr;
3250 bool SignedIndices = false;
3251 auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * {
3253 if (E->getLHS() != E->getIdx()) {
3254 assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS");
3255 Idx = EmitScalarExpr(E->getIdx());
3258 QualType IdxTy = E->getIdx()->getType();
3259 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
3260 SignedIndices |= IdxSigned;
3262 if (SanOpts.has(SanitizerKind::ArrayBounds))
3263 EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
3265 // Extend or truncate the index type to 32 or 64-bits.
3266 if (Promote && Idx->getType() != IntPtrTy)
3267 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
3273 // If the base is a vector type, then we are forming a vector element lvalue
3274 // with this subscript.
3275 if (E->getBase()->getType()->isVectorType() &&
3276 !isa<ExtVectorElementExpr>(E->getBase())) {
3277 // Emit the vector as an lvalue to get its address.
3278 LValue LHS = EmitLValue(E->getBase());
3279 auto *Idx = EmitIdxAfterBase(/*Promote*/false);
3280 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
3281 return LValue::MakeVectorElt(LHS.getAddress(), Idx, E->getBase()->getType(),
3282 LHS.getBaseInfo(), TBAAAccessInfo());
3285 // All the other cases basically behave like simple offsetting.
3287 // Handle the extvector case we ignored above.
3288 if (isa<ExtVectorElementExpr>(E->getBase())) {
3289 LValue LV = EmitLValue(E->getBase());
3290 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3291 Address Addr = EmitExtVectorElementLValue(LV);
3293 QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
3294 Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true,
3295 SignedIndices, E->getExprLoc());
3296 return MakeAddrLValue(Addr, EltType, LV.getBaseInfo(),
3297 CGM.getTBAAInfoForSubobject(LV, EltType));
3300 LValueBaseInfo EltBaseInfo;
3301 TBAAAccessInfo EltTBAAInfo;
3302 Address Addr = Address::invalid();
3303 if (const VariableArrayType *vla =
3304 getContext().getAsVariableArrayType(E->getType())) {
3305 // The base must be a pointer, which is not an aggregate. Emit
3306 // it. It needs to be emitted first in case it's what captures
3308 Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
3309 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3311 // The element count here is the total number of non-VLA elements.
3312 llvm::Value *numElements = getVLASize(vla).first;
3314 // Effectively, the multiply by the VLA size is part of the GEP.
3315 // GEP indexes are signed, and scaling an index isn't permitted to
3316 // signed-overflow, so we use the same semantics for our explicit
3317 // multiply. We suppress this if overflow is not undefined behavior.
3318 if (getLangOpts().isSignedOverflowDefined()) {
3319 Idx = Builder.CreateMul(Idx, numElements);
3321 Idx = Builder.CreateNSWMul(Idx, numElements);
3324 Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
3325 !getLangOpts().isSignedOverflowDefined(),
3326 SignedIndices, E->getExprLoc());
3328 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
3329 // Indexing over an interface, as in "NSString *P; P[4];"
3331 // Emit the base pointer.
3332 Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
3333 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3335 CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
3336 llvm::Value *InterfaceSizeVal =
3337 llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());
3339 llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
3341 // We don't necessarily build correct LLVM struct types for ObjC
3342 // interfaces, so we can't rely on GEP to do this scaling
3343 // correctly, so we need to cast to i8*. FIXME: is this actually
3344 // true? A lot of other things in the fragile ABI would break...
3345 llvm::Type *OrigBaseTy = Addr.getType();
3346 Addr = Builder.CreateElementBitCast(Addr, Int8Ty);
3349 CharUnits EltAlign =
3350 getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
3351 llvm::Value *EltPtr =
3352 emitArraySubscriptGEP(*this, Addr.getPointer(), ScaledIdx, false,
3353 SignedIndices, E->getExprLoc());
3354 Addr = Address(EltPtr, EltAlign);
3357 Addr = Builder.CreateBitCast(Addr, OrigBaseTy);
3358 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3359 // If this is A[i] where A is an array, the frontend will have decayed the
3360 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3361 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3362 // "gep x, i" here. Emit one "gep A, 0, i".
3363 assert(Array->getType()->isArrayType() &&
3364 "Array to pointer decay must have array source type!");
3366 // For simple multidimensional array indexing, set the 'accessed' flag for
3367 // better bounds-checking of the base expression.
3368 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3369 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3371 ArrayLV = EmitLValue(Array);
3372 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3374 // Propagate the alignment from the array itself to the result.
3375 Addr = emitArraySubscriptGEP(
3376 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
3377 E->getType(), !getLangOpts().isSignedOverflowDefined(), SignedIndices,
3379 EltBaseInfo = ArrayLV.getBaseInfo();
3380 EltTBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, E->getType());
3382 // The base must be a pointer; emit it with an estimate of its alignment.
3383 Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
3384 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3385 Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
3386 !getLangOpts().isSignedOverflowDefined(),
3387 SignedIndices, E->getExprLoc());
3390 LValue LV = MakeAddrLValue(Addr, E->getType(), EltBaseInfo, EltTBAAInfo);
3392 if (getLangOpts().ObjC1 &&
3393 getLangOpts().getGC() != LangOptions::NonGC) {
3394 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
3395 setObjCGCLValueClass(getContext(), E, LV);
3400 static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base,
3401 LValueBaseInfo &BaseInfo,
3402 TBAAAccessInfo &TBAAInfo,
3403 QualType BaseTy, QualType ElTy,
3404 bool IsLowerBound) {
3406 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParenImpCasts())) {
3407 BaseLVal = CGF.EmitOMPArraySectionExpr(ASE, IsLowerBound);
3408 if (BaseTy->isArrayType()) {
3409 Address Addr = BaseLVal.getAddress();
3410 BaseInfo = BaseLVal.getBaseInfo();
3412 // If the array type was an incomplete type, we need to make sure
3413 // the decay ends up being the right type.
3414 llvm::Type *NewTy = CGF.ConvertType(BaseTy);
3415 Addr = CGF.Builder.CreateElementBitCast(Addr, NewTy);
3417 // Note that VLA pointers are always decayed, so we don't need to do
3419 if (!BaseTy->isVariableArrayType()) {
3420 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3421 "Expected pointer to array");
3422 Addr = CGF.Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(),
3426 return CGF.Builder.CreateElementBitCast(Addr,
3427 CGF.ConvertTypeForMem(ElTy));
3429 LValueBaseInfo TypeBaseInfo;
3430 TBAAAccessInfo TypeTBAAInfo;
3431 CharUnits Align = CGF.getNaturalTypeAlignment(ElTy, &TypeBaseInfo,
3433 BaseInfo.mergeForCast(TypeBaseInfo);
3434 TBAAInfo = CGF.CGM.mergeTBAAInfoForCast(TBAAInfo, TypeTBAAInfo);
3435 return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress()), Align);
3437 return CGF.EmitPointerWithAlignment(Base, &BaseInfo, &TBAAInfo);
3440 LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
3441 bool IsLowerBound) {
3442 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(E->getBase());
3443 QualType ResultExprTy;
3444 if (auto *AT = getContext().getAsArrayType(BaseTy))
3445 ResultExprTy = AT->getElementType();
3447 ResultExprTy = BaseTy->getPointeeType();
3448 llvm::Value *Idx = nullptr;
3449 if (IsLowerBound || E->getColonLoc().isInvalid()) {
3450 // Requesting lower bound or upper bound, but without provided length and
3451 // without ':' symbol for the default length -> length = 1.
3452 // Idx = LowerBound ?: 0;
3453 if (auto *LowerBound = E->getLowerBound()) {
3454 Idx = Builder.CreateIntCast(
3455 EmitScalarExpr(LowerBound), IntPtrTy,
3456 LowerBound->getType()->hasSignedIntegerRepresentation());
3458 Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
3460 // Try to emit length or lower bound as constant. If this is possible, 1
3461 // is subtracted from constant length or lower bound. Otherwise, emit LLVM
3462 // IR (LB + Len) - 1.
3463 auto &C = CGM.getContext();
3464 auto *Length = E->getLength();
3465 llvm::APSInt ConstLength;
3467 // Idx = LowerBound + Length - 1;
3468 if (Length->isIntegerConstantExpr(ConstLength, C)) {
3469 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3472 auto *LowerBound = E->getLowerBound();
3473 llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
3474 if (LowerBound && LowerBound->isIntegerConstantExpr(ConstLowerBound, C)) {
3475 ConstLowerBound = ConstLowerBound.zextOrTrunc(PointerWidthInBits);
3476 LowerBound = nullptr;
3480 else if (!LowerBound)
3483 if (Length || LowerBound) {
3484 auto *LowerBoundVal =
3486 ? Builder.CreateIntCast(
3487 EmitScalarExpr(LowerBound), IntPtrTy,
3488 LowerBound->getType()->hasSignedIntegerRepresentation())
3489 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
3492 ? Builder.CreateIntCast(
3493 EmitScalarExpr(Length), IntPtrTy,
3494 Length->getType()->hasSignedIntegerRepresentation())
3495 : llvm::ConstantInt::get(IntPtrTy, ConstLength);
3496 Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
3498 !getLangOpts().isSignedOverflowDefined());
3499 if (Length && LowerBound) {
3500 Idx = Builder.CreateSub(
3501 Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
3502 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3505 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
3507 // Idx = ArraySize - 1;
3508 QualType ArrayTy = BaseTy->isPointerType()
3509 ? E->getBase()->IgnoreParenImpCasts()->getType()
3511 if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) {
3512 Length = VAT->getSizeExpr();
3513 if (Length->isIntegerConstantExpr(ConstLength, C))
3516 auto *CAT = C.getAsConstantArrayType(ArrayTy);
3517 ConstLength = CAT->getSize();
3520 auto *LengthVal = Builder.CreateIntCast(
3521 EmitScalarExpr(Length), IntPtrTy,
3522 Length->getType()->hasSignedIntegerRepresentation());
3523 Idx = Builder.CreateSub(
3524 LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
3525 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3527 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3529 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
3535 Address EltPtr = Address::invalid();
3536 LValueBaseInfo BaseInfo;
3537 TBAAAccessInfo TBAAInfo;
3538 if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
3539 // The base must be a pointer, which is not an aggregate. Emit
3540 // it. It needs to be emitted first in case it's what captures
3543 emitOMPArraySectionBase(*this, E->getBase(), BaseInfo, TBAAInfo,
3544 BaseTy, VLA->getElementType(), IsLowerBound);
3545 // The element count here is the total number of non-VLA elements.
3546 llvm::Value *NumElements = getVLASize(VLA).first;
3548 // Effectively, the multiply by the VLA size is part of the GEP.
3549 // GEP indexes are signed, and scaling an index isn't permitted to
3550 // signed-overflow, so we use the same semantics for our explicit
3551 // multiply. We suppress this if overflow is not undefined behavior.
3552 if (getLangOpts().isSignedOverflowDefined())
3553 Idx = Builder.CreateMul(Idx, NumElements);
3555 Idx = Builder.CreateNSWMul(Idx, NumElements);
3556 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(),
3557 !getLangOpts().isSignedOverflowDefined(),
3558 /*SignedIndices=*/false, E->getExprLoc());
3559 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3560 // If this is A[i] where A is an array, the frontend will have decayed the
3561 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3562 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3563 // "gep x, i" here. Emit one "gep A, 0, i".
3564 assert(Array->getType()->isArrayType() &&
3565 "Array to pointer decay must have array source type!");
3567 // For simple multidimensional array indexing, set the 'accessed' flag for
3568 // better bounds-checking of the base expression.
3569 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3570 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3572 ArrayLV = EmitLValue(Array);
3574 // Propagate the alignment from the array itself to the result.
3575 EltPtr = emitArraySubscriptGEP(
3576 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
3577 ResultExprTy, !getLangOpts().isSignedOverflowDefined(),
3578 /*SignedIndices=*/false, E->getExprLoc());
3579 BaseInfo = ArrayLV.getBaseInfo();
3580 TBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, ResultExprTy);
3582 Address Base = emitOMPArraySectionBase(*this, E->getBase(), BaseInfo,
3583 TBAAInfo, BaseTy, ResultExprTy,
3585 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy,
3586 !getLangOpts().isSignedOverflowDefined(),
3587 /*SignedIndices=*/false, E->getExprLoc());
3590 return MakeAddrLValue(EltPtr, ResultExprTy, BaseInfo, TBAAInfo);
3593 LValue CodeGenFunction::
3594 EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
3595 // Emit the base vector as an l-value.
3598 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
3600 // If it is a pointer to a vector, emit the address and form an lvalue with
3602 LValueBaseInfo BaseInfo;
3603 TBAAAccessInfo TBAAInfo;
3604 Address Ptr = EmitPointerWithAlignment(E->getBase(), &BaseInfo, &TBAAInfo);
3605 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
3606 Base = MakeAddrLValue(Ptr, PT->getPointeeType(), BaseInfo, TBAAInfo);
3607 Base.getQuals().removeObjCGCAttr();
3608 } else if (E->getBase()->isGLValue()) {
3609 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
3610 // emit the base as an lvalue.
3611 assert(E->getBase()->getType()->isVectorType());
3612 Base = EmitLValue(E->getBase());
3614 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
3615 assert(E->getBase()->getType()->isVectorType() &&
3616 "Result must be a vector");
3617 llvm::Value *Vec = EmitScalarExpr(E->getBase());
3619 // Store the vector to memory (because LValue wants an address).
3620 Address VecMem = CreateMemTemp(E->getBase()->getType());
3621 Builder.CreateStore(Vec, VecMem);
3622 Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
3623 AlignmentSource::Decl);
3627 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
3629 // Encode the element access list into a vector of unsigned indices.
3630 SmallVector<uint32_t, 4> Indices;
3631 E->getEncodedElementAccess(Indices);
3633 if (Base.isSimple()) {
3634 llvm::Constant *CV =
3635 llvm::ConstantDataVector::get(getLLVMContext(), Indices);
3636 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
3637 Base.getBaseInfo(), TBAAAccessInfo());
3639 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
3641 llvm::Constant *BaseElts = Base.getExtVectorElts();
3642 SmallVector<llvm::Constant *, 4> CElts;
3644 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
3645 CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
3646 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
3647 return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
3648 Base.getBaseInfo(), TBAAAccessInfo());
3651 LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
3652 if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, E)) {
3653 EmitIgnoredExpr(E->getBase());
3654 return EmitDeclRefLValue(DRE);
3657 Expr *BaseExpr = E->getBase();
3658 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
3661 LValueBaseInfo BaseInfo;
3662 TBAAAccessInfo TBAAInfo;
3663 Address Addr = EmitPointerWithAlignment(BaseExpr, &BaseInfo, &TBAAInfo);
3664 QualType PtrTy = BaseExpr->getType()->getPointeeType();
3665 SanitizerSet SkippedChecks;
3666 bool IsBaseCXXThis = IsWrappedCXXThis(BaseExpr);
3668 SkippedChecks.set(SanitizerKind::Alignment, true);
3669 if (IsBaseCXXThis || isa<DeclRefExpr>(BaseExpr))
3670 SkippedChecks.set(SanitizerKind::Null, true);
3671 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy,
3672 /*Alignment=*/CharUnits::Zero(), SkippedChecks);
3673 BaseLV = MakeAddrLValue(Addr, PtrTy, BaseInfo, TBAAInfo);
3675 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
3677 NamedDecl *ND = E->getMemberDecl();
3678 if (auto *Field = dyn_cast<FieldDecl>(ND)) {
3679 LValue LV = EmitLValueForField(BaseLV, Field);
3680 setObjCGCLValueClass(getContext(), E, LV);
3684 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
3685 return EmitFunctionDeclLValue(*this, E, FD);
3687 llvm_unreachable("Unhandled member declaration!");
3690 /// Given that we are currently emitting a lambda, emit an l-value for
3691 /// one of its members.
3692 LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
3693 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
3694 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
3695 QualType LambdaTagType =
3696 getContext().getTagDeclType(Field->getParent());
3697 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
3698 return EmitLValueForField(LambdaLV, Field);
3701 /// Drill down to the storage of a field without walking into
3702 /// reference types.
3704 /// The resulting address doesn't necessarily have the right type.
3705 static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
3706 const FieldDecl *field) {
3707 const RecordDecl *rec = field->getParent();
3710 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
3713 // Adjust the alignment down to the given offset.
3714 // As a special case, if the LLVM field index is 0, we know that this
3716 assert((idx != 0 || CGF.getContext().getASTRecordLayout(rec)
3717 .getFieldOffset(field->getFieldIndex()) == 0) &&
3718 "LLVM field at index zero had non-zero offset?");
3720 auto &recLayout = CGF.getContext().getASTRecordLayout(rec);
3721 auto offsetInBits = recLayout.getFieldOffset(field->getFieldIndex());
3722 offset = CGF.getContext().toCharUnitsFromBits(offsetInBits);
3725 return CGF.Builder.CreateStructGEP(base, idx, offset, field->getName());
3728 static bool hasAnyVptr(const QualType Type, const ASTContext &Context) {
3729 const auto *RD = Type.getTypePtr()->getAsCXXRecordDecl();
3733 if (RD->isDynamicClass())
3736 for (const auto &Base : RD->bases())
3737 if (hasAnyVptr(Base.getType(), Context))
3740 for (const FieldDecl *Field : RD->fields())
3741 if (hasAnyVptr(Field->getType(), Context))
3747 LValue CodeGenFunction::EmitLValueForField(LValue base,
3748 const FieldDecl *field) {
3749 LValueBaseInfo BaseInfo = base.getBaseInfo();
3751 if (field->isBitField()) {
3752 const CGRecordLayout &RL =
3753 CGM.getTypes().getCGRecordLayout(field->getParent());
3754 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
3755 Address Addr = base.getAddress();
3756 unsigned Idx = RL.getLLVMFieldNo(field);
3758 // For structs, we GEP to the field that the record layout suggests.
3759 Addr = Builder.CreateStructGEP(Addr, Idx, Info.StorageOffset,
3761 // Get the access type.
3762 llvm::Type *FieldIntTy =
3763 llvm::Type::getIntNTy(getLLVMContext(), Info.StorageSize);
3764 if (Addr.getElementType() != FieldIntTy)
3765 Addr = Builder.CreateElementBitCast(Addr, FieldIntTy);
3767 QualType fieldType =
3768 field->getType().withCVRQualifiers(base.getVRQualifiers());
3769 // TODO: Support TBAA for bit fields.
3770 LValueBaseInfo FieldBaseInfo(BaseInfo.getAlignmentSource());
3771 return LValue::MakeBitfield(Addr, Info, fieldType, FieldBaseInfo,
3775 // Fields of may-alias structures are may-alias themselves.
3776 // FIXME: this should get propagated down through anonymous structs
3778 QualType FieldType = field->getType();
3779 const RecordDecl *rec = field->getParent();
3780 AlignmentSource BaseAlignSource = BaseInfo.getAlignmentSource();
3781 LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(BaseAlignSource));
3782 TBAAAccessInfo FieldTBAAInfo;
3783 if (base.getTBAAInfo().isMayAlias() ||
3784 rec->hasAttr<MayAliasAttr>() || FieldType->isVectorType()) {
3785 FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
3786 } else if (rec->isUnion()) {
3787 // TODO: Support TBAA for unions.
3788 FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
3790 // If no base type been assigned for the base access, then try to generate
3791 // one for this base lvalue.
3792 FieldTBAAInfo = base.getTBAAInfo();
3793 if (!FieldTBAAInfo.BaseType) {
3794 FieldTBAAInfo.BaseType = CGM.getTBAABaseTypeInfo(base.getType());
3795 assert(!FieldTBAAInfo.Offset &&
3796 "Nonzero offset for an access with no base type!");
3799 // Adjust offset to be relative to the base type.
3800 const ASTRecordLayout &Layout =
3801 getContext().getASTRecordLayout(field->getParent());
3802 unsigned CharWidth = getContext().getCharWidth();
3803 if (FieldTBAAInfo.BaseType)
3804 FieldTBAAInfo.Offset +=
3805 Layout.getFieldOffset(field->getFieldIndex()) / CharWidth;
3807 // Update the final access type and size.
3808 FieldTBAAInfo.AccessType = CGM.getTBAATypeInfo(FieldType);
3809 FieldTBAAInfo.Size =
3810 getContext().getTypeSizeInChars(FieldType).getQuantity();
3813 Address addr = base.getAddress();
3814 unsigned RecordCVR = base.getVRQualifiers();
3815 if (rec->isUnion()) {
3816 // For unions, there is no pointer adjustment.
3817 assert(!FieldType->isReferenceType() && "union has reference member");
3818 if (CGM.getCodeGenOpts().StrictVTablePointers &&
3819 hasAnyVptr(FieldType, getContext()))
3820 // Because unions can easily skip invariant.barriers, we need to add
3821 // a barrier every time CXXRecord field with vptr is referenced.
3822 addr = Address(Builder.CreateInvariantGroupBarrier(addr.getPointer()),
3823 addr.getAlignment());
3825 // For structs, we GEP to the field that the record layout suggests.
3826 addr = emitAddrOfFieldStorage(*this, addr, field);
3828 // If this is a reference field, load the reference right now.
3829 if (FieldType->isReferenceType()) {
3830 LValue RefLVal = MakeAddrLValue(addr, FieldType, FieldBaseInfo,
3832 if (RecordCVR & Qualifiers::Volatile)
3833 RefLVal.getQuals().setVolatile(true);
3834 addr = EmitLoadOfReference(RefLVal, &FieldBaseInfo, &FieldTBAAInfo);
3836 // Qualifiers on the struct don't apply to the referencee.
3838 FieldType = FieldType->getPointeeType();
3842 // Make sure that the address is pointing to the right type. This is critical
3843 // for both unions and structs. A union needs a bitcast, a struct element
3844 // will need a bitcast if the LLVM type laid out doesn't match the desired
3846 addr = Builder.CreateElementBitCast(
3847 addr, CGM.getTypes().ConvertTypeForMem(FieldType), field->getName());
3849 if (field->hasAttr<AnnotateAttr>())
3850 addr = EmitFieldAnnotations(field, addr);
3852 LValue LV = MakeAddrLValue(addr, FieldType, FieldBaseInfo, FieldTBAAInfo);
3853 LV.getQuals().addCVRQualifiers(RecordCVR);
3855 // __weak attribute on a field is ignored.
3856 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
3857 LV.getQuals().removeObjCGCAttr();
3863 CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
3864 const FieldDecl *Field) {
3865 QualType FieldType = Field->getType();
3867 if (!FieldType->isReferenceType())
3868 return EmitLValueForField(Base, Field);
3870 Address V = emitAddrOfFieldStorage(*this, Base.getAddress(), Field);
3872 // Make sure that the address is pointing to the right type.
3873 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
3874 V = Builder.CreateElementBitCast(V, llvmType, Field->getName());
3876 // TODO: Generate TBAA information that describes this access as a structure
3877 // member access and not just an access to an object of the field's type. This
3878 // should be similar to what we do in EmitLValueForField().
3879 LValueBaseInfo BaseInfo = Base.getBaseInfo();
3880 AlignmentSource FieldAlignSource = BaseInfo.getAlignmentSource();
3881 LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(FieldAlignSource));
3882 return MakeAddrLValue(V, FieldType, FieldBaseInfo,
3883 CGM.getTBAAInfoForSubobject(Base, FieldType));
3886 LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
3887 if (E->isFileScope()) {
3888 ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
3889 return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl);
3891 if (E->getType()->isVariablyModifiedType())
3892 // make sure to emit the VLA size.
3893 EmitVariablyModifiedType(E->getType());
3895 Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
3896 const Expr *InitExpr = E->getInitializer();
3897 LValue Result = MakeAddrLValue(DeclPtr, E->getType(), AlignmentSource::Decl);
3899 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
3905 LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
3906 if (!E->isGLValue())
3907 // Initializing an aggregate temporary in C++11: T{...}.
3908 return EmitAggExprToLValue(E);
3910 // An lvalue initializer list must be initializing a reference.
3911 assert(E->isTransparent() && "non-transparent glvalue init list");
3912 return EmitLValue(E->getInit(0));
3915 /// Emit the operand of a glvalue conditional operator. This is either a glvalue
3916 /// or a (possibly-parenthesized) throw-expression. If this is a throw, no
3917 /// LValue is returned and the current block has been terminated.
3918 static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
3919 const Expr *Operand) {
3920 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
3921 CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
3925 return CGF.EmitLValue(Operand);
3928 LValue CodeGenFunction::
3929 EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
3930 if (!expr->isGLValue()) {
3931 // ?: here should be an aggregate.
3932 assert(hasAggregateEvaluationKind(expr->getType()) &&
3933 "Unexpected conditional operator!");
3934 return EmitAggExprToLValue(expr);
3937 OpaqueValueMapping binding(*this, expr);
3939 const Expr *condExpr = expr->getCond();
3941 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
3942 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
3943 if (!CondExprBool) std::swap(live, dead);
3945 if (!ContainsLabel(dead)) {
3946 // If the true case is live, we need to track its region.
3948 incrementProfileCounter(expr);
3949 return EmitLValue(live);
3953 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
3954 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
3955 llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
3957 ConditionalEvaluation eval(*this);
3958 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr));
3960 // Any temporaries created here are conditional.
3961 EmitBlock(lhsBlock);
3962 incrementProfileCounter(expr);
3964 Optional<LValue> lhs =
3965 EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
3968 if (lhs && !lhs->isSimple())
3969 return EmitUnsupportedLValue(expr, "conditional operator");
3971 lhsBlock = Builder.GetInsertBlock();
3973 Builder.CreateBr(contBlock);
3975 // Any temporaries created here are conditional.
3976 EmitBlock(rhsBlock);
3978 Optional<LValue> rhs =
3979 EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
3981 if (rhs && !rhs->isSimple())
3982 return EmitUnsupportedLValue(expr, "conditional operator");
3983 rhsBlock = Builder.GetInsertBlock();
3985 EmitBlock(contBlock);
3988 llvm::PHINode *phi = Builder.CreatePHI(lhs->getPointer()->getType(),
3990 phi->addIncoming(lhs->getPointer(), lhsBlock);
3991 phi->addIncoming(rhs->getPointer(), rhsBlock);
3992 Address result(phi, std::min(lhs->getAlignment(), rhs->getAlignment()));
3993 AlignmentSource alignSource =
3994 std::max(lhs->getBaseInfo().getAlignmentSource(),
3995 rhs->getBaseInfo().getAlignmentSource());
3996 TBAAAccessInfo TBAAInfo = CGM.mergeTBAAInfoForConditionalOperator(
3997 lhs->getTBAAInfo(), rhs->getTBAAInfo());
3998 return MakeAddrLValue(result, expr->getType(), LValueBaseInfo(alignSource),
4001 assert((lhs || rhs) &&
4002 "both operands of glvalue conditional are throw-expressions?");
4003 return lhs ? *lhs : *rhs;
4007 /// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
4008 /// type. If the cast is to a reference, we can have the usual lvalue result,
4009 /// otherwise if a cast is needed by the code generator in an lvalue context,
4010 /// then it must mean that we need the address of an aggregate in order to
4011 /// access one of its members. This can happen for all the reasons that casts
4012 /// are permitted with aggregate result, including noop aggregate casts, and
4013 /// cast from scalar to union.
4014 LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
4015 switch (E->getCastKind()) {
4018 case CK_ArrayToPointerDecay:
4019 case CK_FunctionToPointerDecay:
4020 case CK_NullToMemberPointer:
4021 case CK_NullToPointer:
4022 case CK_IntegralToPointer:
4023 case CK_PointerToIntegral:
4024 case CK_PointerToBoolean:
4025 case CK_VectorSplat:
4026 case CK_IntegralCast:
4027 case CK_BooleanToSignedIntegral:
4028 case CK_IntegralToBoolean:
4029 case CK_IntegralToFloating:
4030 case CK_FloatingToIntegral:
4031 case CK_FloatingToBoolean:
4032 case CK_FloatingCast:
4033 case CK_FloatingRealToComplex:
4034 case CK_FloatingComplexToReal:
4035 case CK_FloatingComplexToBoolean:
4036 case CK_FloatingComplexCast:
4037 case CK_FloatingComplexToIntegralComplex:
4038 case CK_IntegralRealToComplex:
4039 case CK_IntegralComplexToReal:
4040 case CK_IntegralComplexToBoolean:
4041 case CK_IntegralComplexCast:
4042 case CK_IntegralComplexToFloatingComplex:
4043 case CK_DerivedToBaseMemberPointer:
4044 case CK_BaseToDerivedMemberPointer:
4045 case CK_MemberPointerToBoolean:
4046 case CK_ReinterpretMemberPointer:
4047 case CK_AnyPointerToBlockPointerCast:
4048 case CK_ARCProduceObject:
4049 case CK_ARCConsumeObject:
4050 case CK_ARCReclaimReturnedObject:
4051 case CK_ARCExtendBlockObject:
4052 case CK_CopyAndAutoreleaseBlockObject:
4053 case CK_AddressSpaceConversion:
4054 case CK_IntToOCLSampler:
4055 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
4058 llvm_unreachable("dependent cast kind in IR gen!");
4060 case CK_BuiltinFnToFnPtr:
4061 llvm_unreachable("builtin functions are handled elsewhere");
4063 // These are never l-values; just use the aggregate emission code.
4064 case CK_NonAtomicToAtomic:
4065 case CK_AtomicToNonAtomic:
4066 return EmitAggExprToLValue(E);
4069 LValue LV = EmitLValue(E->getSubExpr());
4070 Address V = LV.getAddress();
4071 const auto *DCE = cast<CXXDynamicCastExpr>(E);
4072 return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
4075 case CK_ConstructorConversion:
4076 case CK_UserDefinedConversion:
4077 case CK_CPointerToObjCPointerCast:
4078 case CK_BlockPointerToObjCPointerCast:
4080 case CK_LValueToRValue:
4081 return EmitLValue(E->getSubExpr());
4083 case CK_UncheckedDerivedToBase:
4084 case CK_DerivedToBase: {
4085 const RecordType *DerivedClassTy =
4086 E->getSubExpr()->getType()->getAs<RecordType>();
4087 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
4089 LValue LV = EmitLValue(E->getSubExpr());
4090 Address This = LV.getAddress();
4092 // Perform the derived-to-base conversion
4093 Address Base = GetAddressOfBaseClass(
4094 This, DerivedClassDecl, E->path_begin(), E->path_end(),
4095 /*NullCheckValue=*/false, E->getExprLoc());
4097 // TODO: Support accesses to members of base classes in TBAA. For now, we
4098 // conservatively pretend that the complete object is of the base class
4100 return MakeAddrLValue(Base, E->getType(), LV.getBaseInfo(),
4101 CGM.getTBAAInfoForSubobject(LV, E->getType()));
4104 return EmitAggExprToLValue(E);
4105 case CK_BaseToDerived: {
4106 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
4107 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
4109 LValue LV = EmitLValue(E->getSubExpr());
4111 // Perform the base-to-derived conversion
4113 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
4114 E->path_begin(), E->path_end(),
4115 /*NullCheckValue=*/false);
4117 // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
4118 // performed and the object is not of the derived type.
4119 if (sanitizePerformTypeCheck())
4120 EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
4121 Derived.getPointer(), E->getType());
4123 if (SanOpts.has(SanitizerKind::CFIDerivedCast))
4124 EmitVTablePtrCheckForCast(E->getType(), Derived.getPointer(),
4125 /*MayBeNull=*/false,
4126 CFITCK_DerivedCast, E->getLocStart());
4128 return MakeAddrLValue(Derived, E->getType(), LV.getBaseInfo(),
4129 CGM.getTBAAInfoForSubobject(LV, E->getType()));
4131 case CK_LValueBitCast: {
4132 // This must be a reinterpret_cast (or c-style equivalent).
4133 const auto *CE = cast<ExplicitCastExpr>(E);
4135 CGM.EmitExplicitCastExprType(CE, this);
4136 LValue LV = EmitLValue(E->getSubExpr());
4137 Address V = Builder.CreateBitCast(LV.getAddress(),
4138 ConvertType(CE->getTypeAsWritten()));
4140 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
4141 EmitVTablePtrCheckForCast(E->getType(), V.getPointer(),
4142 /*MayBeNull=*/false,
4143 CFITCK_UnrelatedCast, E->getLocStart());
4145 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
4146 CGM.getTBAAInfoForSubobject(LV, E->getType()));
4148 case CK_ObjCObjectLValueCast: {
4149 LValue LV = EmitLValue(E->getSubExpr());
4150 Address V = Builder.CreateElementBitCast(LV.getAddress(),
4151 ConvertType(E->getType()));
4152 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
4153 CGM.getTBAAInfoForSubobject(LV, E->getType()));
4155 case CK_ZeroToOCLQueue:
4156 llvm_unreachable("NULL to OpenCL queue lvalue cast is not valid");
4157 case CK_ZeroToOCLEvent:
4158 llvm_unreachable("NULL to OpenCL event lvalue cast is not valid");
4161 llvm_unreachable("Unhandled lvalue cast kind?");
4164 LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
4165 assert(OpaqueValueMappingData::shouldBindAsLValue(e));
4166 return getOpaqueLValueMapping(e);
4169 RValue CodeGenFunction::EmitRValueForField(LValue LV,
4170 const FieldDecl *FD,
4171 SourceLocation Loc) {
4172 QualType FT = FD->getType();
4173 LValue FieldLV = EmitLValueForField(LV, FD);
4174 switch (getEvaluationKind(FT)) {
4176 return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
4178 return FieldLV.asAggregateRValue();
4180 // This routine is used to load fields one-by-one to perform a copy, so
4181 // don't load reference fields.
4182 if (FD->getType()->isReferenceType())
4183 return RValue::get(FieldLV.getPointer());
4184 return EmitLoadOfLValue(FieldLV, Loc);
4186 llvm_unreachable("bad evaluation kind");
4189 //===--------------------------------------------------------------------===//
4190 // Expression Emission
4191 //===--------------------------------------------------------------------===//
4193 RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
4194 ReturnValueSlot ReturnValue) {
4195 // Builtins never have block type.
4196 if (E->getCallee()->getType()->isBlockPointerType())
4197 return EmitBlockCallExpr(E, ReturnValue);
4199 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
4200 return EmitCXXMemberCallExpr(CE, ReturnValue);
4202 if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
4203 return EmitCUDAKernelCallExpr(CE, ReturnValue);
4205 if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
4206 if (const CXXMethodDecl *MD =
4207 dyn_cast_or_null<CXXMethodDecl>(CE->getCalleeDecl()))
4208 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
4210 CGCallee callee = EmitCallee(E->getCallee());
4212 if (callee.isBuiltin()) {
4213 return EmitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(),
4217 if (callee.isPseudoDestructor()) {
4218 return EmitCXXPseudoDestructorExpr(callee.getPseudoDestructorExpr());
4221 return EmitCall(E->getCallee()->getType(), callee, E, ReturnValue);
4224 /// Emit a CallExpr without considering whether it might be a subclass.
4225 RValue CodeGenFunction::EmitSimpleCallExpr(const CallExpr *E,
4226 ReturnValueSlot ReturnValue) {
4227 CGCallee Callee = EmitCallee(E->getCallee());
4228 return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue);
4231 static CGCallee EmitDirectCallee(CodeGenFunction &CGF, const FunctionDecl *FD) {
4232 if (auto builtinID = FD->getBuiltinID()) {
4233 return CGCallee::forBuiltin(builtinID, FD);
4236 llvm::Constant *calleePtr = EmitFunctionDeclPointer(CGF.CGM, FD);
4237 return CGCallee::forDirect(calleePtr, FD);
4240 CGCallee CodeGenFunction::EmitCallee(const Expr *E) {
4241 E = E->IgnoreParens();
4243 // Look through function-to-pointer decay.
4244 if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) {
4245 if (ICE->getCastKind() == CK_FunctionToPointerDecay ||
4246 ICE->getCastKind() == CK_BuiltinFnToFnPtr) {
4247 return EmitCallee(ICE->getSubExpr());
4250 // Resolve direct calls.
4251 } else if (auto DRE = dyn_cast<DeclRefExpr>(E)) {
4252 if (auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
4253 return EmitDirectCallee(*this, FD);
4255 } else if (auto ME = dyn_cast<MemberExpr>(E)) {
4256 if (auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) {
4257 EmitIgnoredExpr(ME->getBase());
4258 return EmitDirectCallee(*this, FD);
4261 // Look through template substitutions.
4262 } else if (auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
4263 return EmitCallee(NTTP->getReplacement());
4265 // Treat pseudo-destructor calls differently.
4266 } else if (auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) {
4267 return CGCallee::forPseudoDestructor(PDE);
4270 // Otherwise, we have an indirect reference.
4271 llvm::Value *calleePtr;
4272 QualType functionType;
4273 if (auto ptrType = E->getType()->getAs<PointerType>()) {
4274 calleePtr = EmitScalarExpr(E);
4275 functionType = ptrType->getPointeeType();
4277 functionType = E->getType();
4278 calleePtr = EmitLValue(E).getPointer();
4280 assert(functionType->isFunctionType());
4281 CGCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(),
4282 E->getReferencedDeclOfCallee());
4283 CGCallee callee(calleeInfo, calleePtr);
4287 LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
4288 // Comma expressions just emit their LHS then their RHS as an l-value.
4289 if (E->getOpcode() == BO_Comma) {
4290 EmitIgnoredExpr(E->getLHS());
4291 EnsureInsertPoint();
4292 return EmitLValue(E->getRHS());
4295 if (E->getOpcode() == BO_PtrMemD ||
4296 E->getOpcode() == BO_PtrMemI)
4297 return EmitPointerToDataMemberBinaryExpr(E);
4299 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
4301 // Note that in all of these cases, __block variables need the RHS
4302 // evaluated first just in case the variable gets moved by the RHS.
4304 switch (getEvaluationKind(E->getType())) {
4306 switch (E->getLHS()->getType().getObjCLifetime()) {
4307 case Qualifiers::OCL_Strong:
4308 return EmitARCStoreStrong(E, /*ignored*/ false).first;
4310 case Qualifiers::OCL_Autoreleasing:
4311 return EmitARCStoreAutoreleasing(E).first;
4313 // No reason to do any of these differently.
4314 case Qualifiers::OCL_None:
4315 case Qualifiers::OCL_ExplicitNone:
4316 case Qualifiers::OCL_Weak:
4320 RValue RV = EmitAnyExpr(E->getRHS());
4321 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
4323 EmitNullabilityCheck(LV, RV.getScalarVal(), E->getExprLoc());
4324 EmitStoreThroughLValue(RV, LV);
4329 return EmitComplexAssignmentLValue(E);
4332 return EmitAggExprToLValue(E);
4334 llvm_unreachable("bad evaluation kind");
4337 LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
4338 RValue RV = EmitCallExpr(E);
4341 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
4342 AlignmentSource::Decl);
4344 assert(E->getCallReturnType(getContext())->isReferenceType() &&
4345 "Can't have a scalar return unless the return type is a "
4348 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
4351 LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
4352 // FIXME: This shouldn't require another copy.
4353 return EmitAggExprToLValue(E);
4356 LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
4357 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
4358 && "binding l-value to type which needs a temporary");
4359 AggValueSlot Slot = CreateAggTemp(E->getType());
4360 EmitCXXConstructExpr(E, Slot);
4361 return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl);
4365 CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
4366 return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType());
4369 Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
4370 return Builder.CreateElementBitCast(CGM.GetAddrOfUuidDescriptor(E),
4371 ConvertType(E->getType()));
4374 LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
4375 return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(),
4376 AlignmentSource::Decl);
4380 CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
4381 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
4382 Slot.setExternallyDestructed();
4383 EmitAggExpr(E->getSubExpr(), Slot);
4384 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
4385 return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl);
4389 CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
4390 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
4391 EmitLambdaExpr(E, Slot);
4392 return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl);
4395 LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
4396 RValue RV = EmitObjCMessageExpr(E);
4399 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
4400 AlignmentSource::Decl);
4402 assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
4403 "Can't have a scalar return unless the return type is a "
4406 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
4409 LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
4411 CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
4412 return MakeAddrLValue(V, E->getType(), AlignmentSource::Decl);
4415 llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
4416 const ObjCIvarDecl *Ivar) {
4417 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
4420 LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
4421 llvm::Value *BaseValue,
4422 const ObjCIvarDecl *Ivar,
4423 unsigned CVRQualifiers) {
4424 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
4425 Ivar, CVRQualifiers);
4428 LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
4429 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
4430 llvm::Value *BaseValue = nullptr;
4431 const Expr *BaseExpr = E->getBase();
4432 Qualifiers BaseQuals;
4435 BaseValue = EmitScalarExpr(BaseExpr);
4436 ObjectTy = BaseExpr->getType()->getPointeeType();
4437 BaseQuals = ObjectTy.getQualifiers();
4439 LValue BaseLV = EmitLValue(BaseExpr);
4440 BaseValue = BaseLV.getPointer();
4441 ObjectTy = BaseExpr->getType();
4442 BaseQuals = ObjectTy.getQualifiers();
4446 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
4447 BaseQuals.getCVRQualifiers());
4448 setObjCGCLValueClass(getContext(), E, LV);
4452 LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
4453 // Can only get l-value for message expression returning aggregate type
4454 RValue RV = EmitAnyExprToTemp(E);
4455 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
4456 AlignmentSource::Decl);
4459 RValue CodeGenFunction::EmitCall(QualType CalleeType, const CGCallee &OrigCallee,
4460 const CallExpr *E, ReturnValueSlot ReturnValue,
4461 llvm::Value *Chain) {
4462 // Get the actual function type. The callee type will always be a pointer to
4463 // function type or a block pointer type.
4464 assert(CalleeType->isFunctionPointerType() &&
4465 "Call must have function pointer type!");
4467 const Decl *TargetDecl = OrigCallee.getAbstractInfo().getCalleeDecl();
4469 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
4470 // We can only guarantee that a function is called from the correct
4471 // context/function based on the appropriate target attributes,
4472 // so only check in the case where we have both always_inline and target
4473 // since otherwise we could be making a conditional call after a check for
4474 // the proper cpu features (and it won't cause code generation issues due to
4475 // function based code generation).
4476 if (TargetDecl->hasAttr<AlwaysInlineAttr>() &&
4477 TargetDecl->hasAttr<TargetAttr>())
4478 checkTargetFeatures(E, FD);
4480 CalleeType = getContext().getCanonicalType(CalleeType);
4482 const auto *FnType =
4483 cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
4485 CGCallee Callee = OrigCallee;
4487 if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
4488 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4489 if (llvm::Constant *PrefixSig =
4490 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
4491 SanitizerScope SanScope(this);
4492 llvm::Constant *FTRTTIConst =
4493 CGM.GetAddrOfRTTIDescriptor(QualType(FnType, 0), /*ForEH=*/true);
4494 llvm::Type *PrefixStructTyElems[] = {PrefixSig->getType(), Int32Ty};
4495 llvm::StructType *PrefixStructTy = llvm::StructType::get(
4496 CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true);
4498 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4500 llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
4501 CalleePtr, llvm::PointerType::getUnqual(PrefixStructTy));
4502 llvm::Value *CalleeSigPtr =
4503 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0);
4504 llvm::Value *CalleeSig =
4505 Builder.CreateAlignedLoad(CalleeSigPtr, getIntAlign());
4506 llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
4508 llvm::BasicBlock *Cont = createBasicBlock("cont");
4509 llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
4510 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
4512 EmitBlock(TypeCheck);
4513 llvm::Value *CalleeRTTIPtr =
4514 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1);
4515 llvm::Value *CalleeRTTIEncoded =
4516 Builder.CreateAlignedLoad(CalleeRTTIPtr, getPointerAlign());
4517 llvm::Value *CalleeRTTI =
4518 DecodeAddrUsedInPrologue(CalleePtr, CalleeRTTIEncoded);
4519 llvm::Value *CalleeRTTIMatch =
4520 Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
4521 llvm::Constant *StaticData[] = {
4522 EmitCheckSourceLocation(E->getLocStart()),
4523 EmitCheckTypeDescriptor(CalleeType)
4525 EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
4526 SanitizerHandler::FunctionTypeMismatch, StaticData, CalleePtr);
4528 Builder.CreateBr(Cont);
4533 // If we are checking indirect calls and this call is indirect, check that the
4534 // function pointer is a member of the bit set for the function type.
4535 if (SanOpts.has(SanitizerKind::CFIICall) &&
4536 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4537 SanitizerScope SanScope(this);
4538 EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
4541 if (CGM.getCodeGenOpts().SanitizeCfiICallGeneralizePointers)
4542 MD = CGM.CreateMetadataIdentifierGeneralized(QualType(FnType, 0));
4544 MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0));
4546 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
4548 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4549 llvm::Value *CastedCallee = Builder.CreateBitCast(CalleePtr, Int8PtrTy);
4550 llvm::Value *TypeTest = Builder.CreateCall(
4551 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedCallee, TypeId});
4553 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
4554 llvm::Constant *StaticData[] = {
4555 llvm::ConstantInt::get(Int8Ty, CFITCK_ICall),
4556 EmitCheckSourceLocation(E->getLocStart()),
4557 EmitCheckTypeDescriptor(QualType(FnType, 0)),
4559 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
4560 EmitCfiSlowPathCheck(SanitizerKind::CFIICall, TypeTest, CrossDsoTypeId,
4561 CastedCallee, StaticData);
4563 EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIICall),
4564 SanitizerHandler::CFICheckFail, StaticData,
4565 {CastedCallee, llvm::UndefValue::get(IntPtrTy)});
4571 Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
4572 CGM.getContext().VoidPtrTy);
4574 // C++17 requires that we evaluate arguments to a call using assignment syntax
4575 // right-to-left, and that we evaluate arguments to certain other operators
4576 // left-to-right. Note that we allow this to override the order dictated by
4577 // the calling convention on the MS ABI, which means that parameter
4578 // destruction order is not necessarily reverse construction order.
4579 // FIXME: Revisit this based on C++ committee response to unimplementability.
4580 EvaluationOrder Order = EvaluationOrder::Default;
4581 if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
4582 if (OCE->isAssignmentOp())
4583 Order = EvaluationOrder::ForceRightToLeft;
4585 switch (OCE->getOperator()) {
4587 case OO_GreaterGreater:
4592 Order = EvaluationOrder::ForceLeftToRight;
4600 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(),
4601 E->getDirectCallee(), /*ParamsToSkip*/ 0, Order);
4603 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
4604 Args, FnType, /*isChainCall=*/Chain);
4607 // If the expression that denotes the called function has a type
4608 // that does not include a prototype, [the default argument
4609 // promotions are performed]. If the number of arguments does not
4610 // equal the number of parameters, the behavior is undefined. If
4611 // the function is defined with a type that includes a prototype,
4612 // and either the prototype ends with an ellipsis (, ...) or the
4613 // types of the arguments after promotion are not compatible with
4614 // the types of the parameters, the behavior is undefined. If the
4615 // function is defined with a type that does not include a
4616 // prototype, and the types of the arguments after promotion are
4617 // not compatible with those of the parameters after promotion,
4618 // the behavior is undefined [except in some trivial cases].
4619 // That is, in the general case, we should assume that a call
4620 // through an unprototyped function type works like a *non-variadic*
4621 // call. The way we make this work is to cast to the exact type
4622 // of the promoted arguments.
4624 // Chain calls use this same code path to add the invisible chain parameter
4625 // to the function type.
4626 if (isa<FunctionNoProtoType>(FnType) || Chain) {
4627 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
4628 CalleeTy = CalleeTy->getPointerTo();
4630 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4631 CalleePtr = Builder.CreateBitCast(CalleePtr, CalleeTy, "callee.knr.cast");
4632 Callee.setFunctionPointer(CalleePtr);
4635 return EmitCall(FnInfo, Callee, ReturnValue, Args, nullptr, E->getExprLoc());
4638 LValue CodeGenFunction::
4639 EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
4640 Address BaseAddr = Address::invalid();
4641 if (E->getOpcode() == BO_PtrMemI) {
4642 BaseAddr = EmitPointerWithAlignment(E->getLHS());
4644 BaseAddr = EmitLValue(E->getLHS()).getAddress();
4647 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
4649 const MemberPointerType *MPT
4650 = E->getRHS()->getType()->getAs<MemberPointerType>();
4652 LValueBaseInfo BaseInfo;
4653 TBAAAccessInfo TBAAInfo;
4654 Address MemberAddr =
4655 EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT, &BaseInfo,
4658 return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), BaseInfo, TBAAInfo);
4661 /// Given the address of a temporary variable, produce an r-value of
4663 RValue CodeGenFunction::convertTempToRValue(Address addr,
4665 SourceLocation loc) {
4666 LValue lvalue = MakeAddrLValue(addr, type, AlignmentSource::Decl);
4667 switch (getEvaluationKind(type)) {
4669 return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
4671 return lvalue.asAggregateRValue();
4673 return RValue::get(EmitLoadOfScalar(lvalue, loc));
4675 llvm_unreachable("bad evaluation kind");
4678 void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
4679 assert(Val->getType()->isFPOrFPVectorTy());
4680 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
4683 llvm::MDBuilder MDHelper(getLLVMContext());
4684 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
4686 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
4690 struct LValueOrRValue {
4696 static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
4697 const PseudoObjectExpr *E,
4699 AggValueSlot slot) {
4700 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
4702 // Find the result expression, if any.
4703 const Expr *resultExpr = E->getResultExpr();
4704 LValueOrRValue result;
4706 for (PseudoObjectExpr::const_semantics_iterator
4707 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
4708 const Expr *semantic = *i;
4710 // If this semantic expression is an opaque value, bind it
4711 // to the result of its source expression.
4712 if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
4714 // If this is the result expression, we may need to evaluate
4715 // directly into the slot.
4716 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
4718 if (ov == resultExpr && ov->isRValue() && !forLValue &&
4719 CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
4720 CGF.EmitAggExpr(ov->getSourceExpr(), slot);
4721 LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
4722 AlignmentSource::Decl);
4723 opaqueData = OVMA::bind(CGF, ov, LV);
4724 result.RV = slot.asRValue();
4726 // Otherwise, emit as normal.
4728 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
4730 // If this is the result, also evaluate the result now.
4731 if (ov == resultExpr) {
4733 result.LV = CGF.EmitLValue(ov);
4735 result.RV = CGF.EmitAnyExpr(ov, slot);
4739 opaques.push_back(opaqueData);
4741 // Otherwise, if the expression is the result, evaluate it
4742 // and remember the result.
4743 } else if (semantic == resultExpr) {
4745 result.LV = CGF.EmitLValue(semantic);
4747 result.RV = CGF.EmitAnyExpr(semantic, slot);
4749 // Otherwise, evaluate the expression in an ignored context.
4751 CGF.EmitIgnoredExpr(semantic);
4755 // Unbind all the opaques now.
4756 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
4757 opaques[i].unbind(CGF);
4762 RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
4763 AggValueSlot slot) {
4764 return emitPseudoObjectExpr(*this, E, false, slot).RV;
4767 LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
4768 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;