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 "TargetInfo.h"
24 #include "clang/AST/ASTContext.h"
25 #include "clang/AST/Attr.h"
26 #include "clang/AST/DeclObjC.h"
27 #include "clang/AST/NSAPI.h"
28 #include "clang/Frontend/CodeGenOptions.h"
29 #include "llvm/ADT/Hashing.h"
30 #include "llvm/ADT/StringExtras.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/Intrinsics.h"
33 #include "llvm/IR/LLVMContext.h"
34 #include "llvm/IR/MDBuilder.h"
35 #include "llvm/Support/ConvertUTF.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/Path.h"
38 #include "llvm/Transforms/Utils/SanitizerStats.h"
42 using namespace clang;
43 using namespace CodeGen;
45 //===--------------------------------------------------------------------===//
46 // Miscellaneous Helper Methods
47 //===--------------------------------------------------------------------===//
49 llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) {
50 unsigned addressSpace =
51 cast<llvm::PointerType>(value->getType())->getAddressSpace();
53 llvm::PointerType *destType = Int8PtrTy;
55 destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace);
57 if (value->getType() == destType) return value;
58 return Builder.CreateBitCast(value, destType);
61 /// CreateTempAlloca - This creates a alloca and inserts it into the entry
63 Address CodeGenFunction::CreateTempAlloca(llvm::Type *Ty, CharUnits Align,
65 auto Alloca = CreateTempAlloca(Ty, Name);
66 Alloca->setAlignment(Align.getQuantity());
67 return Address(Alloca, Align);
70 /// CreateTempAlloca - This creates a alloca and inserts it into the entry
72 llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
74 return new llvm::AllocaInst(Ty, nullptr, Name, AllocaInsertPt);
77 /// CreateDefaultAlignTempAlloca - This creates an alloca with the
78 /// default alignment of the corresponding LLVM type, which is *not*
79 /// guaranteed to be related in any way to the expected alignment of
80 /// an AST type that might have been lowered to Ty.
81 Address CodeGenFunction::CreateDefaultAlignTempAlloca(llvm::Type *Ty,
84 CharUnits::fromQuantity(CGM.getDataLayout().getABITypeAlignment(Ty));
85 return CreateTempAlloca(Ty, Align, Name);
88 void CodeGenFunction::InitTempAlloca(Address Var, llvm::Value *Init) {
89 assert(isa<llvm::AllocaInst>(Var.getPointer()));
90 auto *Store = new llvm::StoreInst(Init, Var.getPointer());
91 Store->setAlignment(Var.getAlignment().getQuantity());
92 llvm::BasicBlock *Block = AllocaInsertPt->getParent();
93 Block->getInstList().insertAfter(AllocaInsertPt->getIterator(), Store);
96 Address CodeGenFunction::CreateIRTemp(QualType Ty, const Twine &Name) {
97 CharUnits Align = getContext().getTypeAlignInChars(Ty);
98 return CreateTempAlloca(ConvertType(Ty), Align, Name);
101 Address CodeGenFunction::CreateMemTemp(QualType Ty, const Twine &Name) {
102 // FIXME: Should we prefer the preferred type alignment here?
103 return CreateMemTemp(Ty, getContext().getTypeAlignInChars(Ty), Name);
106 Address CodeGenFunction::CreateMemTemp(QualType Ty, CharUnits Align,
108 return CreateTempAlloca(ConvertTypeForMem(Ty), Align, Name);
111 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
112 /// expression and compare the result against zero, returning an Int1Ty value.
113 llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
114 PGO.setCurrentStmt(E);
115 if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
116 llvm::Value *MemPtr = EmitScalarExpr(E);
117 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
120 QualType BoolTy = getContext().BoolTy;
121 SourceLocation Loc = E->getExprLoc();
122 if (!E->getType()->isAnyComplexType())
123 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy, Loc);
125 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(), BoolTy,
129 /// EmitIgnoredExpr - Emit code to compute the specified expression,
130 /// ignoring the result.
131 void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
133 return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
135 // Just emit it as an l-value and drop the result.
139 /// EmitAnyExpr - Emit code to compute the specified expression which
140 /// can have any type. The result is returned as an RValue struct.
141 /// If this is an aggregate expression, AggSlot indicates where the
142 /// result should be returned.
143 RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
144 AggValueSlot aggSlot,
146 switch (getEvaluationKind(E->getType())) {
148 return RValue::get(EmitScalarExpr(E, ignoreResult));
150 return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
152 if (!ignoreResult && aggSlot.isIgnored())
153 aggSlot = CreateAggTemp(E->getType(), "agg-temp");
154 EmitAggExpr(E, aggSlot);
155 return aggSlot.asRValue();
157 llvm_unreachable("bad evaluation kind");
160 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
161 /// always be accessible even if no aggregate location is provided.
162 RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
163 AggValueSlot AggSlot = AggValueSlot::ignored();
165 if (hasAggregateEvaluationKind(E->getType()))
166 AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
167 return EmitAnyExpr(E, AggSlot);
170 /// EmitAnyExprToMem - Evaluate an expression into a given memory
172 void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
176 // FIXME: This function should take an LValue as an argument.
177 switch (getEvaluationKind(E->getType())) {
179 EmitComplexExprIntoLValue(E, MakeAddrLValue(Location, E->getType()),
183 case TEK_Aggregate: {
184 EmitAggExpr(E, AggValueSlot::forAddr(Location, Quals,
185 AggValueSlot::IsDestructed_t(IsInit),
186 AggValueSlot::DoesNotNeedGCBarriers,
187 AggValueSlot::IsAliased_t(!IsInit)));
192 RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
193 LValue LV = MakeAddrLValue(Location, E->getType());
194 EmitStoreThroughLValue(RV, LV);
198 llvm_unreachable("bad evaluation kind");
202 pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M,
203 const Expr *E, Address ReferenceTemporary) {
204 // Objective-C++ ARC:
205 // If we are binding a reference to a temporary that has ownership, we
206 // need to perform retain/release operations on the temporary.
208 // FIXME: This should be looking at E, not M.
209 if (auto Lifetime = M->getType().getObjCLifetime()) {
211 case Qualifiers::OCL_None:
212 case Qualifiers::OCL_ExplicitNone:
213 // Carry on to normal cleanup handling.
216 case Qualifiers::OCL_Autoreleasing:
217 // Nothing to do; cleaned up by an autorelease pool.
220 case Qualifiers::OCL_Strong:
221 case Qualifiers::OCL_Weak:
222 switch (StorageDuration Duration = M->getStorageDuration()) {
224 // Note: we intentionally do not register a cleanup to release
225 // the object on program termination.
229 // FIXME: We should probably register a cleanup in this case.
233 case SD_FullExpression:
234 CodeGenFunction::Destroyer *Destroy;
235 CleanupKind CleanupKind;
236 if (Lifetime == Qualifiers::OCL_Strong) {
237 const ValueDecl *VD = M->getExtendingDecl();
239 VD && isa<VarDecl>(VD) && VD->hasAttr<ObjCPreciseLifetimeAttr>();
240 CleanupKind = CGF.getARCCleanupKind();
241 Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise
242 : &CodeGenFunction::destroyARCStrongImprecise;
244 // __weak objects always get EH cleanups; otherwise, exceptions
245 // could cause really nasty crashes instead of mere leaks.
246 CleanupKind = NormalAndEHCleanup;
247 Destroy = &CodeGenFunction::destroyARCWeak;
249 if (Duration == SD_FullExpression)
250 CGF.pushDestroy(CleanupKind, ReferenceTemporary,
251 M->getType(), *Destroy,
252 CleanupKind & EHCleanup);
254 CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
256 *Destroy, CleanupKind & EHCleanup);
260 llvm_unreachable("temporary cannot have dynamic storage duration");
262 llvm_unreachable("unknown storage duration");
266 CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
267 if (const RecordType *RT =
268 E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
269 // Get the destructor for the reference temporary.
270 auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
271 if (!ClassDecl->hasTrivialDestructor())
272 ReferenceTemporaryDtor = ClassDecl->getDestructor();
275 if (!ReferenceTemporaryDtor)
278 // Call the destructor for the temporary.
279 switch (M->getStorageDuration()) {
282 llvm::Constant *CleanupFn;
283 llvm::Constant *CleanupArg;
284 if (E->getType()->isArrayType()) {
285 CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper(
286 ReferenceTemporary, E->getType(),
287 CodeGenFunction::destroyCXXObject, CGF.getLangOpts().Exceptions,
288 dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
289 CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
291 CleanupFn = CGF.CGM.getAddrOfCXXStructor(ReferenceTemporaryDtor,
292 StructorType::Complete);
293 CleanupArg = cast<llvm::Constant>(ReferenceTemporary.getPointer());
295 CGF.CGM.getCXXABI().registerGlobalDtor(
296 CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
300 case SD_FullExpression:
301 CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(),
302 CodeGenFunction::destroyCXXObject,
303 CGF.getLangOpts().Exceptions);
307 CGF.pushLifetimeExtendedDestroy(NormalAndEHCleanup,
308 ReferenceTemporary, E->getType(),
309 CodeGenFunction::destroyCXXObject,
310 CGF.getLangOpts().Exceptions);
314 llvm_unreachable("temporary cannot have dynamic storage duration");
319 createReferenceTemporary(CodeGenFunction &CGF,
320 const MaterializeTemporaryExpr *M, const Expr *Inner) {
321 switch (M->getStorageDuration()) {
322 case SD_FullExpression:
324 // If we have a constant temporary array or record try to promote it into a
325 // constant global under the same rules a normal constant would've been
326 // promoted. This is easier on the optimizer and generally emits fewer
328 QualType Ty = Inner->getType();
329 if (CGF.CGM.getCodeGenOpts().MergeAllConstants &&
330 (Ty->isArrayType() || Ty->isRecordType()) &&
331 CGF.CGM.isTypeConstant(Ty, true))
332 if (llvm::Constant *Init = CGF.CGM.EmitConstantExpr(Inner, Ty, &CGF)) {
333 auto *GV = new llvm::GlobalVariable(
334 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
335 llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp");
336 CharUnits alignment = CGF.getContext().getTypeAlignInChars(Ty);
337 GV->setAlignment(alignment.getQuantity());
338 // FIXME: Should we put the new global into a COMDAT?
339 return Address(GV, alignment);
341 return CGF.CreateMemTemp(Ty, "ref.tmp");
345 return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
348 llvm_unreachable("temporary can't have dynamic storage duration");
350 llvm_unreachable("unknown storage duration");
353 LValue CodeGenFunction::
354 EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *M) {
355 const Expr *E = M->GetTemporaryExpr();
357 // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
358 // as that will cause the lifetime adjustment to be lost for ARC
359 auto ownership = M->getType().getObjCLifetime();
360 if (ownership != Qualifiers::OCL_None &&
361 ownership != Qualifiers::OCL_ExplicitNone) {
362 Address Object = createReferenceTemporary(*this, M, E);
363 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
364 Object = Address(llvm::ConstantExpr::getBitCast(Var,
365 ConvertTypeForMem(E->getType())
366 ->getPointerTo(Object.getAddressSpace())),
367 Object.getAlignment());
369 // createReferenceTemporary will promote the temporary to a global with a
370 // constant initializer if it can. It can only do this to a value of
371 // ARC-manageable type if the value is global and therefore "immune" to
372 // ref-counting operations. Therefore we have no need to emit either a
373 // dynamic initialization or a cleanup and we can just return the address
375 if (Var->hasInitializer())
376 return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
378 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
380 LValue RefTempDst = MakeAddrLValue(Object, M->getType(),
381 AlignmentSource::Decl);
383 switch (getEvaluationKind(E->getType())) {
384 default: llvm_unreachable("expected scalar or aggregate expression");
386 EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
388 case TEK_Aggregate: {
389 EmitAggExpr(E, AggValueSlot::forAddr(Object,
390 E->getType().getQualifiers(),
391 AggValueSlot::IsDestructed,
392 AggValueSlot::DoesNotNeedGCBarriers,
393 AggValueSlot::IsNotAliased));
398 pushTemporaryCleanup(*this, M, E, Object);
402 SmallVector<const Expr *, 2> CommaLHSs;
403 SmallVector<SubobjectAdjustment, 2> Adjustments;
404 E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
406 for (const auto &Ignored : CommaLHSs)
407 EmitIgnoredExpr(Ignored);
409 if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
410 if (opaque->getType()->isRecordType()) {
411 assert(Adjustments.empty());
412 return EmitOpaqueValueLValue(opaque);
416 // Create and initialize the reference temporary.
417 Address Object = createReferenceTemporary(*this, M, E);
418 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
419 Object = Address(llvm::ConstantExpr::getBitCast(
420 Var, ConvertTypeForMem(E->getType())->getPointerTo()),
421 Object.getAlignment());
422 // If the temporary is a global and has a constant initializer or is a
423 // constant temporary that we promoted to a global, we may have already
425 if (!Var->hasInitializer()) {
426 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
427 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
430 switch (M->getStorageDuration()) {
432 case SD_FullExpression:
433 if (auto *Size = EmitLifetimeStart(
434 CGM.getDataLayout().getTypeAllocSize(Object.getElementType()),
435 Object.getPointer())) {
436 if (M->getStorageDuration() == SD_Automatic)
437 pushCleanupAfterFullExpr<CallLifetimeEnd>(NormalEHLifetimeMarker,
440 pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, Object,
447 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
449 pushTemporaryCleanup(*this, M, E, Object);
451 // Perform derived-to-base casts and/or field accesses, to get from the
452 // temporary object we created (and, potentially, for which we extended
453 // the lifetime) to the subobject we're binding the reference to.
454 for (unsigned I = Adjustments.size(); I != 0; --I) {
455 SubobjectAdjustment &Adjustment = Adjustments[I-1];
456 switch (Adjustment.Kind) {
457 case SubobjectAdjustment::DerivedToBaseAdjustment:
459 GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
460 Adjustment.DerivedToBase.BasePath->path_begin(),
461 Adjustment.DerivedToBase.BasePath->path_end(),
462 /*NullCheckValue=*/ false, E->getExprLoc());
465 case SubobjectAdjustment::FieldAdjustment: {
466 LValue LV = MakeAddrLValue(Object, E->getType(),
467 AlignmentSource::Decl);
468 LV = EmitLValueForField(LV, Adjustment.Field);
469 assert(LV.isSimple() &&
470 "materialized temporary field is not a simple lvalue");
471 Object = LV.getAddress();
475 case SubobjectAdjustment::MemberPointerAdjustment: {
476 llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
477 Object = EmitCXXMemberDataPointerAddress(E, Object, Ptr,
484 return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
488 CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) {
489 // Emit the expression as an lvalue.
490 LValue LV = EmitLValue(E);
491 assert(LV.isSimple());
492 llvm::Value *Value = LV.getPointer();
494 if (sanitizePerformTypeCheck() && !E->getType()->isFunctionType()) {
495 // C++11 [dcl.ref]p5 (as amended by core issue 453):
496 // If a glvalue to which a reference is directly bound designates neither
497 // an existing object or function of an appropriate type nor a region of
498 // storage of suitable size and alignment to contain an object of the
499 // reference's type, the behavior is undefined.
500 QualType Ty = E->getType();
501 EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
504 return RValue::get(Value);
508 /// getAccessedFieldNo - Given an encoded value and a result number, return the
509 /// input field number being accessed.
510 unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
511 const llvm::Constant *Elts) {
512 return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
516 /// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
517 static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
519 llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
520 llvm::Value *K47 = Builder.getInt64(47);
521 llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
522 llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
523 llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
524 llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
525 return Builder.CreateMul(B1, KMul);
528 bool CodeGenFunction::sanitizePerformTypeCheck() const {
529 return SanOpts.has(SanitizerKind::Null) |
530 SanOpts.has(SanitizerKind::Alignment) |
531 SanOpts.has(SanitizerKind::ObjectSize) |
532 SanOpts.has(SanitizerKind::Vptr);
535 void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
536 llvm::Value *Ptr, QualType Ty,
538 SanitizerSet SkippedChecks) {
539 if (!sanitizePerformTypeCheck())
542 // Don't check pointers outside the default address space. The null check
543 // isn't correct, the object-size check isn't supported by LLVM, and we can't
544 // communicate the addresses to the runtime handler for the vptr check.
545 if (Ptr->getType()->getPointerAddressSpace())
548 SanitizerScope SanScope(this);
550 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 3> Checks;
551 llvm::BasicBlock *Done = nullptr;
553 bool AllowNullPointers = TCK == TCK_DowncastPointer || TCK == TCK_Upcast ||
554 TCK == TCK_UpcastToVirtualBase;
555 if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
556 !SkippedChecks.has(SanitizerKind::Null)) {
557 // The glvalue must not be an empty glvalue.
558 llvm::Value *IsNonNull = Builder.CreateIsNotNull(Ptr);
560 if (AllowNullPointers) {
561 // When performing pointer casts, it's OK if the value is null.
562 // Skip the remaining checks in that case.
563 Done = createBasicBlock("null");
564 llvm::BasicBlock *Rest = createBasicBlock("not.null");
565 Builder.CreateCondBr(IsNonNull, Rest, Done);
568 Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null));
572 if (SanOpts.has(SanitizerKind::ObjectSize) &&
573 !SkippedChecks.has(SanitizerKind::ObjectSize) &&
574 !Ty->isIncompleteType()) {
575 uint64_t Size = getContext().getTypeSizeInChars(Ty).getQuantity();
577 // The glvalue must refer to a large enough storage region.
578 // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
580 // FIXME: Get object address space
581 llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
582 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
583 llvm::Value *Min = Builder.getFalse();
584 llvm::Value *NullIsUnknown = Builder.getFalse();
585 llvm::Value *CastAddr = Builder.CreateBitCast(Ptr, Int8PtrTy);
586 llvm::Value *LargeEnough = Builder.CreateICmpUGE(
587 Builder.CreateCall(F, {CastAddr, Min, NullIsUnknown}),
588 llvm::ConstantInt::get(IntPtrTy, Size));
589 Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
592 uint64_t AlignVal = 0;
594 if (SanOpts.has(SanitizerKind::Alignment) &&
595 !SkippedChecks.has(SanitizerKind::Alignment)) {
596 AlignVal = Alignment.getQuantity();
597 if (!Ty->isIncompleteType() && !AlignVal)
598 AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity();
600 // The glvalue must be suitably aligned.
603 Builder.CreateAnd(Builder.CreatePtrToInt(Ptr, IntPtrTy),
604 llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
605 llvm::Value *Aligned =
606 Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
607 Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
611 if (Checks.size() > 0) {
612 // Make sure we're not losing information. Alignment needs to be a power of
614 assert(!AlignVal || (uint64_t)1 << llvm::Log2_64(AlignVal) == AlignVal);
615 llvm::Constant *StaticData[] = {
616 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(Ty),
617 llvm::ConstantInt::get(Int8Ty, AlignVal ? llvm::Log2_64(AlignVal) : 1),
618 llvm::ConstantInt::get(Int8Ty, TCK)};
619 EmitCheck(Checks, SanitizerHandler::TypeMismatch, StaticData, Ptr);
622 // If possible, check that the vptr indicates that there is a subobject of
623 // type Ty at offset zero within this object.
625 // C++11 [basic.life]p5,6:
626 // [For storage which does not refer to an object within its lifetime]
627 // The program has undefined behavior if:
628 // -- the [pointer or glvalue] is used to access a non-static data member
629 // or call a non-static member function
630 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
631 if (SanOpts.has(SanitizerKind::Vptr) &&
632 !SkippedChecks.has(SanitizerKind::Vptr) &&
633 (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
634 TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
635 TCK == TCK_UpcastToVirtualBase) &&
636 RD && RD->hasDefinition() && RD->isDynamicClass()) {
637 // Compute a hash of the mangled name of the type.
639 // FIXME: This is not guaranteed to be deterministic! Move to a
640 // fingerprinting mechanism once LLVM provides one. For the time
641 // being the implementation happens to be deterministic.
642 SmallString<64> MangledName;
643 llvm::raw_svector_ostream Out(MangledName);
644 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
647 // Blacklist based on the mangled type.
648 if (!CGM.getContext().getSanitizerBlacklist().isBlacklistedType(
650 llvm::hash_code TypeHash = hash_value(Out.str());
652 // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
653 llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
654 llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
655 Address VPtrAddr(Builder.CreateBitCast(Ptr, VPtrTy), getPointerAlign());
656 llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
657 llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
659 llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
660 Hash = Builder.CreateTrunc(Hash, IntPtrTy);
662 // Look the hash up in our cache.
663 const int CacheSize = 128;
664 llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
665 llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
666 "__ubsan_vptr_type_cache");
667 llvm::Value *Slot = Builder.CreateAnd(Hash,
668 llvm::ConstantInt::get(IntPtrTy,
670 llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
671 llvm::Value *CacheVal =
672 Builder.CreateAlignedLoad(Builder.CreateInBoundsGEP(Cache, Indices),
675 // If the hash isn't in the cache, call a runtime handler to perform the
676 // hard work of checking whether the vptr is for an object of the right
677 // type. This will either fill in the cache and return, or produce a
679 llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
680 llvm::Constant *StaticData[] = {
681 EmitCheckSourceLocation(Loc),
682 EmitCheckTypeDescriptor(Ty),
683 CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
684 llvm::ConstantInt::get(Int8Ty, TCK)
686 llvm::Value *DynamicData[] = { Ptr, Hash };
687 EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
688 SanitizerHandler::DynamicTypeCacheMiss, StaticData,
694 Builder.CreateBr(Done);
699 /// Determine whether this expression refers to a flexible array member in a
700 /// struct. We disable array bounds checks for such members.
701 static bool isFlexibleArrayMemberExpr(const Expr *E) {
702 // For compatibility with existing code, we treat arrays of length 0 or
703 // 1 as flexible array members.
704 const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe();
705 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
706 if (CAT->getSize().ugt(1))
708 } else if (!isa<IncompleteArrayType>(AT))
711 E = E->IgnoreParens();
713 // A flexible array member must be the last member in the class.
714 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
715 // FIXME: If the base type of the member expr is not FD->getParent(),
716 // this should not be treated as a flexible array member access.
717 if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
718 RecordDecl::field_iterator FI(
719 DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
720 return ++FI == FD->getParent()->field_end();
722 } else if (const auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) {
723 return IRE->getDecl()->getNextIvar() == nullptr;
729 /// If Base is known to point to the start of an array, return the length of
730 /// that array. Return 0 if the length cannot be determined.
731 static llvm::Value *getArrayIndexingBound(
732 CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType) {
733 // For the vector indexing extension, the bound is the number of elements.
734 if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
735 IndexedType = Base->getType();
736 return CGF.Builder.getInt32(VT->getNumElements());
739 Base = Base->IgnoreParens();
741 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
742 if (CE->getCastKind() == CK_ArrayToPointerDecay &&
743 !isFlexibleArrayMemberExpr(CE->getSubExpr())) {
744 IndexedType = CE->getSubExpr()->getType();
745 const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
746 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
747 return CGF.Builder.getInt(CAT->getSize());
748 else if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
749 return CGF.getVLASize(VAT).first;
756 void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
757 llvm::Value *Index, QualType IndexType,
759 assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
760 "should not be called unless adding bounds checks");
761 SanitizerScope SanScope(this);
763 QualType IndexedType;
764 llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType);
768 bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
769 llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
770 llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
772 llvm::Constant *StaticData[] = {
773 EmitCheckSourceLocation(E->getExprLoc()),
774 EmitCheckTypeDescriptor(IndexedType),
775 EmitCheckTypeDescriptor(IndexType)
777 llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
778 : Builder.CreateICmpULE(IndexVal, BoundVal);
779 EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds),
780 SanitizerHandler::OutOfBounds, StaticData, Index);
784 CodeGenFunction::ComplexPairTy CodeGenFunction::
785 EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
786 bool isInc, bool isPre) {
787 ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
789 llvm::Value *NextVal;
790 if (isa<llvm::IntegerType>(InVal.first->getType())) {
791 uint64_t AmountVal = isInc ? 1 : -1;
792 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
794 // Add the inc/dec to the real part.
795 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
797 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
798 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
801 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
803 // Add the inc/dec to the real part.
804 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
807 ComplexPairTy IncVal(NextVal, InVal.second);
809 // Store the updated result through the lvalue.
810 EmitStoreOfComplex(IncVal, LV, /*init*/ false);
812 // If this is a postinc, return the value read from memory, otherwise use the
814 return isPre ? IncVal : InVal;
817 void CodeGenModule::EmitExplicitCastExprType(const ExplicitCastExpr *E,
818 CodeGenFunction *CGF) {
819 // Bind VLAs in the cast type.
820 if (CGF && E->getType()->isVariablyModifiedType())
821 CGF->EmitVariablyModifiedType(E->getType());
823 if (CGDebugInfo *DI = getModuleDebugInfo())
824 DI->EmitExplicitCastType(E->getType());
827 //===----------------------------------------------------------------------===//
828 // LValue Expression Emission
829 //===----------------------------------------------------------------------===//
831 /// EmitPointerWithAlignment - Given an expression of pointer type, try to
832 /// derive a more accurate bound on the alignment of the pointer.
833 Address CodeGenFunction::EmitPointerWithAlignment(const Expr *E,
834 AlignmentSource *Source) {
835 // We allow this with ObjC object pointers because of fragile ABIs.
836 assert(E->getType()->isPointerType() ||
837 E->getType()->isObjCObjectPointerType());
838 E = E->IgnoreParens();
841 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
842 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
843 CGM.EmitExplicitCastExprType(ECE, this);
845 switch (CE->getCastKind()) {
846 // Non-converting casts (but not C's implicit conversion from void*).
849 if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) {
850 if (PtrTy->getPointeeType()->isVoidType())
853 AlignmentSource InnerSource;
854 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), &InnerSource);
855 if (Source) *Source = InnerSource;
857 // If this is an explicit bitcast, and the source l-value is
858 // opaque, honor the alignment of the casted-to type.
859 if (isa<ExplicitCastExpr>(CE) &&
860 InnerSource != AlignmentSource::Decl) {
861 Addr = Address(Addr.getPointer(),
862 getNaturalPointeeTypeAlignment(E->getType(), Source));
865 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast) &&
866 CE->getCastKind() == CK_BitCast) {
867 if (auto PT = E->getType()->getAs<PointerType>())
868 EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr.getPointer(),
870 CodeGenFunction::CFITCK_UnrelatedCast,
874 return Builder.CreateBitCast(Addr, ConvertType(E->getType()));
878 // Array-to-pointer decay.
879 case CK_ArrayToPointerDecay:
880 return EmitArrayToPointerDecay(CE->getSubExpr(), Source);
882 // Derived-to-base conversions.
883 case CK_UncheckedDerivedToBase:
884 case CK_DerivedToBase: {
885 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), Source);
886 auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
887 return GetAddressOfBaseClass(Addr, Derived,
888 CE->path_begin(), CE->path_end(),
889 ShouldNullCheckClassCastValue(CE),
893 // TODO: Is there any reason to treat base-to-derived conversions
901 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
902 if (UO->getOpcode() == UO_AddrOf) {
903 LValue LV = EmitLValue(UO->getSubExpr());
904 if (Source) *Source = LV.getAlignmentSource();
905 return LV.getAddress();
909 // TODO: conditional operators, comma.
911 // Otherwise, use the alignment of the type.
912 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(), Source);
913 return Address(EmitScalarExpr(E), Align);
916 RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
917 if (Ty->isVoidType())
918 return RValue::get(nullptr);
920 switch (getEvaluationKind(Ty)) {
923 ConvertType(Ty->castAs<ComplexType>()->getElementType());
924 llvm::Value *U = llvm::UndefValue::get(EltTy);
925 return RValue::getComplex(std::make_pair(U, U));
928 // If this is a use of an undefined aggregate type, the aggregate must have an
929 // identifiable address. Just because the contents of the value are undefined
930 // doesn't mean that the address can't be taken and compared.
931 case TEK_Aggregate: {
932 Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
933 return RValue::getAggregate(DestPtr);
937 return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
939 llvm_unreachable("bad evaluation kind");
942 RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
944 ErrorUnsupported(E, Name);
945 return GetUndefRValue(E->getType());
948 LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
950 ErrorUnsupported(E, Name);
951 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
952 return MakeAddrLValue(Address(llvm::UndefValue::get(Ty), CharUnits::One()),
956 bool CodeGenFunction::IsDeclRefOrWrappedCXXThis(const Expr *Obj) {
957 if (isa<DeclRefExpr>(Obj))
960 const Expr *Base = Obj;
961 while (!isa<CXXThisExpr>(Base)) {
962 // The result of a dynamic_cast can be null.
963 if (isa<CXXDynamicCastExpr>(Base))
966 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
967 Base = CE->getSubExpr();
968 } else if (const auto *PE = dyn_cast<ParenExpr>(Base)) {
969 Base = PE->getSubExpr();
970 } else if (const auto *UO = dyn_cast<UnaryOperator>(Base)) {
971 if (UO->getOpcode() == UO_Extension)
972 Base = UO->getSubExpr();
982 LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
984 if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
985 LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
988 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple()) {
989 SanitizerSet SkippedChecks;
990 if (const auto *ME = dyn_cast<MemberExpr>(E))
991 if (IsDeclRefOrWrappedCXXThis(ME->getBase()))
992 SkippedChecks.set(SanitizerKind::Null, true);
993 EmitTypeCheck(TCK, E->getExprLoc(), LV.getPointer(),
994 E->getType(), LV.getAlignment(), SkippedChecks);
999 /// EmitLValue - Emit code to compute a designator that specifies the location
1000 /// of the expression.
1002 /// This can return one of two things: a simple address or a bitfield reference.
1003 /// In either case, the LLVM Value* in the LValue structure is guaranteed to be
1004 /// an LLVM pointer type.
1006 /// If this returns a bitfield reference, nothing about the pointee type of the
1007 /// LLVM value is known: For example, it may not be a pointer to an integer.
1009 /// If this returns a normal address, and if the lvalue's C type is fixed size,
1010 /// this method guarantees that the returned pointer type will point to an LLVM
1011 /// type of the same size of the lvalue's type. If the lvalue has a variable
1012 /// length type, this is not possible.
1014 LValue CodeGenFunction::EmitLValue(const Expr *E) {
1015 ApplyDebugLocation DL(*this, E);
1016 switch (E->getStmtClass()) {
1017 default: return EmitUnsupportedLValue(E, "l-value expression");
1019 case Expr::ObjCPropertyRefExprClass:
1020 llvm_unreachable("cannot emit a property reference directly");
1022 case Expr::ObjCSelectorExprClass:
1023 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
1024 case Expr::ObjCIsaExprClass:
1025 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
1026 case Expr::BinaryOperatorClass:
1027 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
1028 case Expr::CompoundAssignOperatorClass: {
1029 QualType Ty = E->getType();
1030 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1031 Ty = AT->getValueType();
1032 if (!Ty->isAnyComplexType())
1033 return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
1034 return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
1036 case Expr::CallExprClass:
1037 case Expr::CXXMemberCallExprClass:
1038 case Expr::CXXOperatorCallExprClass:
1039 case Expr::UserDefinedLiteralClass:
1040 return EmitCallExprLValue(cast<CallExpr>(E));
1041 case Expr::VAArgExprClass:
1042 return EmitVAArgExprLValue(cast<VAArgExpr>(E));
1043 case Expr::DeclRefExprClass:
1044 return EmitDeclRefLValue(cast<DeclRefExpr>(E));
1045 case Expr::ParenExprClass:
1046 return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
1047 case Expr::GenericSelectionExprClass:
1048 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
1049 case Expr::PredefinedExprClass:
1050 return EmitPredefinedLValue(cast<PredefinedExpr>(E));
1051 case Expr::StringLiteralClass:
1052 return EmitStringLiteralLValue(cast<StringLiteral>(E));
1053 case Expr::ObjCEncodeExprClass:
1054 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
1055 case Expr::PseudoObjectExprClass:
1056 return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
1057 case Expr::InitListExprClass:
1058 return EmitInitListLValue(cast<InitListExpr>(E));
1059 case Expr::CXXTemporaryObjectExprClass:
1060 case Expr::CXXConstructExprClass:
1061 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
1062 case Expr::CXXBindTemporaryExprClass:
1063 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
1064 case Expr::CXXUuidofExprClass:
1065 return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
1066 case Expr::LambdaExprClass:
1067 return EmitLambdaLValue(cast<LambdaExpr>(E));
1069 case Expr::ExprWithCleanupsClass: {
1070 const auto *cleanups = cast<ExprWithCleanups>(E);
1071 enterFullExpression(cleanups);
1072 RunCleanupsScope Scope(*this);
1073 LValue LV = EmitLValue(cleanups->getSubExpr());
1074 if (LV.isSimple()) {
1075 // Defend against branches out of gnu statement expressions surrounded by
1077 llvm::Value *V = LV.getPointer();
1078 Scope.ForceCleanup({&V});
1079 return LValue::MakeAddr(Address(V, LV.getAlignment()), LV.getType(),
1080 getContext(), LV.getAlignmentSource(),
1083 // FIXME: Is it possible to create an ExprWithCleanups that produces a
1084 // bitfield lvalue or some other non-simple lvalue?
1088 case Expr::CXXDefaultArgExprClass:
1089 return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
1090 case Expr::CXXDefaultInitExprClass: {
1091 CXXDefaultInitExprScope Scope(*this);
1092 return EmitLValue(cast<CXXDefaultInitExpr>(E)->getExpr());
1094 case Expr::CXXTypeidExprClass:
1095 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
1097 case Expr::ObjCMessageExprClass:
1098 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
1099 case Expr::ObjCIvarRefExprClass:
1100 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
1101 case Expr::StmtExprClass:
1102 return EmitStmtExprLValue(cast<StmtExpr>(E));
1103 case Expr::UnaryOperatorClass:
1104 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
1105 case Expr::ArraySubscriptExprClass:
1106 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
1107 case Expr::OMPArraySectionExprClass:
1108 return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E));
1109 case Expr::ExtVectorElementExprClass:
1110 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
1111 case Expr::MemberExprClass:
1112 return EmitMemberExpr(cast<MemberExpr>(E));
1113 case Expr::CompoundLiteralExprClass:
1114 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
1115 case Expr::ConditionalOperatorClass:
1116 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
1117 case Expr::BinaryConditionalOperatorClass:
1118 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
1119 case Expr::ChooseExprClass:
1120 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr());
1121 case Expr::OpaqueValueExprClass:
1122 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
1123 case Expr::SubstNonTypeTemplateParmExprClass:
1124 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
1125 case Expr::ImplicitCastExprClass:
1126 case Expr::CStyleCastExprClass:
1127 case Expr::CXXFunctionalCastExprClass:
1128 case Expr::CXXStaticCastExprClass:
1129 case Expr::CXXDynamicCastExprClass:
1130 case Expr::CXXReinterpretCastExprClass:
1131 case Expr::CXXConstCastExprClass:
1132 case Expr::ObjCBridgedCastExprClass:
1133 return EmitCastLValue(cast<CastExpr>(E));
1135 case Expr::MaterializeTemporaryExprClass:
1136 return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
1140 /// Given an object of the given canonical type, can we safely copy a
1141 /// value out of it based on its initializer?
1142 static bool isConstantEmittableObjectType(QualType type) {
1143 assert(type.isCanonical());
1144 assert(!type->isReferenceType());
1146 // Must be const-qualified but non-volatile.
1147 Qualifiers qs = type.getLocalQualifiers();
1148 if (!qs.hasConst() || qs.hasVolatile()) return false;
1150 // Otherwise, all object types satisfy this except C++ classes with
1151 // mutable subobjects or non-trivial copy/destroy behavior.
1152 if (const auto *RT = dyn_cast<RecordType>(type))
1153 if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
1154 if (RD->hasMutableFields() || !RD->isTrivial())
1160 /// Can we constant-emit a load of a reference to a variable of the
1161 /// given type? This is different from predicates like
1162 /// Decl::isUsableInConstantExpressions because we do want it to apply
1163 /// in situations that don't necessarily satisfy the language's rules
1164 /// for this (e.g. C++'s ODR-use rules). For example, we want to able
1165 /// to do this with const float variables even if those variables
1166 /// aren't marked 'constexpr'.
1167 enum ConstantEmissionKind {
1169 CEK_AsReferenceOnly,
1170 CEK_AsValueOrReference,
1173 static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
1174 type = type.getCanonicalType();
1175 if (const auto *ref = dyn_cast<ReferenceType>(type)) {
1176 if (isConstantEmittableObjectType(ref->getPointeeType()))
1177 return CEK_AsValueOrReference;
1178 return CEK_AsReferenceOnly;
1180 if (isConstantEmittableObjectType(type))
1181 return CEK_AsValueOnly;
1185 /// Try to emit a reference to the given value without producing it as
1186 /// an l-value. This is actually more than an optimization: we can't
1187 /// produce an l-value for variables that we never actually captured
1188 /// in a block or lambda, which means const int variables or constexpr
1189 /// literals or similar.
1190 CodeGenFunction::ConstantEmission
1191 CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
1192 ValueDecl *value = refExpr->getDecl();
1194 // The value needs to be an enum constant or a constant variable.
1195 ConstantEmissionKind CEK;
1196 if (isa<ParmVarDecl>(value)) {
1198 } else if (auto *var = dyn_cast<VarDecl>(value)) {
1199 CEK = checkVarTypeForConstantEmission(var->getType());
1200 } else if (isa<EnumConstantDecl>(value)) {
1201 CEK = CEK_AsValueOnly;
1205 if (CEK == CEK_None) return ConstantEmission();
1207 Expr::EvalResult result;
1208 bool resultIsReference;
1209 QualType resultType;
1211 // It's best to evaluate all the way as an r-value if that's permitted.
1212 if (CEK != CEK_AsReferenceOnly &&
1213 refExpr->EvaluateAsRValue(result, getContext())) {
1214 resultIsReference = false;
1215 resultType = refExpr->getType();
1217 // Otherwise, try to evaluate as an l-value.
1218 } else if (CEK != CEK_AsValueOnly &&
1219 refExpr->EvaluateAsLValue(result, getContext())) {
1220 resultIsReference = true;
1221 resultType = value->getType();
1225 return ConstantEmission();
1228 // In any case, if the initializer has side-effects, abandon ship.
1229 if (result.HasSideEffects)
1230 return ConstantEmission();
1232 // Emit as a constant.
1233 llvm::Constant *C = CGM.EmitConstantValue(result.Val, resultType, this);
1235 // Make sure we emit a debug reference to the global variable.
1236 // This should probably fire even for
1237 if (isa<VarDecl>(value)) {
1238 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
1239 EmitDeclRefExprDbgValue(refExpr, result.Val);
1241 assert(isa<EnumConstantDecl>(value));
1242 EmitDeclRefExprDbgValue(refExpr, result.Val);
1245 // If we emitted a reference constant, we need to dereference that.
1246 if (resultIsReference)
1247 return ConstantEmission::forReference(C);
1249 return ConstantEmission::forValue(C);
1252 llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
1253 SourceLocation Loc) {
1254 return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
1255 lvalue.getType(), Loc, lvalue.getAlignmentSource(),
1256 lvalue.getTBAAInfo(),
1257 lvalue.getTBAABaseType(), lvalue.getTBAAOffset(),
1258 lvalue.isNontemporal());
1261 static bool hasBooleanRepresentation(QualType Ty) {
1262 if (Ty->isBooleanType())
1265 if (const EnumType *ET = Ty->getAs<EnumType>())
1266 return ET->getDecl()->getIntegerType()->isBooleanType();
1268 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1269 return hasBooleanRepresentation(AT->getValueType());
1274 static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
1275 llvm::APInt &Min, llvm::APInt &End,
1276 bool StrictEnums, bool IsBool) {
1277 const EnumType *ET = Ty->getAs<EnumType>();
1278 bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
1279 ET && !ET->getDecl()->isFixed();
1280 if (!IsBool && !IsRegularCPlusPlusEnum)
1284 Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
1285 End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
1287 const EnumDecl *ED = ET->getDecl();
1288 llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
1289 unsigned Bitwidth = LTy->getScalarSizeInBits();
1290 unsigned NumNegativeBits = ED->getNumNegativeBits();
1291 unsigned NumPositiveBits = ED->getNumPositiveBits();
1293 if (NumNegativeBits) {
1294 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
1295 assert(NumBits <= Bitwidth);
1296 End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
1299 assert(NumPositiveBits <= Bitwidth);
1300 End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
1301 Min = llvm::APInt(Bitwidth, 0);
1307 llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
1308 llvm::APInt Min, End;
1309 if (!getRangeForType(*this, Ty, Min, End, CGM.getCodeGenOpts().StrictEnums,
1310 hasBooleanRepresentation(Ty)))
1313 llvm::MDBuilder MDHelper(getLLVMContext());
1314 return MDHelper.createRange(Min, End);
1317 bool CodeGenFunction::EmitScalarRangeCheck(llvm::Value *Value, QualType Ty,
1318 SourceLocation Loc) {
1319 bool HasBoolCheck = SanOpts.has(SanitizerKind::Bool);
1320 bool HasEnumCheck = SanOpts.has(SanitizerKind::Enum);
1321 if (!HasBoolCheck && !HasEnumCheck)
1324 bool IsBool = hasBooleanRepresentation(Ty) ||
1325 NSAPI(CGM.getContext()).isObjCBOOLType(Ty);
1326 bool NeedsBoolCheck = HasBoolCheck && IsBool;
1327 bool NeedsEnumCheck = HasEnumCheck && Ty->getAs<EnumType>();
1328 if (!NeedsBoolCheck && !NeedsEnumCheck)
1331 // Single-bit booleans don't need to be checked. Special-case this to avoid
1332 // a bit width mismatch when handling bitfield values. This is handled by
1333 // EmitFromMemory for the non-bitfield case.
1335 cast<llvm::IntegerType>(Value->getType())->getBitWidth() == 1)
1338 llvm::APInt Min, End;
1339 if (!getRangeForType(*this, Ty, Min, End, /*StrictEnums=*/true, IsBool))
1342 SanitizerScope SanScope(this);
1346 Check = Builder.CreateICmpULE(
1347 Value, llvm::ConstantInt::get(getLLVMContext(), End));
1349 llvm::Value *Upper = Builder.CreateICmpSLE(
1350 Value, llvm::ConstantInt::get(getLLVMContext(), End));
1351 llvm::Value *Lower = Builder.CreateICmpSGE(
1352 Value, llvm::ConstantInt::get(getLLVMContext(), Min));
1353 Check = Builder.CreateAnd(Upper, Lower);
1355 llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc),
1356 EmitCheckTypeDescriptor(Ty)};
1357 SanitizerMask Kind =
1358 NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
1359 EmitCheck(std::make_pair(Check, Kind), SanitizerHandler::LoadInvalidValue,
1360 StaticArgs, EmitCheckValue(Value));
1364 llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile,
1367 AlignmentSource AlignSource,
1368 llvm::MDNode *TBAAInfo,
1369 QualType TBAABaseType,
1370 uint64_t TBAAOffset,
1371 bool isNontemporal) {
1372 // For better performance, handle vector loads differently.
1373 if (Ty->isVectorType()) {
1374 const llvm::Type *EltTy = Addr.getElementType();
1376 const auto *VTy = cast<llvm::VectorType>(EltTy);
1378 // Handle vectors of size 3 like size 4 for better performance.
1379 if (VTy->getNumElements() == 3) {
1381 // Bitcast to vec4 type.
1382 llvm::VectorType *vec4Ty = llvm::VectorType::get(VTy->getElementType(),
1384 Address Cast = Builder.CreateElementBitCast(Addr, vec4Ty, "castToVec4");
1386 llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4");
1388 // Shuffle vector to get vec3.
1389 V = Builder.CreateShuffleVector(V, llvm::UndefValue::get(vec4Ty),
1390 {0, 1, 2}, "extractVec");
1391 return EmitFromMemory(V, Ty);
1395 // Atomic operations have to be done on integral types.
1396 LValue AtomicLValue =
1397 LValue::MakeAddr(Addr, Ty, getContext(), AlignSource, TBAAInfo);
1398 if (Ty->isAtomicType() || LValueIsSuitableForInlineAtomic(AtomicLValue)) {
1399 return EmitAtomicLoad(AtomicLValue, Loc).getScalarVal();
1402 llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
1403 if (isNontemporal) {
1404 llvm::MDNode *Node = llvm::MDNode::get(
1405 Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1406 Load->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1409 llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
1412 CGM.DecorateInstructionWithTBAA(Load, TBAAPath,
1413 false /*ConvertTypeToTag*/);
1416 if (EmitScalarRangeCheck(Load, Ty, Loc)) {
1417 // In order to prevent the optimizer from throwing away the check, don't
1418 // attach range metadata to the load.
1419 } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
1420 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
1421 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
1423 return EmitFromMemory(Load, Ty);
1426 llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
1427 // Bool has a different representation in memory than in registers.
1428 if (hasBooleanRepresentation(Ty)) {
1429 // This should really always be an i1, but sometimes it's already
1430 // an i8, and it's awkward to track those cases down.
1431 if (Value->getType()->isIntegerTy(1))
1432 return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
1433 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1434 "wrong value rep of bool");
1440 llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
1441 // Bool has a different representation in memory than in registers.
1442 if (hasBooleanRepresentation(Ty)) {
1443 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1444 "wrong value rep of bool");
1445 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
1451 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr,
1452 bool Volatile, QualType Ty,
1453 AlignmentSource AlignSource,
1454 llvm::MDNode *TBAAInfo,
1455 bool isInit, QualType TBAABaseType,
1456 uint64_t TBAAOffset,
1457 bool isNontemporal) {
1459 // Handle vectors differently to get better performance.
1460 if (Ty->isVectorType()) {
1461 llvm::Type *SrcTy = Value->getType();
1462 auto *VecTy = cast<llvm::VectorType>(SrcTy);
1463 // Handle vec3 special.
1464 if (VecTy->getNumElements() == 3) {
1465 // Our source is a vec3, do a shuffle vector to make it a vec4.
1466 llvm::Constant *Mask[] = {Builder.getInt32(0), Builder.getInt32(1),
1467 Builder.getInt32(2),
1468 llvm::UndefValue::get(Builder.getInt32Ty())};
1469 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1470 Value = Builder.CreateShuffleVector(Value,
1471 llvm::UndefValue::get(VecTy),
1472 MaskV, "extractVec");
1473 SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
1475 if (Addr.getElementType() != SrcTy) {
1476 Addr = Builder.CreateElementBitCast(Addr, SrcTy, "storetmp");
1480 Value = EmitToMemory(Value, Ty);
1482 LValue AtomicLValue =
1483 LValue::MakeAddr(Addr, Ty, getContext(), AlignSource, TBAAInfo);
1484 if (Ty->isAtomicType() ||
1485 (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) {
1486 EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit);
1490 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
1491 if (isNontemporal) {
1492 llvm::MDNode *Node =
1493 llvm::MDNode::get(Store->getContext(),
1494 llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1495 Store->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1498 llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
1501 CGM.DecorateInstructionWithTBAA(Store, TBAAPath,
1502 false /*ConvertTypeToTag*/);
1506 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
1508 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
1509 lvalue.getType(), lvalue.getAlignmentSource(),
1510 lvalue.getTBAAInfo(), isInit, lvalue.getTBAABaseType(),
1511 lvalue.getTBAAOffset(), lvalue.isNontemporal());
1514 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1515 /// method emits the address of the lvalue, then loads the result as an rvalue,
1516 /// returning the rvalue.
1517 RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
1518 if (LV.isObjCWeak()) {
1519 // load of a __weak object.
1520 Address AddrWeakObj = LV.getAddress();
1521 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1524 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
1525 // In MRC mode, we do a load+autorelease.
1526 if (!getLangOpts().ObjCAutoRefCount) {
1527 return RValue::get(EmitARCLoadWeak(LV.getAddress()));
1530 // In ARC mode, we load retained and then consume the value.
1531 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
1532 Object = EmitObjCConsumeObject(LV.getType(), Object);
1533 return RValue::get(Object);
1536 if (LV.isSimple()) {
1537 assert(!LV.getType()->isFunctionType());
1539 // Everything needs a load.
1540 return RValue::get(EmitLoadOfScalar(LV, Loc));
1543 if (LV.isVectorElt()) {
1544 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
1545 LV.isVolatileQualified());
1546 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
1550 // If this is a reference to a subset of the elements of a vector, either
1551 // shuffle the input or extract/insert them as appropriate.
1552 if (LV.isExtVectorElt())
1553 return EmitLoadOfExtVectorElementLValue(LV);
1555 // Global Register variables always invoke intrinsics
1556 if (LV.isGlobalReg())
1557 return EmitLoadOfGlobalRegLValue(LV);
1559 assert(LV.isBitField() && "Unknown LValue type!");
1560 return EmitLoadOfBitfieldLValue(LV, Loc);
1563 RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
1564 SourceLocation Loc) {
1565 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
1567 // Get the output type.
1568 llvm::Type *ResLTy = ConvertType(LV.getType());
1570 Address Ptr = LV.getBitFieldAddress();
1571 llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
1573 if (Info.IsSigned) {
1574 assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
1575 unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
1577 Val = Builder.CreateShl(Val, HighBits, "bf.shl");
1578 if (Info.Offset + HighBits)
1579 Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
1582 Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
1583 if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
1584 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
1588 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
1589 EmitScalarRangeCheck(Val, LV.getType(), Loc);
1590 return RValue::get(Val);
1593 // If this is a reference to a subset of the elements of a vector, create an
1594 // appropriate shufflevector.
1595 RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
1596 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
1597 LV.isVolatileQualified());
1599 const llvm::Constant *Elts = LV.getExtVectorElts();
1601 // If the result of the expression is a non-vector type, we must be extracting
1602 // a single element. Just codegen as an extractelement.
1603 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1605 unsigned InIdx = getAccessedFieldNo(0, Elts);
1606 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
1607 return RValue::get(Builder.CreateExtractElement(Vec, Elt));
1610 // Always use shuffle vector to try to retain the original program structure
1611 unsigned NumResultElts = ExprVT->getNumElements();
1613 SmallVector<llvm::Constant*, 4> Mask;
1614 for (unsigned i = 0; i != NumResultElts; ++i)
1615 Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
1617 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1618 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
1620 return RValue::get(Vec);
1623 /// @brief Generates lvalue for partial ext_vector access.
1624 Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
1625 Address VectorAddress = LV.getExtVectorAddress();
1626 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1627 QualType EQT = ExprVT->getElementType();
1628 llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
1630 Address CastToPointerElement =
1631 Builder.CreateElementBitCast(VectorAddress, VectorElementTy,
1632 "conv.ptr.element");
1634 const llvm::Constant *Elts = LV.getExtVectorElts();
1635 unsigned ix = getAccessedFieldNo(0, Elts);
1637 Address VectorBasePtrPlusIx =
1638 Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
1639 getContext().getTypeSizeInChars(EQT),
1642 return VectorBasePtrPlusIx;
1645 /// @brief Load of global gamed gegisters are always calls to intrinsics.
1646 RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
1647 assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
1648 "Bad type for register variable");
1649 llvm::MDNode *RegName = cast<llvm::MDNode>(
1650 cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
1652 // We accept integer and pointer types only
1653 llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
1654 llvm::Type *Ty = OrigTy;
1655 if (OrigTy->isPointerTy())
1656 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1657 llvm::Type *Types[] = { Ty };
1659 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
1660 llvm::Value *Call = Builder.CreateCall(
1661 F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
1662 if (OrigTy->isPointerTy())
1663 Call = Builder.CreateIntToPtr(Call, OrigTy);
1664 return RValue::get(Call);
1668 /// EmitStoreThroughLValue - Store the specified rvalue into the specified
1669 /// lvalue, where both are guaranteed to the have the same type, and that type
1671 void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
1673 if (!Dst.isSimple()) {
1674 if (Dst.isVectorElt()) {
1675 // Read/modify/write the vector, inserting the new element.
1676 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
1677 Dst.isVolatileQualified());
1678 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
1679 Dst.getVectorIdx(), "vecins");
1680 Builder.CreateStore(Vec, Dst.getVectorAddress(),
1681 Dst.isVolatileQualified());
1685 // If this is an update of extended vector elements, insert them as
1687 if (Dst.isExtVectorElt())
1688 return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
1690 if (Dst.isGlobalReg())
1691 return EmitStoreThroughGlobalRegLValue(Src, Dst);
1693 assert(Dst.isBitField() && "Unknown LValue type");
1694 return EmitStoreThroughBitfieldLValue(Src, Dst);
1697 // There's special magic for assigning into an ARC-qualified l-value.
1698 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
1700 case Qualifiers::OCL_None:
1701 llvm_unreachable("present but none");
1703 case Qualifiers::OCL_ExplicitNone:
1707 case Qualifiers::OCL_Strong:
1709 Src = RValue::get(EmitARCRetain(Dst.getType(), Src.getScalarVal()));
1712 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
1715 case Qualifiers::OCL_Weak:
1717 // Initialize and then skip the primitive store.
1718 EmitARCInitWeak(Dst.getAddress(), Src.getScalarVal());
1720 EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
1723 case Qualifiers::OCL_Autoreleasing:
1724 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
1725 Src.getScalarVal()));
1726 // fall into the normal path
1731 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
1732 // load of a __weak object.
1733 Address LvalueDst = Dst.getAddress();
1734 llvm::Value *src = Src.getScalarVal();
1735 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
1739 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
1740 // load of a __strong object.
1741 Address LvalueDst = Dst.getAddress();
1742 llvm::Value *src = Src.getScalarVal();
1743 if (Dst.isObjCIvar()) {
1744 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
1745 llvm::Type *ResultType = IntPtrTy;
1746 Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp());
1747 llvm::Value *RHS = dst.getPointer();
1748 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1750 Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType,
1751 "sub.ptr.lhs.cast");
1752 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
1753 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
1755 } else if (Dst.isGlobalObjCRef()) {
1756 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
1757 Dst.isThreadLocalRef());
1760 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
1764 assert(Src.isScalar() && "Can't emit an agg store with this method");
1765 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
1768 void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
1769 llvm::Value **Result) {
1770 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
1771 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
1772 Address Ptr = Dst.getBitFieldAddress();
1774 // Get the source value, truncated to the width of the bit-field.
1775 llvm::Value *SrcVal = Src.getScalarVal();
1777 // Cast the source to the storage type and shift it into place.
1778 SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
1779 /*IsSigned=*/false);
1780 llvm::Value *MaskedVal = SrcVal;
1782 // See if there are other bits in the bitfield's storage we'll need to load
1783 // and mask together with source before storing.
1784 if (Info.StorageSize != Info.Size) {
1785 assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
1787 Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
1789 // Mask the source value as needed.
1790 if (!hasBooleanRepresentation(Dst.getType()))
1791 SrcVal = Builder.CreateAnd(SrcVal,
1792 llvm::APInt::getLowBitsSet(Info.StorageSize,
1797 SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
1799 // Mask out the original value.
1800 Val = Builder.CreateAnd(Val,
1801 ~llvm::APInt::getBitsSet(Info.StorageSize,
1803 Info.Offset + Info.Size),
1806 // Or together the unchanged values and the source value.
1807 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
1809 assert(Info.Offset == 0);
1812 // Write the new value back out.
1813 Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
1815 // Return the new value of the bit-field, if requested.
1817 llvm::Value *ResultVal = MaskedVal;
1819 // Sign extend the value if needed.
1820 if (Info.IsSigned) {
1821 assert(Info.Size <= Info.StorageSize);
1822 unsigned HighBits = Info.StorageSize - Info.Size;
1824 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
1825 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
1829 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
1831 *Result = EmitFromMemory(ResultVal, Dst.getType());
1835 void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
1837 // This access turns into a read/modify/write of the vector. Load the input
1839 llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(),
1840 Dst.isVolatileQualified());
1841 const llvm::Constant *Elts = Dst.getExtVectorElts();
1843 llvm::Value *SrcVal = Src.getScalarVal();
1845 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
1846 unsigned NumSrcElts = VTy->getNumElements();
1847 unsigned NumDstElts = Vec->getType()->getVectorNumElements();
1848 if (NumDstElts == NumSrcElts) {
1849 // Use shuffle vector is the src and destination are the same number of
1850 // elements and restore the vector mask since it is on the side it will be
1852 SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
1853 for (unsigned i = 0; i != NumSrcElts; ++i)
1854 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
1856 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1857 Vec = Builder.CreateShuffleVector(SrcVal,
1858 llvm::UndefValue::get(Vec->getType()),
1860 } else if (NumDstElts > NumSrcElts) {
1861 // Extended the source vector to the same length and then shuffle it
1862 // into the destination.
1863 // FIXME: since we're shuffling with undef, can we just use the indices
1864 // into that? This could be simpler.
1865 SmallVector<llvm::Constant*, 4> ExtMask;
1866 for (unsigned i = 0; i != NumSrcElts; ++i)
1867 ExtMask.push_back(Builder.getInt32(i));
1868 ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
1869 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
1870 llvm::Value *ExtSrcVal =
1871 Builder.CreateShuffleVector(SrcVal,
1872 llvm::UndefValue::get(SrcVal->getType()),
1875 SmallVector<llvm::Constant*, 4> Mask;
1876 for (unsigned i = 0; i != NumDstElts; ++i)
1877 Mask.push_back(Builder.getInt32(i));
1879 // When the vector size is odd and .odd or .hi is used, the last element
1880 // of the Elts constant array will be one past the size of the vector.
1881 // Ignore the last element here, if it is greater than the mask size.
1882 if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
1885 // modify when what gets shuffled in
1886 for (unsigned i = 0; i != NumSrcElts; ++i)
1887 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
1888 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1889 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
1891 // We should never shorten the vector
1892 llvm_unreachable("unexpected shorten vector length");
1895 // If the Src is a scalar (not a vector) it must be updating one element.
1896 unsigned InIdx = getAccessedFieldNo(0, Elts);
1897 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
1898 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
1901 Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
1902 Dst.isVolatileQualified());
1905 /// @brief Store of global named registers are always calls to intrinsics.
1906 void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
1907 assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
1908 "Bad type for register variable");
1909 llvm::MDNode *RegName = cast<llvm::MDNode>(
1910 cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
1911 assert(RegName && "Register LValue is not metadata");
1913 // We accept integer and pointer types only
1914 llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
1915 llvm::Type *Ty = OrigTy;
1916 if (OrigTy->isPointerTy())
1917 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1918 llvm::Type *Types[] = { Ty };
1920 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
1921 llvm::Value *Value = Src.getScalarVal();
1922 if (OrigTy->isPointerTy())
1923 Value = Builder.CreatePtrToInt(Value, Ty);
1925 F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
1928 // setObjCGCLValueClass - sets class of the lvalue for the purpose of
1929 // generating write-barries API. It is currently a global, ivar,
1931 static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
1933 bool IsMemberAccess=false) {
1934 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
1937 if (isa<ObjCIvarRefExpr>(E)) {
1938 QualType ExpTy = E->getType();
1939 if (IsMemberAccess && ExpTy->isPointerType()) {
1940 // If ivar is a structure pointer, assigning to field of
1941 // this struct follows gcc's behavior and makes it a non-ivar
1942 // writer-barrier conservatively.
1943 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1944 if (ExpTy->isRecordType()) {
1945 LV.setObjCIvar(false);
1949 LV.setObjCIvar(true);
1950 auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
1951 LV.setBaseIvarExp(Exp->getBase());
1952 LV.setObjCArray(E->getType()->isArrayType());
1956 if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
1957 if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
1958 if (VD->hasGlobalStorage()) {
1959 LV.setGlobalObjCRef(true);
1960 LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
1963 LV.setObjCArray(E->getType()->isArrayType());
1967 if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
1968 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
1972 if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
1973 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
1974 if (LV.isObjCIvar()) {
1975 // If cast is to a structure pointer, follow gcc's behavior and make it
1976 // a non-ivar write-barrier.
1977 QualType ExpTy = E->getType();
1978 if (ExpTy->isPointerType())
1979 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1980 if (ExpTy->isRecordType())
1981 LV.setObjCIvar(false);
1986 if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
1987 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
1991 if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
1992 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
1996 if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
1997 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2001 if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
2002 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2006 if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
2007 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
2008 if (LV.isObjCIvar() && !LV.isObjCArray())
2009 // Using array syntax to assigning to what an ivar points to is not
2010 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
2011 LV.setObjCIvar(false);
2012 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
2013 // Using array syntax to assigning to what global points to is not
2014 // same as assigning to the global itself. {id *G;} G[i] = 0;
2015 LV.setGlobalObjCRef(false);
2019 if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
2020 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
2021 // We don't know if member is an 'ivar', but this flag is looked at
2022 // only in the context of LV.isObjCIvar().
2023 LV.setObjCArray(E->getType()->isArrayType());
2028 static llvm::Value *
2029 EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
2030 llvm::Value *V, llvm::Type *IRType,
2031 StringRef Name = StringRef()) {
2032 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
2033 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
2036 static LValue EmitThreadPrivateVarDeclLValue(
2037 CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
2038 llvm::Type *RealVarTy, SourceLocation Loc) {
2039 Addr = CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
2040 Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy);
2041 return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
2044 Address CodeGenFunction::EmitLoadOfReference(Address Addr,
2045 const ReferenceType *RefTy,
2046 AlignmentSource *Source) {
2047 llvm::Value *Ptr = Builder.CreateLoad(Addr);
2048 return Address(Ptr, getNaturalTypeAlignment(RefTy->getPointeeType(),
2049 Source, /*forPointee*/ true));
2053 LValue CodeGenFunction::EmitLoadOfReferenceLValue(Address RefAddr,
2054 const ReferenceType *RefTy) {
2055 AlignmentSource Source;
2056 Address Addr = EmitLoadOfReference(RefAddr, RefTy, &Source);
2057 return MakeAddrLValue(Addr, RefTy->getPointeeType(), Source);
2060 Address CodeGenFunction::EmitLoadOfPointer(Address Ptr,
2061 const PointerType *PtrTy,
2062 AlignmentSource *Source) {
2063 llvm::Value *Addr = Builder.CreateLoad(Ptr);
2064 return Address(Addr, getNaturalTypeAlignment(PtrTy->getPointeeType(), Source,
2065 /*forPointeeType=*/true));
2068 LValue CodeGenFunction::EmitLoadOfPointerLValue(Address PtrAddr,
2069 const PointerType *PtrTy) {
2070 AlignmentSource Source;
2071 Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &Source);
2072 return MakeAddrLValue(Addr, PtrTy->getPointeeType(), Source);
2075 static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
2076 const Expr *E, const VarDecl *VD) {
2077 QualType T = E->getType();
2079 // If it's thread_local, emit a call to its wrapper function instead.
2080 if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
2081 CGF.CGM.getCXXABI().usesThreadWrapperFunction())
2082 return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
2084 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
2085 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
2086 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
2087 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
2088 Address Addr(V, Alignment);
2090 // Emit reference to the private copy of the variable if it is an OpenMP
2091 // threadprivate variable.
2092 if (CGF.getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>())
2093 return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
2095 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2096 LV = CGF.EmitLoadOfReferenceLValue(Addr, RefTy);
2098 LV = CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
2100 setObjCGCLValueClass(CGF.getContext(), E, LV);
2104 static llvm::Constant *EmitFunctionDeclPointer(CodeGenModule &CGM,
2105 const FunctionDecl *FD) {
2106 if (FD->hasAttr<WeakRefAttr>()) {
2107 ConstantAddress aliasee = CGM.GetWeakRefReference(FD);
2108 return aliasee.getPointer();
2111 llvm::Constant *V = CGM.GetAddrOfFunction(FD);
2112 if (!FD->hasPrototype()) {
2113 if (const FunctionProtoType *Proto =
2114 FD->getType()->getAs<FunctionProtoType>()) {
2115 // Ugly case: for a K&R-style definition, the type of the definition
2116 // isn't the same as the type of a use. Correct for this with a
2118 QualType NoProtoType =
2119 CGM.getContext().getFunctionNoProtoType(Proto->getReturnType());
2120 NoProtoType = CGM.getContext().getPointerType(NoProtoType);
2121 V = llvm::ConstantExpr::getBitCast(V,
2122 CGM.getTypes().ConvertType(NoProtoType));
2128 static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
2129 const Expr *E, const FunctionDecl *FD) {
2130 llvm::Value *V = EmitFunctionDeclPointer(CGF.CGM, FD);
2131 CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
2132 return CGF.MakeAddrLValue(V, E->getType(), Alignment, AlignmentSource::Decl);
2135 static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
2136 llvm::Value *ThisValue) {
2137 QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
2138 LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
2139 return CGF.EmitLValueForField(LV, FD);
2142 /// Named Registers are named metadata pointing to the register name
2143 /// which will be read from/written to as an argument to the intrinsic
2144 /// @llvm.read/write_register.
2145 /// So far, only the name is being passed down, but other options such as
2146 /// register type, allocation type or even optimization options could be
2147 /// passed down via the metadata node.
2148 static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
2149 SmallString<64> Name("llvm.named.register.");
2150 AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
2151 assert(Asm->getLabel().size() < 64-Name.size() &&
2152 "Register name too big");
2153 Name.append(Asm->getLabel());
2154 llvm::NamedMDNode *M =
2155 CGM.getModule().getOrInsertNamedMetadata(Name);
2156 if (M->getNumOperands() == 0) {
2157 llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
2159 llvm::Metadata *Ops[] = {Str};
2160 M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2163 CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
2166 llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
2167 return LValue::MakeGlobalReg(Address(Ptr, Alignment), VD->getType());
2170 LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
2171 const NamedDecl *ND = E->getDecl();
2172 QualType T = E->getType();
2174 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2175 // Global Named registers access via intrinsics only
2176 if (VD->getStorageClass() == SC_Register &&
2177 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
2178 return EmitGlobalNamedRegister(VD, CGM);
2180 // A DeclRefExpr for a reference initialized by a constant expression can
2181 // appear without being odr-used. Directly emit the constant initializer.
2182 const Expr *Init = VD->getAnyInitializer(VD);
2183 if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() &&
2184 VD->isUsableInConstantExpressions(getContext()) &&
2185 VD->checkInitIsICE() &&
2186 // Do not emit if it is private OpenMP variable.
2187 !(E->refersToEnclosingVariableOrCapture() && CapturedStmtInfo &&
2188 LocalDeclMap.count(VD))) {
2189 llvm::Constant *Val =
2190 CGM.EmitConstantValue(*VD->evaluateValue(), VD->getType(), this);
2191 assert(Val && "failed to emit reference constant expression");
2192 // FIXME: Eventually we will want to emit vector element references.
2194 // Should we be using the alignment of the constant pointer we emitted?
2195 CharUnits Alignment = getNaturalTypeAlignment(E->getType(), nullptr,
2198 return MakeAddrLValue(Address(Val, Alignment), T, AlignmentSource::Decl);
2201 // Check for captured variables.
2202 if (E->refersToEnclosingVariableOrCapture()) {
2203 if (auto *FD = LambdaCaptureFields.lookup(VD))
2204 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
2205 else if (CapturedStmtInfo) {
2206 auto I = LocalDeclMap.find(VD);
2207 if (I != LocalDeclMap.end()) {
2208 if (auto RefTy = VD->getType()->getAs<ReferenceType>())
2209 return EmitLoadOfReferenceLValue(I->second, RefTy);
2210 return MakeAddrLValue(I->second, T);
2213 EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
2214 CapturedStmtInfo->getContextValue());
2215 return MakeAddrLValue(
2216 Address(CapLVal.getPointer(), getContext().getDeclAlign(VD)),
2217 CapLVal.getType(), AlignmentSource::Decl);
2220 assert(isa<BlockDecl>(CurCodeDecl));
2221 Address addr = GetAddrOfBlockDecl(VD, VD->hasAttr<BlocksAttr>());
2222 return MakeAddrLValue(addr, T, AlignmentSource::Decl);
2226 // FIXME: We should be able to assert this for FunctionDecls as well!
2227 // FIXME: We should be able to assert this for all DeclRefExprs, not just
2228 // those with a valid source location.
2229 assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
2230 !E->getLocation().isValid()) &&
2231 "Should not use decl without marking it used!");
2233 if (ND->hasAttr<WeakRefAttr>()) {
2234 const auto *VD = cast<ValueDecl>(ND);
2235 ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
2236 return MakeAddrLValue(Aliasee, T, AlignmentSource::Decl);
2239 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2240 // Check if this is a global variable.
2241 if (VD->hasLinkage() || VD->isStaticDataMember())
2242 return EmitGlobalVarDeclLValue(*this, E, VD);
2244 Address addr = Address::invalid();
2246 // The variable should generally be present in the local decl map.
2247 auto iter = LocalDeclMap.find(VD);
2248 if (iter != LocalDeclMap.end()) {
2249 addr = iter->second;
2251 // Otherwise, it might be static local we haven't emitted yet for
2252 // some reason; most likely, because it's in an outer function.
2253 } else if (VD->isStaticLocal()) {
2254 addr = Address(CGM.getOrCreateStaticVarDecl(
2255 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false)),
2256 getContext().getDeclAlign(VD));
2258 // No other cases for now.
2260 llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
2264 // Check for OpenMP threadprivate variables.
2265 if (getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
2266 return EmitThreadPrivateVarDeclLValue(
2267 *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
2271 // Drill into block byref variables.
2272 bool isBlockByref = VD->hasAttr<BlocksAttr>();
2274 addr = emitBlockByrefAddress(addr, VD);
2277 // Drill into reference types.
2279 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2280 LV = EmitLoadOfReferenceLValue(addr, RefTy);
2282 LV = MakeAddrLValue(addr, T, AlignmentSource::Decl);
2285 bool isLocalStorage = VD->hasLocalStorage();
2287 bool NonGCable = isLocalStorage &&
2288 !VD->getType()->isReferenceType() &&
2291 LV.getQuals().removeObjCGCAttr();
2295 bool isImpreciseLifetime =
2296 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
2297 if (isImpreciseLifetime)
2298 LV.setARCPreciseLifetime(ARCImpreciseLifetime);
2299 setObjCGCLValueClass(getContext(), E, LV);
2303 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
2304 return EmitFunctionDeclLValue(*this, E, FD);
2306 // FIXME: While we're emitting a binding from an enclosing scope, all other
2307 // DeclRefExprs we see should be implicitly treated as if they also refer to
2308 // an enclosing scope.
2309 if (const auto *BD = dyn_cast<BindingDecl>(ND))
2310 return EmitLValue(BD->getBinding());
2312 llvm_unreachable("Unhandled DeclRefExpr");
2315 LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
2316 // __extension__ doesn't affect lvalue-ness.
2317 if (E->getOpcode() == UO_Extension)
2318 return EmitLValue(E->getSubExpr());
2320 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
2321 switch (E->getOpcode()) {
2322 default: llvm_unreachable("Unknown unary operator lvalue!");
2324 QualType T = E->getSubExpr()->getType()->getPointeeType();
2325 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
2327 AlignmentSource AlignSource;
2328 Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &AlignSource);
2329 LValue LV = MakeAddrLValue(Addr, T, AlignSource);
2330 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
2332 // We should not generate __weak write barrier on indirect reference
2333 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
2334 // But, we continue to generate __strong write barrier on indirect write
2335 // into a pointer to object.
2336 if (getLangOpts().ObjC1 &&
2337 getLangOpts().getGC() != LangOptions::NonGC &&
2339 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
2344 LValue LV = EmitLValue(E->getSubExpr());
2345 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
2347 // __real is valid on scalars. This is a faster way of testing that.
2348 // __imag can only produce an rvalue on scalars.
2349 if (E->getOpcode() == UO_Real &&
2350 !LV.getAddress().getElementType()->isStructTy()) {
2351 assert(E->getSubExpr()->getType()->isArithmeticType());
2355 QualType T = ExprTy->castAs<ComplexType>()->getElementType();
2358 (E->getOpcode() == UO_Real
2359 ? emitAddrOfRealComponent(LV.getAddress(), LV.getType())
2360 : emitAddrOfImagComponent(LV.getAddress(), LV.getType()));
2361 LValue ElemLV = MakeAddrLValue(Component, T, LV.getAlignmentSource());
2362 ElemLV.getQuals().addQualifiers(LV.getQuals());
2367 LValue LV = EmitLValue(E->getSubExpr());
2368 bool isInc = E->getOpcode() == UO_PreInc;
2370 if (E->getType()->isAnyComplexType())
2371 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
2373 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
2379 LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
2380 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
2381 E->getType(), AlignmentSource::Decl);
2384 LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
2385 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
2386 E->getType(), AlignmentSource::Decl);
2389 LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
2390 auto SL = E->getFunctionName();
2391 assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
2392 StringRef FnName = CurFn->getName();
2393 if (FnName.startswith("\01"))
2394 FnName = FnName.substr(1);
2395 StringRef NameItems[] = {
2396 PredefinedExpr::getIdentTypeName(E->getIdentType()), FnName};
2397 std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
2398 if (auto *BD = dyn_cast<BlockDecl>(CurCodeDecl)) {
2399 std::string Name = SL->getString();
2400 if (!Name.empty()) {
2401 unsigned Discriminator =
2402 CGM.getCXXABI().getMangleContext().getBlockId(BD, true);
2404 Name += "_" + Twine(Discriminator + 1).str();
2405 auto C = CGM.GetAddrOfConstantCString(Name, GVName.c_str());
2406 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
2408 auto C = CGM.GetAddrOfConstantCString(FnName, GVName.c_str());
2409 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
2412 auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
2413 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
2416 /// Emit a type description suitable for use by a runtime sanitizer library. The
2417 /// format of a type descriptor is
2420 /// { i16 TypeKind, i16 TypeInfo }
2423 /// followed by an array of i8 containing the type name. TypeKind is 0 for an
2424 /// integer, 1 for a floating point value, and -1 for anything else.
2425 llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
2426 // Only emit each type's descriptor once.
2427 if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
2430 uint16_t TypeKind = -1;
2431 uint16_t TypeInfo = 0;
2433 if (T->isIntegerType()) {
2435 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
2436 (T->isSignedIntegerType() ? 1 : 0);
2437 } else if (T->isFloatingType()) {
2439 TypeInfo = getContext().getTypeSize(T);
2442 // Format the type name as if for a diagnostic, including quotes and
2443 // optionally an 'aka'.
2444 SmallString<32> Buffer;
2445 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
2446 (intptr_t)T.getAsOpaquePtr(),
2447 StringRef(), StringRef(), None, Buffer,
2450 llvm::Constant *Components[] = {
2451 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
2452 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
2454 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
2456 auto *GV = new llvm::GlobalVariable(
2457 CGM.getModule(), Descriptor->getType(),
2458 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
2459 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2460 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
2462 // Remember the descriptor for this type.
2463 CGM.setTypeDescriptorInMap(T, GV);
2468 llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
2469 llvm::Type *TargetTy = IntPtrTy;
2471 // Floating-point types which fit into intptr_t are bitcast to integers
2472 // and then passed directly (after zero-extension, if necessary).
2473 if (V->getType()->isFloatingPointTy()) {
2474 unsigned Bits = V->getType()->getPrimitiveSizeInBits();
2475 if (Bits <= TargetTy->getIntegerBitWidth())
2476 V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
2480 // Integers which fit in intptr_t are zero-extended and passed directly.
2481 if (V->getType()->isIntegerTy() &&
2482 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
2483 return Builder.CreateZExt(V, TargetTy);
2485 // Pointers are passed directly, everything else is passed by address.
2486 if (!V->getType()->isPointerTy()) {
2487 Address Ptr = CreateDefaultAlignTempAlloca(V->getType());
2488 Builder.CreateStore(V, Ptr);
2489 V = Ptr.getPointer();
2491 return Builder.CreatePtrToInt(V, TargetTy);
2494 /// \brief Emit a representation of a SourceLocation for passing to a handler
2495 /// in a sanitizer runtime library. The format for this data is:
2497 /// struct SourceLocation {
2498 /// const char *Filename;
2499 /// int32_t Line, Column;
2502 /// For an invalid SourceLocation, the Filename pointer is null.
2503 llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
2504 llvm::Constant *Filename;
2507 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
2508 if (PLoc.isValid()) {
2509 StringRef FilenameString = PLoc.getFilename();
2511 int PathComponentsToStrip =
2512 CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
2513 if (PathComponentsToStrip < 0) {
2514 assert(PathComponentsToStrip != INT_MIN);
2515 int PathComponentsToKeep = -PathComponentsToStrip;
2516 auto I = llvm::sys::path::rbegin(FilenameString);
2517 auto E = llvm::sys::path::rend(FilenameString);
2518 while (I != E && --PathComponentsToKeep)
2521 FilenameString = FilenameString.substr(I - E);
2522 } else if (PathComponentsToStrip > 0) {
2523 auto I = llvm::sys::path::begin(FilenameString);
2524 auto E = llvm::sys::path::end(FilenameString);
2525 while (I != E && PathComponentsToStrip--)
2530 FilenameString.substr(I - llvm::sys::path::begin(FilenameString));
2532 FilenameString = llvm::sys::path::filename(FilenameString);
2535 auto FilenameGV = CGM.GetAddrOfConstantCString(FilenameString, ".src");
2536 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
2537 cast<llvm::GlobalVariable>(FilenameGV.getPointer()));
2538 Filename = FilenameGV.getPointer();
2539 Line = PLoc.getLine();
2540 Column = PLoc.getColumn();
2542 Filename = llvm::Constant::getNullValue(Int8PtrTy);
2546 llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
2547 Builder.getInt32(Column)};
2549 return llvm::ConstantStruct::getAnon(Data);
2553 /// \brief Specify under what conditions this check can be recovered
2554 enum class CheckRecoverableKind {
2555 /// Always terminate program execution if this check fails.
2557 /// Check supports recovering, runtime has both fatal (noreturn) and
2558 /// non-fatal handlers for this check.
2560 /// Runtime conditionally aborts, always need to support recovery.
2565 static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
2566 assert(llvm::countPopulation(Kind) == 1);
2568 case SanitizerKind::Vptr:
2569 return CheckRecoverableKind::AlwaysRecoverable;
2570 case SanitizerKind::Return:
2571 case SanitizerKind::Unreachable:
2572 return CheckRecoverableKind::Unrecoverable;
2574 return CheckRecoverableKind::Recoverable;
2579 struct SanitizerHandlerInfo {
2580 char const *const Name;
2585 const SanitizerHandlerInfo SanitizerHandlers[] = {
2586 #define SANITIZER_CHECK(Enum, Name, Version) {#Name, Version},
2587 LIST_SANITIZER_CHECKS
2588 #undef SANITIZER_CHECK
2591 static void emitCheckHandlerCall(CodeGenFunction &CGF,
2592 llvm::FunctionType *FnType,
2593 ArrayRef<llvm::Value *> FnArgs,
2594 SanitizerHandler CheckHandler,
2595 CheckRecoverableKind RecoverKind, bool IsFatal,
2596 llvm::BasicBlock *ContBB) {
2597 assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
2598 bool NeedsAbortSuffix =
2599 IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
2600 const SanitizerHandlerInfo &CheckInfo = SanitizerHandlers[CheckHandler];
2601 const StringRef CheckName = CheckInfo.Name;
2602 std::string FnName =
2603 ("__ubsan_handle_" + CheckName +
2604 (CheckInfo.Version ? "_v" + llvm::utostr(CheckInfo.Version) : "") +
2605 (NeedsAbortSuffix ? "_abort" : ""))
2608 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
2610 llvm::AttrBuilder B;
2612 B.addAttribute(llvm::Attribute::NoReturn)
2613 .addAttribute(llvm::Attribute::NoUnwind);
2615 B.addAttribute(llvm::Attribute::UWTable);
2617 llvm::Value *Fn = CGF.CGM.CreateRuntimeFunction(
2619 llvm::AttributeList::get(CGF.getLLVMContext(),
2620 llvm::AttributeList::FunctionIndex, B),
2622 llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
2624 HandlerCall->setDoesNotReturn();
2625 CGF.Builder.CreateUnreachable();
2627 CGF.Builder.CreateBr(ContBB);
2631 void CodeGenFunction::EmitCheck(
2632 ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
2633 SanitizerHandler CheckHandler, ArrayRef<llvm::Constant *> StaticArgs,
2634 ArrayRef<llvm::Value *> DynamicArgs) {
2635 assert(IsSanitizerScope);
2636 assert(Checked.size() > 0);
2637 assert(CheckHandler >= 0 &&
2638 CheckHandler < sizeof(SanitizerHandlers) / sizeof(*SanitizerHandlers));
2639 const StringRef CheckName = SanitizerHandlers[CheckHandler].Name;
2641 llvm::Value *FatalCond = nullptr;
2642 llvm::Value *RecoverableCond = nullptr;
2643 llvm::Value *TrapCond = nullptr;
2644 for (int i = 0, n = Checked.size(); i < n; ++i) {
2645 llvm::Value *Check = Checked[i].first;
2646 // -fsanitize-trap= overrides -fsanitize-recover=.
2647 llvm::Value *&Cond =
2648 CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
2650 : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
2653 Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
2657 EmitTrapCheck(TrapCond);
2658 if (!FatalCond && !RecoverableCond)
2661 llvm::Value *JointCond;
2662 if (FatalCond && RecoverableCond)
2663 JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
2665 JointCond = FatalCond ? FatalCond : RecoverableCond;
2668 CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
2669 assert(SanOpts.has(Checked[0].second));
2671 for (int i = 1, n = Checked.size(); i < n; ++i) {
2672 assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
2673 "All recoverable kinds in a single check must be same!");
2674 assert(SanOpts.has(Checked[i].second));
2678 llvm::BasicBlock *Cont = createBasicBlock("cont");
2679 llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
2680 llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
2681 // Give hint that we very much don't expect to execute the handler
2682 // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
2683 llvm::MDBuilder MDHelper(getLLVMContext());
2684 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2685 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
2686 EmitBlock(Handlers);
2688 // Handler functions take an i8* pointing to the (handler-specific) static
2689 // information block, followed by a sequence of intptr_t arguments
2690 // representing operand values.
2691 SmallVector<llvm::Value *, 4> Args;
2692 SmallVector<llvm::Type *, 4> ArgTypes;
2693 Args.reserve(DynamicArgs.size() + 1);
2694 ArgTypes.reserve(DynamicArgs.size() + 1);
2696 // Emit handler arguments and create handler function type.
2697 if (!StaticArgs.empty()) {
2698 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2700 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2701 llvm::GlobalVariable::PrivateLinkage, Info);
2702 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2703 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2704 Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
2705 ArgTypes.push_back(Int8PtrTy);
2708 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
2709 Args.push_back(EmitCheckValue(DynamicArgs[i]));
2710 ArgTypes.push_back(IntPtrTy);
2713 llvm::FunctionType *FnType =
2714 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
2716 if (!FatalCond || !RecoverableCond) {
2717 // Simple case: we need to generate a single handler call, either
2718 // fatal, or non-fatal.
2719 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind,
2720 (FatalCond != nullptr), Cont);
2722 // Emit two handler calls: first one for set of unrecoverable checks,
2723 // another one for recoverable.
2724 llvm::BasicBlock *NonFatalHandlerBB =
2725 createBasicBlock("non_fatal." + CheckName);
2726 llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
2727 Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
2728 EmitBlock(FatalHandlerBB);
2729 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, true,
2731 EmitBlock(NonFatalHandlerBB);
2732 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, false,
2739 void CodeGenFunction::EmitCfiSlowPathCheck(
2740 SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId,
2741 llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) {
2742 llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
2744 llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
2745 llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
2747 llvm::MDBuilder MDHelper(getLLVMContext());
2748 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2749 BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
2753 bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind);
2755 llvm::CallInst *CheckCall;
2757 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2759 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2760 llvm::GlobalVariable::PrivateLinkage, Info);
2761 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2762 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2764 llvm::Constant *SlowPathDiagFn = CGM.getModule().getOrInsertFunction(
2765 "__cfi_slowpath_diag",
2766 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
2768 CheckCall = Builder.CreateCall(
2770 {TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)});
2772 llvm::Constant *SlowPathFn = CGM.getModule().getOrInsertFunction(
2774 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
2775 CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
2778 CheckCall->setDoesNotThrow();
2783 // This function is basically a switch over the CFI failure kind, which is
2784 // extracted from CFICheckFailData (1st function argument). Each case is either
2785 // llvm.trap or a call to one of the two runtime handlers, based on
2786 // -fsanitize-trap and -fsanitize-recover settings. Default case (invalid
2787 // failure kind) traps, but this should really never happen. CFICheckFailData
2788 // can be nullptr if the calling module has -fsanitize-trap behavior for this
2789 // check kind; in this case __cfi_check_fail traps as well.
2790 void CodeGenFunction::EmitCfiCheckFail() {
2791 SanitizerScope SanScope(this);
2792 FunctionArgList Args;
2793 ImplicitParamDecl ArgData(getContext(), nullptr, SourceLocation(), nullptr,
2794 getContext().VoidPtrTy);
2795 ImplicitParamDecl ArgAddr(getContext(), nullptr, SourceLocation(), nullptr,
2796 getContext().VoidPtrTy);
2797 Args.push_back(&ArgData);
2798 Args.push_back(&ArgAddr);
2800 const CGFunctionInfo &FI =
2801 CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args);
2803 llvm::Function *F = llvm::Function::Create(
2804 llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false),
2805 llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule());
2806 F->setVisibility(llvm::GlobalValue::HiddenVisibility);
2808 StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args,
2812 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false,
2813 CGM.getContext().VoidPtrTy, ArgData.getLocation());
2815 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false,
2816 CGM.getContext().VoidPtrTy, ArgAddr.getLocation());
2818 // Data == nullptr means the calling module has trap behaviour for this check.
2819 llvm::Value *DataIsNotNullPtr =
2820 Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy));
2821 EmitTrapCheck(DataIsNotNullPtr);
2823 llvm::StructType *SourceLocationTy =
2824 llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty, nullptr);
2825 llvm::StructType *CfiCheckFailDataTy =
2826 llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy, nullptr);
2828 llvm::Value *V = Builder.CreateConstGEP2_32(
2830 Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0,
2832 Address CheckKindAddr(V, getIntAlign());
2833 llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr);
2835 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
2836 CGM.getLLVMContext(),
2837 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
2838 llvm::Value *ValidVtable = Builder.CreateZExt(
2839 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
2840 {Addr, AllVtables}),
2843 const std::pair<int, SanitizerMask> CheckKinds[] = {
2844 {CFITCK_VCall, SanitizerKind::CFIVCall},
2845 {CFITCK_NVCall, SanitizerKind::CFINVCall},
2846 {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast},
2847 {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast},
2848 {CFITCK_ICall, SanitizerKind::CFIICall}};
2850 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 5> Checks;
2851 for (auto CheckKindMaskPair : CheckKinds) {
2852 int Kind = CheckKindMaskPair.first;
2853 SanitizerMask Mask = CheckKindMaskPair.second;
2855 Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind));
2856 if (CGM.getLangOpts().Sanitize.has(Mask))
2857 EmitCheck(std::make_pair(Cond, Mask), SanitizerHandler::CFICheckFail, {},
2858 {Data, Addr, ValidVtable});
2860 EmitTrapCheck(Cond);
2864 // The only reference to this function will be created during LTO link.
2865 // Make sure it survives until then.
2866 CGM.addUsedGlobal(F);
2869 void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) {
2870 llvm::BasicBlock *Cont = createBasicBlock("cont");
2872 // If we're optimizing, collapse all calls to trap down to just one per
2873 // function to save on code size.
2874 if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
2875 TrapBB = createBasicBlock("trap");
2876 Builder.CreateCondBr(Checked, Cont, TrapBB);
2878 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
2879 TrapCall->setDoesNotReturn();
2880 TrapCall->setDoesNotThrow();
2881 Builder.CreateUnreachable();
2883 Builder.CreateCondBr(Checked, Cont, TrapBB);
2889 llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
2890 llvm::CallInst *TrapCall = Builder.CreateCall(CGM.getIntrinsic(IntrID));
2892 if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
2893 auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
2894 CGM.getCodeGenOpts().TrapFuncName);
2895 TrapCall->addAttribute(llvm::AttributeList::FunctionIndex, A);
2901 Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E,
2902 AlignmentSource *AlignSource) {
2903 assert(E->getType()->isArrayType() &&
2904 "Array to pointer decay must have array source type!");
2906 // Expressions of array type can't be bitfields or vector elements.
2907 LValue LV = EmitLValue(E);
2908 Address Addr = LV.getAddress();
2909 if (AlignSource) *AlignSource = LV.getAlignmentSource();
2911 // If the array type was an incomplete type, we need to make sure
2912 // the decay ends up being the right type.
2913 llvm::Type *NewTy = ConvertType(E->getType());
2914 Addr = Builder.CreateElementBitCast(Addr, NewTy);
2916 // Note that VLA pointers are always decayed, so we don't need to do
2918 if (!E->getType()->isVariableArrayType()) {
2919 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
2920 "Expected pointer to array");
2921 Addr = Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(), "arraydecay");
2924 QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
2925 return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType));
2928 /// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
2929 /// array to pointer, return the array subexpression.
2930 static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
2931 // If this isn't just an array->pointer decay, bail out.
2932 const auto *CE = dyn_cast<CastExpr>(E);
2933 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
2936 // If this is a decay from variable width array, bail out.
2937 const Expr *SubExpr = CE->getSubExpr();
2938 if (SubExpr->getType()->isVariableArrayType())
2944 static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF,
2946 ArrayRef<llvm::Value*> indices,
2948 const llvm::Twine &name = "arrayidx") {
2950 return CGF.Builder.CreateInBoundsGEP(ptr, indices, name);
2952 return CGF.Builder.CreateGEP(ptr, indices, name);
2956 static CharUnits getArrayElementAlign(CharUnits arrayAlign,
2958 CharUnits eltSize) {
2959 // If we have a constant index, we can use the exact offset of the
2960 // element we're accessing.
2961 if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
2962 CharUnits offset = constantIdx->getZExtValue() * eltSize;
2963 return arrayAlign.alignmentAtOffset(offset);
2965 // Otherwise, use the worst-case alignment for any element.
2967 return arrayAlign.alignmentOfArrayElement(eltSize);
2971 static QualType getFixedSizeElementType(const ASTContext &ctx,
2972 const VariableArrayType *vla) {
2975 eltType = vla->getElementType();
2976 } while ((vla = ctx.getAsVariableArrayType(eltType)));
2980 static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
2981 ArrayRef<llvm::Value*> indices,
2982 QualType eltType, bool inbounds,
2983 const llvm::Twine &name = "arrayidx") {
2984 // All the indices except that last must be zero.
2986 for (auto idx : indices.drop_back())
2987 assert(isa<llvm::ConstantInt>(idx) &&
2988 cast<llvm::ConstantInt>(idx)->isZero());
2991 // Determine the element size of the statically-sized base. This is
2992 // the thing that the indices are expressed in terms of.
2993 if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
2994 eltType = getFixedSizeElementType(CGF.getContext(), vla);
2997 // We can use that to compute the best alignment of the element.
2998 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
2999 CharUnits eltAlign =
3000 getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
3002 llvm::Value *eltPtr =
3003 emitArraySubscriptGEP(CGF, addr.getPointer(), indices, inbounds, name);
3004 return Address(eltPtr, eltAlign);
3007 LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
3009 // The index must always be an integer, which is not an aggregate. Emit it
3010 // in lexical order (this complexity is, sadly, required by C++17).
3011 llvm::Value *IdxPre =
3012 (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E->getIdx()) : nullptr;
3013 auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * {
3015 if (E->getLHS() != E->getIdx()) {
3016 assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS");
3017 Idx = EmitScalarExpr(E->getIdx());
3020 QualType IdxTy = E->getIdx()->getType();
3021 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
3023 if (SanOpts.has(SanitizerKind::ArrayBounds))
3024 EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
3026 // Extend or truncate the index type to 32 or 64-bits.
3027 if (Promote && Idx->getType() != IntPtrTy)
3028 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
3034 // If the base is a vector type, then we are forming a vector element lvalue
3035 // with this subscript.
3036 if (E->getBase()->getType()->isVectorType() &&
3037 !isa<ExtVectorElementExpr>(E->getBase())) {
3038 // Emit the vector as an lvalue to get its address.
3039 LValue LHS = EmitLValue(E->getBase());
3040 auto *Idx = EmitIdxAfterBase(/*Promote*/false);
3041 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
3042 return LValue::MakeVectorElt(LHS.getAddress(), Idx,
3043 E->getBase()->getType(),
3044 LHS.getAlignmentSource());
3047 // All the other cases basically behave like simple offsetting.
3049 // Handle the extvector case we ignored above.
3050 if (isa<ExtVectorElementExpr>(E->getBase())) {
3051 LValue LV = EmitLValue(E->getBase());
3052 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3053 Address Addr = EmitExtVectorElementLValue(LV);
3055 QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
3056 Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true);
3057 return MakeAddrLValue(Addr, EltType, LV.getAlignmentSource());
3060 AlignmentSource AlignSource;
3061 Address Addr = Address::invalid();
3062 if (const VariableArrayType *vla =
3063 getContext().getAsVariableArrayType(E->getType())) {
3064 // The base must be a pointer, which is not an aggregate. Emit
3065 // it. It needs to be emitted first in case it's what captures
3067 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
3068 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3070 // The element count here is the total number of non-VLA elements.
3071 llvm::Value *numElements = getVLASize(vla).first;
3073 // Effectively, the multiply by the VLA size is part of the GEP.
3074 // GEP indexes are signed, and scaling an index isn't permitted to
3075 // signed-overflow, so we use the same semantics for our explicit
3076 // multiply. We suppress this if overflow is not undefined behavior.
3077 if (getLangOpts().isSignedOverflowDefined()) {
3078 Idx = Builder.CreateMul(Idx, numElements);
3080 Idx = Builder.CreateNSWMul(Idx, numElements);
3083 Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
3084 !getLangOpts().isSignedOverflowDefined());
3086 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
3087 // Indexing over an interface, as in "NSString *P; P[4];"
3089 // Emit the base pointer.
3090 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
3091 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3093 CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
3094 llvm::Value *InterfaceSizeVal =
3095 llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());
3097 llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
3099 // We don't necessarily build correct LLVM struct types for ObjC
3100 // interfaces, so we can't rely on GEP to do this scaling
3101 // correctly, so we need to cast to i8*. FIXME: is this actually
3102 // true? A lot of other things in the fragile ABI would break...
3103 llvm::Type *OrigBaseTy = Addr.getType();
3104 Addr = Builder.CreateElementBitCast(Addr, Int8Ty);
3107 CharUnits EltAlign =
3108 getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
3109 llvm::Value *EltPtr =
3110 emitArraySubscriptGEP(*this, Addr.getPointer(), ScaledIdx, false);
3111 Addr = Address(EltPtr, EltAlign);
3114 Addr = Builder.CreateBitCast(Addr, OrigBaseTy);
3115 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3116 // If this is A[i] where A is an array, the frontend will have decayed the
3117 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3118 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3119 // "gep x, i" here. Emit one "gep A, 0, i".
3120 assert(Array->getType()->isArrayType() &&
3121 "Array to pointer decay must have array source type!");
3123 // For simple multidimensional array indexing, set the 'accessed' flag for
3124 // better bounds-checking of the base expression.
3125 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3126 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3128 ArrayLV = EmitLValue(Array);
3129 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3131 // Propagate the alignment from the array itself to the result.
3132 Addr = emitArraySubscriptGEP(*this, ArrayLV.getAddress(),
3133 {CGM.getSize(CharUnits::Zero()), Idx},
3135 !getLangOpts().isSignedOverflowDefined());
3136 AlignSource = ArrayLV.getAlignmentSource();
3138 // The base must be a pointer; emit it with an estimate of its alignment.
3139 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
3140 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3141 Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
3142 !getLangOpts().isSignedOverflowDefined());
3145 LValue LV = MakeAddrLValue(Addr, E->getType(), AlignSource);
3147 // TODO: Preserve/extend path TBAA metadata?
3149 if (getLangOpts().ObjC1 &&
3150 getLangOpts().getGC() != LangOptions::NonGC) {
3151 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
3152 setObjCGCLValueClass(getContext(), E, LV);
3157 static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base,
3158 AlignmentSource &AlignSource,
3159 QualType BaseTy, QualType ElTy,
3160 bool IsLowerBound) {
3162 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParenImpCasts())) {
3163 BaseLVal = CGF.EmitOMPArraySectionExpr(ASE, IsLowerBound);
3164 if (BaseTy->isArrayType()) {
3165 Address Addr = BaseLVal.getAddress();
3166 AlignSource = BaseLVal.getAlignmentSource();
3168 // If the array type was an incomplete type, we need to make sure
3169 // the decay ends up being the right type.
3170 llvm::Type *NewTy = CGF.ConvertType(BaseTy);
3171 Addr = CGF.Builder.CreateElementBitCast(Addr, NewTy);
3173 // Note that VLA pointers are always decayed, so we don't need to do
3175 if (!BaseTy->isVariableArrayType()) {
3176 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3177 "Expected pointer to array");
3178 Addr = CGF.Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(),
3182 return CGF.Builder.CreateElementBitCast(Addr,
3183 CGF.ConvertTypeForMem(ElTy));
3185 CharUnits Align = CGF.getNaturalTypeAlignment(ElTy, &AlignSource);
3186 return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress()), Align);
3188 return CGF.EmitPointerWithAlignment(Base, &AlignSource);
3191 LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
3192 bool IsLowerBound) {
3195 dyn_cast<OMPArraySectionExpr>(E->getBase()->IgnoreParenImpCasts()))
3196 BaseTy = OMPArraySectionExpr::getBaseOriginalType(ASE);
3198 BaseTy = E->getBase()->getType();
3199 QualType ResultExprTy;
3200 if (auto *AT = getContext().getAsArrayType(BaseTy))
3201 ResultExprTy = AT->getElementType();
3203 ResultExprTy = BaseTy->getPointeeType();
3204 llvm::Value *Idx = nullptr;
3205 if (IsLowerBound || E->getColonLoc().isInvalid()) {
3206 // Requesting lower bound or upper bound, but without provided length and
3207 // without ':' symbol for the default length -> length = 1.
3208 // Idx = LowerBound ?: 0;
3209 if (auto *LowerBound = E->getLowerBound()) {
3210 Idx = Builder.CreateIntCast(
3211 EmitScalarExpr(LowerBound), IntPtrTy,
3212 LowerBound->getType()->hasSignedIntegerRepresentation());
3214 Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
3216 // Try to emit length or lower bound as constant. If this is possible, 1
3217 // is subtracted from constant length or lower bound. Otherwise, emit LLVM
3218 // IR (LB + Len) - 1.
3219 auto &C = CGM.getContext();
3220 auto *Length = E->getLength();
3221 llvm::APSInt ConstLength;
3223 // Idx = LowerBound + Length - 1;
3224 if (Length->isIntegerConstantExpr(ConstLength, C)) {
3225 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3228 auto *LowerBound = E->getLowerBound();
3229 llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
3230 if (LowerBound && LowerBound->isIntegerConstantExpr(ConstLowerBound, C)) {
3231 ConstLowerBound = ConstLowerBound.zextOrTrunc(PointerWidthInBits);
3232 LowerBound = nullptr;
3236 else if (!LowerBound)
3239 if (Length || LowerBound) {
3240 auto *LowerBoundVal =
3242 ? Builder.CreateIntCast(
3243 EmitScalarExpr(LowerBound), IntPtrTy,
3244 LowerBound->getType()->hasSignedIntegerRepresentation())
3245 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
3248 ? Builder.CreateIntCast(
3249 EmitScalarExpr(Length), IntPtrTy,
3250 Length->getType()->hasSignedIntegerRepresentation())
3251 : llvm::ConstantInt::get(IntPtrTy, ConstLength);
3252 Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
3254 !getLangOpts().isSignedOverflowDefined());
3255 if (Length && LowerBound) {
3256 Idx = Builder.CreateSub(
3257 Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
3258 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3261 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
3263 // Idx = ArraySize - 1;
3264 QualType ArrayTy = BaseTy->isPointerType()
3265 ? E->getBase()->IgnoreParenImpCasts()->getType()
3267 if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) {
3268 Length = VAT->getSizeExpr();
3269 if (Length->isIntegerConstantExpr(ConstLength, C))
3272 auto *CAT = C.getAsConstantArrayType(ArrayTy);
3273 ConstLength = CAT->getSize();
3276 auto *LengthVal = Builder.CreateIntCast(
3277 EmitScalarExpr(Length), IntPtrTy,
3278 Length->getType()->hasSignedIntegerRepresentation());
3279 Idx = Builder.CreateSub(
3280 LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
3281 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3283 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3285 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
3291 Address EltPtr = Address::invalid();
3292 AlignmentSource AlignSource;
3293 if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
3294 // The base must be a pointer, which is not an aggregate. Emit
3295 // it. It needs to be emitted first in case it's what captures
3298 emitOMPArraySectionBase(*this, E->getBase(), AlignSource, BaseTy,
3299 VLA->getElementType(), IsLowerBound);
3300 // The element count here is the total number of non-VLA elements.
3301 llvm::Value *NumElements = getVLASize(VLA).first;
3303 // Effectively, the multiply by the VLA size is part of the GEP.
3304 // GEP indexes are signed, and scaling an index isn't permitted to
3305 // signed-overflow, so we use the same semantics for our explicit
3306 // multiply. We suppress this if overflow is not undefined behavior.
3307 if (getLangOpts().isSignedOverflowDefined())
3308 Idx = Builder.CreateMul(Idx, NumElements);
3310 Idx = Builder.CreateNSWMul(Idx, NumElements);
3311 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(),
3312 !getLangOpts().isSignedOverflowDefined());
3313 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3314 // If this is A[i] where A is an array, the frontend will have decayed the
3315 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3316 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3317 // "gep x, i" here. Emit one "gep A, 0, i".
3318 assert(Array->getType()->isArrayType() &&
3319 "Array to pointer decay must have array source type!");
3321 // For simple multidimensional array indexing, set the 'accessed' flag for
3322 // better bounds-checking of the base expression.
3323 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3324 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3326 ArrayLV = EmitLValue(Array);
3328 // Propagate the alignment from the array itself to the result.
3329 EltPtr = emitArraySubscriptGEP(
3330 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
3331 ResultExprTy, !getLangOpts().isSignedOverflowDefined());
3332 AlignSource = ArrayLV.getAlignmentSource();
3334 Address Base = emitOMPArraySectionBase(*this, E->getBase(), AlignSource,
3335 BaseTy, ResultExprTy, IsLowerBound);
3336 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy,
3337 !getLangOpts().isSignedOverflowDefined());
3340 return MakeAddrLValue(EltPtr, ResultExprTy, AlignSource);
3343 LValue CodeGenFunction::
3344 EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
3345 // Emit the base vector as an l-value.
3348 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
3350 // If it is a pointer to a vector, emit the address and form an lvalue with
3352 AlignmentSource AlignSource;
3353 Address Ptr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
3354 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
3355 Base = MakeAddrLValue(Ptr, PT->getPointeeType(), AlignSource);
3356 Base.getQuals().removeObjCGCAttr();
3357 } else if (E->getBase()->isGLValue()) {
3358 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
3359 // emit the base as an lvalue.
3360 assert(E->getBase()->getType()->isVectorType());
3361 Base = EmitLValue(E->getBase());
3363 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
3364 assert(E->getBase()->getType()->isVectorType() &&
3365 "Result must be a vector");
3366 llvm::Value *Vec = EmitScalarExpr(E->getBase());
3368 // Store the vector to memory (because LValue wants an address).
3369 Address VecMem = CreateMemTemp(E->getBase()->getType());
3370 Builder.CreateStore(Vec, VecMem);
3371 Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
3372 AlignmentSource::Decl);
3376 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
3378 // Encode the element access list into a vector of unsigned indices.
3379 SmallVector<uint32_t, 4> Indices;
3380 E->getEncodedElementAccess(Indices);
3382 if (Base.isSimple()) {
3383 llvm::Constant *CV =
3384 llvm::ConstantDataVector::get(getLLVMContext(), Indices);
3385 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
3386 Base.getAlignmentSource());
3388 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
3390 llvm::Constant *BaseElts = Base.getExtVectorElts();
3391 SmallVector<llvm::Constant *, 4> CElts;
3393 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
3394 CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
3395 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
3396 return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
3397 Base.getAlignmentSource());
3400 LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
3401 Expr *BaseExpr = E->getBase();
3403 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
3406 AlignmentSource AlignSource;
3407 Address Addr = EmitPointerWithAlignment(BaseExpr, &AlignSource);
3408 QualType PtrTy = BaseExpr->getType()->getPointeeType();
3409 SanitizerSet SkippedChecks;
3410 if (IsDeclRefOrWrappedCXXThis(BaseExpr))
3411 SkippedChecks.set(SanitizerKind::Null, true);
3412 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy,
3413 /*Alignment=*/CharUnits::Zero(), SkippedChecks);
3414 BaseLV = MakeAddrLValue(Addr, PtrTy, AlignSource);
3416 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
3418 NamedDecl *ND = E->getMemberDecl();
3419 if (auto *Field = dyn_cast<FieldDecl>(ND)) {
3420 LValue LV = EmitLValueForField(BaseLV, Field);
3421 setObjCGCLValueClass(getContext(), E, LV);
3425 if (auto *VD = dyn_cast<VarDecl>(ND))
3426 return EmitGlobalVarDeclLValue(*this, E, VD);
3428 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
3429 return EmitFunctionDeclLValue(*this, E, FD);
3431 llvm_unreachable("Unhandled member declaration!");
3434 /// Given that we are currently emitting a lambda, emit an l-value for
3435 /// one of its members.
3436 LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
3437 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
3438 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
3439 QualType LambdaTagType =
3440 getContext().getTagDeclType(Field->getParent());
3441 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
3442 return EmitLValueForField(LambdaLV, Field);
3445 /// Drill down to the storage of a field without walking into
3446 /// reference types.
3448 /// The resulting address doesn't necessarily have the right type.
3449 static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
3450 const FieldDecl *field) {
3451 const RecordDecl *rec = field->getParent();
3454 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
3457 // Adjust the alignment down to the given offset.
3458 // As a special case, if the LLVM field index is 0, we know that this
3460 assert((idx != 0 || CGF.getContext().getASTRecordLayout(rec)
3461 .getFieldOffset(field->getFieldIndex()) == 0) &&
3462 "LLVM field at index zero had non-zero offset?");
3464 auto &recLayout = CGF.getContext().getASTRecordLayout(rec);
3465 auto offsetInBits = recLayout.getFieldOffset(field->getFieldIndex());
3466 offset = CGF.getContext().toCharUnitsFromBits(offsetInBits);
3469 return CGF.Builder.CreateStructGEP(base, idx, offset, field->getName());
3472 LValue CodeGenFunction::EmitLValueForField(LValue base,
3473 const FieldDecl *field) {
3474 AlignmentSource fieldAlignSource =
3475 getFieldAlignmentSource(base.getAlignmentSource());
3477 if (field->isBitField()) {
3478 const CGRecordLayout &RL =
3479 CGM.getTypes().getCGRecordLayout(field->getParent());
3480 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
3481 Address Addr = base.getAddress();
3482 unsigned Idx = RL.getLLVMFieldNo(field);
3484 // For structs, we GEP to the field that the record layout suggests.
3485 Addr = Builder.CreateStructGEP(Addr, Idx, Info.StorageOffset,
3487 // Get the access type.
3488 llvm::Type *FieldIntTy =
3489 llvm::Type::getIntNTy(getLLVMContext(), Info.StorageSize);
3490 if (Addr.getElementType() != FieldIntTy)
3491 Addr = Builder.CreateElementBitCast(Addr, FieldIntTy);
3493 QualType fieldType =
3494 field->getType().withCVRQualifiers(base.getVRQualifiers());
3495 return LValue::MakeBitfield(Addr, Info, fieldType, fieldAlignSource);
3498 const RecordDecl *rec = field->getParent();
3499 QualType type = field->getType();
3501 bool mayAlias = rec->hasAttr<MayAliasAttr>();
3503 Address addr = base.getAddress();
3504 unsigned cvr = base.getVRQualifiers();
3505 bool TBAAPath = CGM.getCodeGenOpts().StructPathTBAA;
3506 if (rec->isUnion()) {
3507 // For unions, there is no pointer adjustment.
3508 assert(!type->isReferenceType() && "union has reference member");
3509 // TODO: handle path-aware TBAA for union.
3512 // For structs, we GEP to the field that the record layout suggests.
3513 addr = emitAddrOfFieldStorage(*this, addr, field);
3515 // If this is a reference field, load the reference right now.
3516 if (const ReferenceType *refType = type->getAs<ReferenceType>()) {
3517 llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
3518 if (cvr & Qualifiers::Volatile) load->setVolatile(true);
3520 // Loading the reference will disable path-aware TBAA.
3522 if (CGM.shouldUseTBAA()) {
3525 tbaa = CGM.getTBAAInfo(getContext().CharTy);
3527 tbaa = CGM.getTBAAInfo(type);
3529 CGM.DecorateInstructionWithTBAA(load, tbaa);
3533 type = refType->getPointeeType();
3535 CharUnits alignment =
3536 getNaturalTypeAlignment(type, &fieldAlignSource, /*pointee*/ true);
3537 addr = Address(load, alignment);
3539 // Qualifiers on the struct don't apply to the referencee, and
3540 // we'll pick up CVR from the actual type later, so reset these
3541 // additional qualifiers now.
3546 // Make sure that the address is pointing to the right type. This is critical
3547 // for both unions and structs. A union needs a bitcast, a struct element
3548 // will need a bitcast if the LLVM type laid out doesn't match the desired
3550 addr = Builder.CreateElementBitCast(addr,
3551 CGM.getTypes().ConvertTypeForMem(type),
3554 if (field->hasAttr<AnnotateAttr>())
3555 addr = EmitFieldAnnotations(field, addr);
3557 LValue LV = MakeAddrLValue(addr, type, fieldAlignSource);
3558 LV.getQuals().addCVRQualifiers(cvr);
3560 const ASTRecordLayout &Layout =
3561 getContext().getASTRecordLayout(field->getParent());
3562 // Set the base type to be the base type of the base LValue and
3563 // update offset to be relative to the base type.
3564 LV.setTBAABaseType(mayAlias ? getContext().CharTy : base.getTBAABaseType());
3565 LV.setTBAAOffset(mayAlias ? 0 : base.getTBAAOffset() +
3566 Layout.getFieldOffset(field->getFieldIndex()) /
3567 getContext().getCharWidth());
3570 // __weak attribute on a field is ignored.
3571 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
3572 LV.getQuals().removeObjCGCAttr();
3574 // Fields of may_alias structs act like 'char' for TBAA purposes.
3575 // FIXME: this should get propagated down through anonymous structs
3577 if (mayAlias && LV.getTBAAInfo())
3578 LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy));
3584 CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
3585 const FieldDecl *Field) {
3586 QualType FieldType = Field->getType();
3588 if (!FieldType->isReferenceType())
3589 return EmitLValueForField(Base, Field);
3591 Address V = emitAddrOfFieldStorage(*this, Base.getAddress(), Field);
3593 // Make sure that the address is pointing to the right type.
3594 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
3595 V = Builder.CreateElementBitCast(V, llvmType, Field->getName());
3597 // TODO: access-path TBAA?
3598 auto FieldAlignSource = getFieldAlignmentSource(Base.getAlignmentSource());
3599 return MakeAddrLValue(V, FieldType, FieldAlignSource);
3602 LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
3603 if (E->isFileScope()) {
3604 ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
3605 return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl);
3607 if (E->getType()->isVariablyModifiedType())
3608 // make sure to emit the VLA size.
3609 EmitVariablyModifiedType(E->getType());
3611 Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
3612 const Expr *InitExpr = E->getInitializer();
3613 LValue Result = MakeAddrLValue(DeclPtr, E->getType(), AlignmentSource::Decl);
3615 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
3621 LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
3622 if (!E->isGLValue())
3623 // Initializing an aggregate temporary in C++11: T{...}.
3624 return EmitAggExprToLValue(E);
3626 // An lvalue initializer list must be initializing a reference.
3627 assert(E->isTransparent() && "non-transparent glvalue init list");
3628 return EmitLValue(E->getInit(0));
3631 /// Emit the operand of a glvalue conditional operator. This is either a glvalue
3632 /// or a (possibly-parenthesized) throw-expression. If this is a throw, no
3633 /// LValue is returned and the current block has been terminated.
3634 static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
3635 const Expr *Operand) {
3636 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
3637 CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
3641 return CGF.EmitLValue(Operand);
3644 LValue CodeGenFunction::
3645 EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
3646 if (!expr->isGLValue()) {
3647 // ?: here should be an aggregate.
3648 assert(hasAggregateEvaluationKind(expr->getType()) &&
3649 "Unexpected conditional operator!");
3650 return EmitAggExprToLValue(expr);
3653 OpaqueValueMapping binding(*this, expr);
3655 const Expr *condExpr = expr->getCond();
3657 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
3658 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
3659 if (!CondExprBool) std::swap(live, dead);
3661 if (!ContainsLabel(dead)) {
3662 // If the true case is live, we need to track its region.
3664 incrementProfileCounter(expr);
3665 return EmitLValue(live);
3669 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
3670 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
3671 llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
3673 ConditionalEvaluation eval(*this);
3674 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr));
3676 // Any temporaries created here are conditional.
3677 EmitBlock(lhsBlock);
3678 incrementProfileCounter(expr);
3680 Optional<LValue> lhs =
3681 EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
3684 if (lhs && !lhs->isSimple())
3685 return EmitUnsupportedLValue(expr, "conditional operator");
3687 lhsBlock = Builder.GetInsertBlock();
3689 Builder.CreateBr(contBlock);
3691 // Any temporaries created here are conditional.
3692 EmitBlock(rhsBlock);
3694 Optional<LValue> rhs =
3695 EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
3697 if (rhs && !rhs->isSimple())
3698 return EmitUnsupportedLValue(expr, "conditional operator");
3699 rhsBlock = Builder.GetInsertBlock();
3701 EmitBlock(contBlock);
3704 llvm::PHINode *phi = Builder.CreatePHI(lhs->getPointer()->getType(),
3706 phi->addIncoming(lhs->getPointer(), lhsBlock);
3707 phi->addIncoming(rhs->getPointer(), rhsBlock);
3708 Address result(phi, std::min(lhs->getAlignment(), rhs->getAlignment()));
3709 AlignmentSource alignSource =
3710 std::max(lhs->getAlignmentSource(), rhs->getAlignmentSource());
3711 return MakeAddrLValue(result, expr->getType(), alignSource);
3713 assert((lhs || rhs) &&
3714 "both operands of glvalue conditional are throw-expressions?");
3715 return lhs ? *lhs : *rhs;
3719 /// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
3720 /// type. If the cast is to a reference, we can have the usual lvalue result,
3721 /// otherwise if a cast is needed by the code generator in an lvalue context,
3722 /// then it must mean that we need the address of an aggregate in order to
3723 /// access one of its members. This can happen for all the reasons that casts
3724 /// are permitted with aggregate result, including noop aggregate casts, and
3725 /// cast from scalar to union.
3726 LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
3727 switch (E->getCastKind()) {
3730 case CK_ArrayToPointerDecay:
3731 case CK_FunctionToPointerDecay:
3732 case CK_NullToMemberPointer:
3733 case CK_NullToPointer:
3734 case CK_IntegralToPointer:
3735 case CK_PointerToIntegral:
3736 case CK_PointerToBoolean:
3737 case CK_VectorSplat:
3738 case CK_IntegralCast:
3739 case CK_BooleanToSignedIntegral:
3740 case CK_IntegralToBoolean:
3741 case CK_IntegralToFloating:
3742 case CK_FloatingToIntegral:
3743 case CK_FloatingToBoolean:
3744 case CK_FloatingCast:
3745 case CK_FloatingRealToComplex:
3746 case CK_FloatingComplexToReal:
3747 case CK_FloatingComplexToBoolean:
3748 case CK_FloatingComplexCast:
3749 case CK_FloatingComplexToIntegralComplex:
3750 case CK_IntegralRealToComplex:
3751 case CK_IntegralComplexToReal:
3752 case CK_IntegralComplexToBoolean:
3753 case CK_IntegralComplexCast:
3754 case CK_IntegralComplexToFloatingComplex:
3755 case CK_DerivedToBaseMemberPointer:
3756 case CK_BaseToDerivedMemberPointer:
3757 case CK_MemberPointerToBoolean:
3758 case CK_ReinterpretMemberPointer:
3759 case CK_AnyPointerToBlockPointerCast:
3760 case CK_ARCProduceObject:
3761 case CK_ARCConsumeObject:
3762 case CK_ARCReclaimReturnedObject:
3763 case CK_ARCExtendBlockObject:
3764 case CK_CopyAndAutoreleaseBlockObject:
3765 case CK_AddressSpaceConversion:
3766 case CK_IntToOCLSampler:
3767 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
3770 llvm_unreachable("dependent cast kind in IR gen!");
3772 case CK_BuiltinFnToFnPtr:
3773 llvm_unreachable("builtin functions are handled elsewhere");
3775 // These are never l-values; just use the aggregate emission code.
3776 case CK_NonAtomicToAtomic:
3777 case CK_AtomicToNonAtomic:
3778 return EmitAggExprToLValue(E);
3781 LValue LV = EmitLValue(E->getSubExpr());
3782 Address V = LV.getAddress();
3783 const auto *DCE = cast<CXXDynamicCastExpr>(E);
3784 return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
3787 case CK_ConstructorConversion:
3788 case CK_UserDefinedConversion:
3789 case CK_CPointerToObjCPointerCast:
3790 case CK_BlockPointerToObjCPointerCast:
3792 case CK_LValueToRValue:
3793 return EmitLValue(E->getSubExpr());
3795 case CK_UncheckedDerivedToBase:
3796 case CK_DerivedToBase: {
3797 const RecordType *DerivedClassTy =
3798 E->getSubExpr()->getType()->getAs<RecordType>();
3799 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
3801 LValue LV = EmitLValue(E->getSubExpr());
3802 Address This = LV.getAddress();
3804 // Perform the derived-to-base conversion
3805 Address Base = GetAddressOfBaseClass(
3806 This, DerivedClassDecl, E->path_begin(), E->path_end(),
3807 /*NullCheckValue=*/false, E->getExprLoc());
3809 return MakeAddrLValue(Base, E->getType(), LV.getAlignmentSource());
3812 return EmitAggExprToLValue(E);
3813 case CK_BaseToDerived: {
3814 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
3815 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
3817 LValue LV = EmitLValue(E->getSubExpr());
3819 // Perform the base-to-derived conversion
3821 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
3822 E->path_begin(), E->path_end(),
3823 /*NullCheckValue=*/false);
3825 // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
3826 // performed and the object is not of the derived type.
3827 if (sanitizePerformTypeCheck())
3828 EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
3829 Derived.getPointer(), E->getType());
3831 if (SanOpts.has(SanitizerKind::CFIDerivedCast))
3832 EmitVTablePtrCheckForCast(E->getType(), Derived.getPointer(),
3833 /*MayBeNull=*/false,
3834 CFITCK_DerivedCast, E->getLocStart());
3836 return MakeAddrLValue(Derived, E->getType(), LV.getAlignmentSource());
3838 case CK_LValueBitCast: {
3839 // This must be a reinterpret_cast (or c-style equivalent).
3840 const auto *CE = cast<ExplicitCastExpr>(E);
3842 CGM.EmitExplicitCastExprType(CE, this);
3843 LValue LV = EmitLValue(E->getSubExpr());
3844 Address V = Builder.CreateBitCast(LV.getAddress(),
3845 ConvertType(CE->getTypeAsWritten()));
3847 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
3848 EmitVTablePtrCheckForCast(E->getType(), V.getPointer(),
3849 /*MayBeNull=*/false,
3850 CFITCK_UnrelatedCast, E->getLocStart());
3852 return MakeAddrLValue(V, E->getType(), LV.getAlignmentSource());
3854 case CK_ObjCObjectLValueCast: {
3855 LValue LV = EmitLValue(E->getSubExpr());
3856 Address V = Builder.CreateElementBitCast(LV.getAddress(),
3857 ConvertType(E->getType()));
3858 return MakeAddrLValue(V, E->getType(), LV.getAlignmentSource());
3860 case CK_ZeroToOCLQueue:
3861 llvm_unreachable("NULL to OpenCL queue lvalue cast is not valid");
3862 case CK_ZeroToOCLEvent:
3863 llvm_unreachable("NULL to OpenCL event lvalue cast is not valid");
3866 llvm_unreachable("Unhandled lvalue cast kind?");
3869 LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
3870 assert(OpaqueValueMappingData::shouldBindAsLValue(e));
3871 return getOpaqueLValueMapping(e);
3874 RValue CodeGenFunction::EmitRValueForField(LValue LV,
3875 const FieldDecl *FD,
3876 SourceLocation Loc) {
3877 QualType FT = FD->getType();
3878 LValue FieldLV = EmitLValueForField(LV, FD);
3879 switch (getEvaluationKind(FT)) {
3881 return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
3883 return FieldLV.asAggregateRValue();
3885 // This routine is used to load fields one-by-one to perform a copy, so
3886 // don't load reference fields.
3887 if (FD->getType()->isReferenceType())
3888 return RValue::get(FieldLV.getPointer());
3889 return EmitLoadOfLValue(FieldLV, Loc);
3891 llvm_unreachable("bad evaluation kind");
3894 //===--------------------------------------------------------------------===//
3895 // Expression Emission
3896 //===--------------------------------------------------------------------===//
3898 RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
3899 ReturnValueSlot ReturnValue) {
3900 // Builtins never have block type.
3901 if (E->getCallee()->getType()->isBlockPointerType())
3902 return EmitBlockCallExpr(E, ReturnValue);
3904 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
3905 return EmitCXXMemberCallExpr(CE, ReturnValue);
3907 if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
3908 return EmitCUDAKernelCallExpr(CE, ReturnValue);
3910 if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
3911 if (const CXXMethodDecl *MD =
3912 dyn_cast_or_null<CXXMethodDecl>(CE->getCalleeDecl()))
3913 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
3915 CGCallee callee = EmitCallee(E->getCallee());
3917 if (callee.isBuiltin()) {
3918 return EmitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(),
3922 if (callee.isPseudoDestructor()) {
3923 return EmitCXXPseudoDestructorExpr(callee.getPseudoDestructorExpr());
3926 return EmitCall(E->getCallee()->getType(), callee, E, ReturnValue);
3929 /// Emit a CallExpr without considering whether it might be a subclass.
3930 RValue CodeGenFunction::EmitSimpleCallExpr(const CallExpr *E,
3931 ReturnValueSlot ReturnValue) {
3932 CGCallee Callee = EmitCallee(E->getCallee());
3933 return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue);
3936 static CGCallee EmitDirectCallee(CodeGenFunction &CGF, const FunctionDecl *FD) {
3937 if (auto builtinID = FD->getBuiltinID()) {
3938 return CGCallee::forBuiltin(builtinID, FD);
3941 llvm::Constant *calleePtr = EmitFunctionDeclPointer(CGF.CGM, FD);
3942 return CGCallee::forDirect(calleePtr, FD);
3945 CGCallee CodeGenFunction::EmitCallee(const Expr *E) {
3946 E = E->IgnoreParens();
3948 // Look through function-to-pointer decay.
3949 if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) {
3950 if (ICE->getCastKind() == CK_FunctionToPointerDecay ||
3951 ICE->getCastKind() == CK_BuiltinFnToFnPtr) {
3952 return EmitCallee(ICE->getSubExpr());
3955 // Resolve direct calls.
3956 } else if (auto DRE = dyn_cast<DeclRefExpr>(E)) {
3957 if (auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
3958 return EmitDirectCallee(*this, FD);
3960 } else if (auto ME = dyn_cast<MemberExpr>(E)) {
3961 if (auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) {
3962 EmitIgnoredExpr(ME->getBase());
3963 return EmitDirectCallee(*this, FD);
3966 // Look through template substitutions.
3967 } else if (auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
3968 return EmitCallee(NTTP->getReplacement());
3970 // Treat pseudo-destructor calls differently.
3971 } else if (auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) {
3972 return CGCallee::forPseudoDestructor(PDE);
3975 // Otherwise, we have an indirect reference.
3976 llvm::Value *calleePtr;
3977 QualType functionType;
3978 if (auto ptrType = E->getType()->getAs<PointerType>()) {
3979 calleePtr = EmitScalarExpr(E);
3980 functionType = ptrType->getPointeeType();
3982 functionType = E->getType();
3983 calleePtr = EmitLValue(E).getPointer();
3985 assert(functionType->isFunctionType());
3986 CGCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(),
3987 E->getReferencedDeclOfCallee());
3988 CGCallee callee(calleeInfo, calleePtr);
3992 LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
3993 // Comma expressions just emit their LHS then their RHS as an l-value.
3994 if (E->getOpcode() == BO_Comma) {
3995 EmitIgnoredExpr(E->getLHS());
3996 EnsureInsertPoint();
3997 return EmitLValue(E->getRHS());
4000 if (E->getOpcode() == BO_PtrMemD ||
4001 E->getOpcode() == BO_PtrMemI)
4002 return EmitPointerToDataMemberBinaryExpr(E);
4004 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
4006 // Note that in all of these cases, __block variables need the RHS
4007 // evaluated first just in case the variable gets moved by the RHS.
4009 switch (getEvaluationKind(E->getType())) {
4011 switch (E->getLHS()->getType().getObjCLifetime()) {
4012 case Qualifiers::OCL_Strong:
4013 return EmitARCStoreStrong(E, /*ignored*/ false).first;
4015 case Qualifiers::OCL_Autoreleasing:
4016 return EmitARCStoreAutoreleasing(E).first;
4018 // No reason to do any of these differently.
4019 case Qualifiers::OCL_None:
4020 case Qualifiers::OCL_ExplicitNone:
4021 case Qualifiers::OCL_Weak:
4025 RValue RV = EmitAnyExpr(E->getRHS());
4026 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
4027 EmitStoreThroughLValue(RV, LV);
4032 return EmitComplexAssignmentLValue(E);
4035 return EmitAggExprToLValue(E);
4037 llvm_unreachable("bad evaluation kind");
4040 LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
4041 RValue RV = EmitCallExpr(E);
4044 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
4045 AlignmentSource::Decl);
4047 assert(E->getCallReturnType(getContext())->isReferenceType() &&
4048 "Can't have a scalar return unless the return type is a "
4051 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
4054 LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
4055 // FIXME: This shouldn't require another copy.
4056 return EmitAggExprToLValue(E);
4059 LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
4060 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
4061 && "binding l-value to type which needs a temporary");
4062 AggValueSlot Slot = CreateAggTemp(E->getType());
4063 EmitCXXConstructExpr(E, Slot);
4064 return MakeAddrLValue(Slot.getAddress(), E->getType(),
4065 AlignmentSource::Decl);
4069 CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
4070 return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType());
4073 Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
4074 return Builder.CreateElementBitCast(CGM.GetAddrOfUuidDescriptor(E),
4075 ConvertType(E->getType()));
4078 LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
4079 return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(),
4080 AlignmentSource::Decl);
4084 CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
4085 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
4086 Slot.setExternallyDestructed();
4087 EmitAggExpr(E->getSubExpr(), Slot);
4088 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
4089 return MakeAddrLValue(Slot.getAddress(), E->getType(),
4090 AlignmentSource::Decl);
4094 CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
4095 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
4096 EmitLambdaExpr(E, Slot);
4097 return MakeAddrLValue(Slot.getAddress(), E->getType(),
4098 AlignmentSource::Decl);
4101 LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
4102 RValue RV = EmitObjCMessageExpr(E);
4105 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
4106 AlignmentSource::Decl);
4108 assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
4109 "Can't have a scalar return unless the return type is a "
4112 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
4115 LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
4117 CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
4118 return MakeAddrLValue(V, E->getType(), AlignmentSource::Decl);
4121 llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
4122 const ObjCIvarDecl *Ivar) {
4123 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
4126 LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
4127 llvm::Value *BaseValue,
4128 const ObjCIvarDecl *Ivar,
4129 unsigned CVRQualifiers) {
4130 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
4131 Ivar, CVRQualifiers);
4134 LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
4135 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
4136 llvm::Value *BaseValue = nullptr;
4137 const Expr *BaseExpr = E->getBase();
4138 Qualifiers BaseQuals;
4141 BaseValue = EmitScalarExpr(BaseExpr);
4142 ObjectTy = BaseExpr->getType()->getPointeeType();
4143 BaseQuals = ObjectTy.getQualifiers();
4145 LValue BaseLV = EmitLValue(BaseExpr);
4146 BaseValue = BaseLV.getPointer();
4147 ObjectTy = BaseExpr->getType();
4148 BaseQuals = ObjectTy.getQualifiers();
4152 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
4153 BaseQuals.getCVRQualifiers());
4154 setObjCGCLValueClass(getContext(), E, LV);
4158 LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
4159 // Can only get l-value for message expression returning aggregate type
4160 RValue RV = EmitAnyExprToTemp(E);
4161 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
4162 AlignmentSource::Decl);
4165 RValue CodeGenFunction::EmitCall(QualType CalleeType, const CGCallee &OrigCallee,
4166 const CallExpr *E, ReturnValueSlot ReturnValue,
4167 llvm::Value *Chain) {
4168 // Get the actual function type. The callee type will always be a pointer to
4169 // function type or a block pointer type.
4170 assert(CalleeType->isFunctionPointerType() &&
4171 "Call must have function pointer type!");
4173 const Decl *TargetDecl = OrigCallee.getAbstractInfo().getCalleeDecl();
4175 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
4176 // We can only guarantee that a function is called from the correct
4177 // context/function based on the appropriate target attributes,
4178 // so only check in the case where we have both always_inline and target
4179 // since otherwise we could be making a conditional call after a check for
4180 // the proper cpu features (and it won't cause code generation issues due to
4181 // function based code generation).
4182 if (TargetDecl->hasAttr<AlwaysInlineAttr>() &&
4183 TargetDecl->hasAttr<TargetAttr>())
4184 checkTargetFeatures(E, FD);
4186 CalleeType = getContext().getCanonicalType(CalleeType);
4188 const auto *FnType =
4189 cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
4191 CGCallee Callee = OrigCallee;
4193 if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
4194 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4195 if (llvm::Constant *PrefixSig =
4196 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
4197 SanitizerScope SanScope(this);
4198 llvm::Constant *FTRTTIConst =
4199 CGM.GetAddrOfRTTIDescriptor(QualType(FnType, 0), /*ForEH=*/true);
4200 llvm::Type *PrefixStructTyElems[] = {
4201 PrefixSig->getType(),
4202 FTRTTIConst->getType()
4204 llvm::StructType *PrefixStructTy = llvm::StructType::get(
4205 CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true);
4207 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4209 llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
4210 CalleePtr, llvm::PointerType::getUnqual(PrefixStructTy));
4211 llvm::Value *CalleeSigPtr =
4212 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0);
4213 llvm::Value *CalleeSig =
4214 Builder.CreateAlignedLoad(CalleeSigPtr, getIntAlign());
4215 llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
4217 llvm::BasicBlock *Cont = createBasicBlock("cont");
4218 llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
4219 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
4221 EmitBlock(TypeCheck);
4222 llvm::Value *CalleeRTTIPtr =
4223 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1);
4224 llvm::Value *CalleeRTTI =
4225 Builder.CreateAlignedLoad(CalleeRTTIPtr, getPointerAlign());
4226 llvm::Value *CalleeRTTIMatch =
4227 Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
4228 llvm::Constant *StaticData[] = {
4229 EmitCheckSourceLocation(E->getLocStart()),
4230 EmitCheckTypeDescriptor(CalleeType)
4232 EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
4233 SanitizerHandler::FunctionTypeMismatch, StaticData, CalleePtr);
4235 Builder.CreateBr(Cont);
4240 // If we are checking indirect calls and this call is indirect, check that the
4241 // function pointer is a member of the bit set for the function type.
4242 if (SanOpts.has(SanitizerKind::CFIICall) &&
4243 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4244 SanitizerScope SanScope(this);
4245 EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
4247 llvm::Metadata *MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0));
4248 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
4250 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4251 llvm::Value *CastedCallee = Builder.CreateBitCast(CalleePtr, Int8PtrTy);
4252 llvm::Value *TypeTest = Builder.CreateCall(
4253 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedCallee, TypeId});
4255 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
4256 llvm::Constant *StaticData[] = {
4257 llvm::ConstantInt::get(Int8Ty, CFITCK_ICall),
4258 EmitCheckSourceLocation(E->getLocStart()),
4259 EmitCheckTypeDescriptor(QualType(FnType, 0)),
4261 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
4262 EmitCfiSlowPathCheck(SanitizerKind::CFIICall, TypeTest, CrossDsoTypeId,
4263 CastedCallee, StaticData);
4265 EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIICall),
4266 SanitizerHandler::CFICheckFail, StaticData,
4267 {CastedCallee, llvm::UndefValue::get(IntPtrTy)});
4273 Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
4274 CGM.getContext().VoidPtrTy);
4276 // C++17 requires that we evaluate arguments to a call using assignment syntax
4277 // right-to-left, and that we evaluate arguments to certain other operators
4278 // left-to-right. Note that we allow this to override the order dictated by
4279 // the calling convention on the MS ABI, which means that parameter
4280 // destruction order is not necessarily reverse construction order.
4281 // FIXME: Revisit this based on C++ committee response to unimplementability.
4282 EvaluationOrder Order = EvaluationOrder::Default;
4283 if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
4284 if (OCE->isAssignmentOp())
4285 Order = EvaluationOrder::ForceRightToLeft;
4287 switch (OCE->getOperator()) {
4289 case OO_GreaterGreater:
4294 Order = EvaluationOrder::ForceLeftToRight;
4302 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(),
4303 E->getDirectCallee(), /*ParamsToSkip*/ 0, Order);
4305 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
4306 Args, FnType, /*isChainCall=*/Chain);
4309 // If the expression that denotes the called function has a type
4310 // that does not include a prototype, [the default argument
4311 // promotions are performed]. If the number of arguments does not
4312 // equal the number of parameters, the behavior is undefined. If
4313 // the function is defined with a type that includes a prototype,
4314 // and either the prototype ends with an ellipsis (, ...) or the
4315 // types of the arguments after promotion are not compatible with
4316 // the types of the parameters, the behavior is undefined. If the
4317 // function is defined with a type that does not include a
4318 // prototype, and the types of the arguments after promotion are
4319 // not compatible with those of the parameters after promotion,
4320 // the behavior is undefined [except in some trivial cases].
4321 // That is, in the general case, we should assume that a call
4322 // through an unprototyped function type works like a *non-variadic*
4323 // call. The way we make this work is to cast to the exact type
4324 // of the promoted arguments.
4326 // Chain calls use this same code path to add the invisible chain parameter
4327 // to the function type.
4328 if (isa<FunctionNoProtoType>(FnType) || Chain) {
4329 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
4330 CalleeTy = CalleeTy->getPointerTo();
4332 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4333 CalleePtr = Builder.CreateBitCast(CalleePtr, CalleeTy, "callee.knr.cast");
4334 Callee.setFunctionPointer(CalleePtr);
4337 return EmitCall(FnInfo, Callee, ReturnValue, Args);
4340 LValue CodeGenFunction::
4341 EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
4342 Address BaseAddr = Address::invalid();
4343 if (E->getOpcode() == BO_PtrMemI) {
4344 BaseAddr = EmitPointerWithAlignment(E->getLHS());
4346 BaseAddr = EmitLValue(E->getLHS()).getAddress();
4349 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
4351 const MemberPointerType *MPT
4352 = E->getRHS()->getType()->getAs<MemberPointerType>();
4354 AlignmentSource AlignSource;
4355 Address MemberAddr =
4356 EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT,
4359 return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), AlignSource);
4362 /// Given the address of a temporary variable, produce an r-value of
4364 RValue CodeGenFunction::convertTempToRValue(Address addr,
4366 SourceLocation loc) {
4367 LValue lvalue = MakeAddrLValue(addr, type, AlignmentSource::Decl);
4368 switch (getEvaluationKind(type)) {
4370 return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
4372 return lvalue.asAggregateRValue();
4374 return RValue::get(EmitLoadOfScalar(lvalue, loc));
4376 llvm_unreachable("bad evaluation kind");
4379 void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
4380 assert(Val->getType()->isFPOrFPVectorTy());
4381 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
4384 llvm::MDBuilder MDHelper(getLLVMContext());
4385 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
4387 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
4391 struct LValueOrRValue {
4397 static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
4398 const PseudoObjectExpr *E,
4400 AggValueSlot slot) {
4401 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
4403 // Find the result expression, if any.
4404 const Expr *resultExpr = E->getResultExpr();
4405 LValueOrRValue result;
4407 for (PseudoObjectExpr::const_semantics_iterator
4408 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
4409 const Expr *semantic = *i;
4411 // If this semantic expression is an opaque value, bind it
4412 // to the result of its source expression.
4413 if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
4415 // If this is the result expression, we may need to evaluate
4416 // directly into the slot.
4417 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
4419 if (ov == resultExpr && ov->isRValue() && !forLValue &&
4420 CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
4421 CGF.EmitAggExpr(ov->getSourceExpr(), slot);
4423 LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
4424 AlignmentSource::Decl);
4425 opaqueData = OVMA::bind(CGF, ov, LV);
4426 result.RV = slot.asRValue();
4428 // Otherwise, emit as normal.
4430 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
4432 // If this is the result, also evaluate the result now.
4433 if (ov == resultExpr) {
4435 result.LV = CGF.EmitLValue(ov);
4437 result.RV = CGF.EmitAnyExpr(ov, slot);
4441 opaques.push_back(opaqueData);
4443 // Otherwise, if the expression is the result, evaluate it
4444 // and remember the result.
4445 } else if (semantic == resultExpr) {
4447 result.LV = CGF.EmitLValue(semantic);
4449 result.RV = CGF.EmitAnyExpr(semantic, slot);
4451 // Otherwise, evaluate the expression in an ignored context.
4453 CGF.EmitIgnoredExpr(semantic);
4457 // Unbind all the opaques now.
4458 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
4459 opaques[i].unbind(CGF);
4464 RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
4465 AggValueSlot slot) {
4466 return emitPseudoObjectExpr(*this, E, false, slot).RV;
4469 LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
4470 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;