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 *CastAddr = Builder.CreateBitCast(Ptr, Int8PtrTy);
585 llvm::Value *LargeEnough =
586 Builder.CreateICmpUGE(Builder.CreateCall(F, {CastAddr, Min}),
587 llvm::ConstantInt::get(IntPtrTy, Size));
588 Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
591 uint64_t AlignVal = 0;
593 if (SanOpts.has(SanitizerKind::Alignment) &&
594 !SkippedChecks.has(SanitizerKind::Alignment)) {
595 AlignVal = Alignment.getQuantity();
596 if (!Ty->isIncompleteType() && !AlignVal)
597 AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity();
599 // The glvalue must be suitably aligned.
602 Builder.CreateAnd(Builder.CreatePtrToInt(Ptr, IntPtrTy),
603 llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
604 llvm::Value *Aligned =
605 Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
606 Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
610 if (Checks.size() > 0) {
611 // Make sure we're not losing information. Alignment needs to be a power of
613 assert(!AlignVal || (uint64_t)1 << llvm::Log2_64(AlignVal) == AlignVal);
614 llvm::Constant *StaticData[] = {
615 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(Ty),
616 llvm::ConstantInt::get(Int8Ty, AlignVal ? llvm::Log2_64(AlignVal) : 1),
617 llvm::ConstantInt::get(Int8Ty, TCK)};
618 EmitCheck(Checks, SanitizerHandler::TypeMismatch, StaticData, Ptr);
621 // If possible, check that the vptr indicates that there is a subobject of
622 // type Ty at offset zero within this object.
624 // C++11 [basic.life]p5,6:
625 // [For storage which does not refer to an object within its lifetime]
626 // The program has undefined behavior if:
627 // -- the [pointer or glvalue] is used to access a non-static data member
628 // or call a non-static member function
629 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
630 if (SanOpts.has(SanitizerKind::Vptr) &&
631 !SkippedChecks.has(SanitizerKind::Vptr) &&
632 (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
633 TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
634 TCK == TCK_UpcastToVirtualBase) &&
635 RD && RD->hasDefinition() && RD->isDynamicClass()) {
636 // Compute a hash of the mangled name of the type.
638 // FIXME: This is not guaranteed to be deterministic! Move to a
639 // fingerprinting mechanism once LLVM provides one. For the time
640 // being the implementation happens to be deterministic.
641 SmallString<64> MangledName;
642 llvm::raw_svector_ostream Out(MangledName);
643 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
646 // Blacklist based on the mangled type.
647 if (!CGM.getContext().getSanitizerBlacklist().isBlacklistedType(
649 llvm::hash_code TypeHash = hash_value(Out.str());
651 // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
652 llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
653 llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
654 Address VPtrAddr(Builder.CreateBitCast(Ptr, VPtrTy), getPointerAlign());
655 llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
656 llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
658 llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
659 Hash = Builder.CreateTrunc(Hash, IntPtrTy);
661 // Look the hash up in our cache.
662 const int CacheSize = 128;
663 llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
664 llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
665 "__ubsan_vptr_type_cache");
666 llvm::Value *Slot = Builder.CreateAnd(Hash,
667 llvm::ConstantInt::get(IntPtrTy,
669 llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
670 llvm::Value *CacheVal =
671 Builder.CreateAlignedLoad(Builder.CreateInBoundsGEP(Cache, Indices),
674 // If the hash isn't in the cache, call a runtime handler to perform the
675 // hard work of checking whether the vptr is for an object of the right
676 // type. This will either fill in the cache and return, or produce a
678 llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
679 llvm::Constant *StaticData[] = {
680 EmitCheckSourceLocation(Loc),
681 EmitCheckTypeDescriptor(Ty),
682 CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
683 llvm::ConstantInt::get(Int8Ty, TCK)
685 llvm::Value *DynamicData[] = { Ptr, Hash };
686 EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
687 SanitizerHandler::DynamicTypeCacheMiss, StaticData,
693 Builder.CreateBr(Done);
698 /// Determine whether this expression refers to a flexible array member in a
699 /// struct. We disable array bounds checks for such members.
700 static bool isFlexibleArrayMemberExpr(const Expr *E) {
701 // For compatibility with existing code, we treat arrays of length 0 or
702 // 1 as flexible array members.
703 const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe();
704 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
705 if (CAT->getSize().ugt(1))
707 } else if (!isa<IncompleteArrayType>(AT))
710 E = E->IgnoreParens();
712 // A flexible array member must be the last member in the class.
713 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
714 // FIXME: If the base type of the member expr is not FD->getParent(),
715 // this should not be treated as a flexible array member access.
716 if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
717 RecordDecl::field_iterator FI(
718 DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
719 return ++FI == FD->getParent()->field_end();
721 } else if (const auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) {
722 return IRE->getDecl()->getNextIvar() == nullptr;
728 /// If Base is known to point to the start of an array, return the length of
729 /// that array. Return 0 if the length cannot be determined.
730 static llvm::Value *getArrayIndexingBound(
731 CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType) {
732 // For the vector indexing extension, the bound is the number of elements.
733 if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
734 IndexedType = Base->getType();
735 return CGF.Builder.getInt32(VT->getNumElements());
738 Base = Base->IgnoreParens();
740 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
741 if (CE->getCastKind() == CK_ArrayToPointerDecay &&
742 !isFlexibleArrayMemberExpr(CE->getSubExpr())) {
743 IndexedType = CE->getSubExpr()->getType();
744 const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
745 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
746 return CGF.Builder.getInt(CAT->getSize());
747 else if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
748 return CGF.getVLASize(VAT).first;
755 void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
756 llvm::Value *Index, QualType IndexType,
758 assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
759 "should not be called unless adding bounds checks");
760 SanitizerScope SanScope(this);
762 QualType IndexedType;
763 llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType);
767 bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
768 llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
769 llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
771 llvm::Constant *StaticData[] = {
772 EmitCheckSourceLocation(E->getExprLoc()),
773 EmitCheckTypeDescriptor(IndexedType),
774 EmitCheckTypeDescriptor(IndexType)
776 llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
777 : Builder.CreateICmpULE(IndexVal, BoundVal);
778 EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds),
779 SanitizerHandler::OutOfBounds, StaticData, Index);
783 CodeGenFunction::ComplexPairTy CodeGenFunction::
784 EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
785 bool isInc, bool isPre) {
786 ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
788 llvm::Value *NextVal;
789 if (isa<llvm::IntegerType>(InVal.first->getType())) {
790 uint64_t AmountVal = isInc ? 1 : -1;
791 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
793 // Add the inc/dec to the real part.
794 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
796 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
797 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
800 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
802 // Add the inc/dec to the real part.
803 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
806 ComplexPairTy IncVal(NextVal, InVal.second);
808 // Store the updated result through the lvalue.
809 EmitStoreOfComplex(IncVal, LV, /*init*/ false);
811 // If this is a postinc, return the value read from memory, otherwise use the
813 return isPre ? IncVal : InVal;
816 void CodeGenModule::EmitExplicitCastExprType(const ExplicitCastExpr *E,
817 CodeGenFunction *CGF) {
818 // Bind VLAs in the cast type.
819 if (CGF && E->getType()->isVariablyModifiedType())
820 CGF->EmitVariablyModifiedType(E->getType());
822 if (CGDebugInfo *DI = getModuleDebugInfo())
823 DI->EmitExplicitCastType(E->getType());
826 //===----------------------------------------------------------------------===//
827 // LValue Expression Emission
828 //===----------------------------------------------------------------------===//
830 /// EmitPointerWithAlignment - Given an expression of pointer type, try to
831 /// derive a more accurate bound on the alignment of the pointer.
832 Address CodeGenFunction::EmitPointerWithAlignment(const Expr *E,
833 AlignmentSource *Source) {
834 // We allow this with ObjC object pointers because of fragile ABIs.
835 assert(E->getType()->isPointerType() ||
836 E->getType()->isObjCObjectPointerType());
837 E = E->IgnoreParens();
840 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
841 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
842 CGM.EmitExplicitCastExprType(ECE, this);
844 switch (CE->getCastKind()) {
845 // Non-converting casts (but not C's implicit conversion from void*).
848 if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) {
849 if (PtrTy->getPointeeType()->isVoidType())
852 AlignmentSource InnerSource;
853 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), &InnerSource);
854 if (Source) *Source = InnerSource;
856 // If this is an explicit bitcast, and the source l-value is
857 // opaque, honor the alignment of the casted-to type.
858 if (isa<ExplicitCastExpr>(CE) &&
859 InnerSource != AlignmentSource::Decl) {
860 Addr = Address(Addr.getPointer(),
861 getNaturalPointeeTypeAlignment(E->getType(), Source));
864 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast) &&
865 CE->getCastKind() == CK_BitCast) {
866 if (auto PT = E->getType()->getAs<PointerType>())
867 EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr.getPointer(),
869 CodeGenFunction::CFITCK_UnrelatedCast,
873 return Builder.CreateBitCast(Addr, ConvertType(E->getType()));
877 // Array-to-pointer decay.
878 case CK_ArrayToPointerDecay:
879 return EmitArrayToPointerDecay(CE->getSubExpr(), Source);
881 // Derived-to-base conversions.
882 case CK_UncheckedDerivedToBase:
883 case CK_DerivedToBase: {
884 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), Source);
885 auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
886 return GetAddressOfBaseClass(Addr, Derived,
887 CE->path_begin(), CE->path_end(),
888 ShouldNullCheckClassCastValue(CE),
892 // TODO: Is there any reason to treat base-to-derived conversions
900 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
901 if (UO->getOpcode() == UO_AddrOf) {
902 LValue LV = EmitLValue(UO->getSubExpr());
903 if (Source) *Source = LV.getAlignmentSource();
904 return LV.getAddress();
908 // TODO: conditional operators, comma.
910 // Otherwise, use the alignment of the type.
911 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(), Source);
912 return Address(EmitScalarExpr(E), Align);
915 RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
916 if (Ty->isVoidType())
917 return RValue::get(nullptr);
919 switch (getEvaluationKind(Ty)) {
922 ConvertType(Ty->castAs<ComplexType>()->getElementType());
923 llvm::Value *U = llvm::UndefValue::get(EltTy);
924 return RValue::getComplex(std::make_pair(U, U));
927 // If this is a use of an undefined aggregate type, the aggregate must have an
928 // identifiable address. Just because the contents of the value are undefined
929 // doesn't mean that the address can't be taken and compared.
930 case TEK_Aggregate: {
931 Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
932 return RValue::getAggregate(DestPtr);
936 return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
938 llvm_unreachable("bad evaluation kind");
941 RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
943 ErrorUnsupported(E, Name);
944 return GetUndefRValue(E->getType());
947 LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
949 ErrorUnsupported(E, Name);
950 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
951 return MakeAddrLValue(Address(llvm::UndefValue::get(Ty), CharUnits::One()),
955 LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
957 if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
958 LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
961 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple())
962 EmitTypeCheck(TCK, E->getExprLoc(), LV.getPointer(),
963 E->getType(), LV.getAlignment());
967 /// EmitLValue - Emit code to compute a designator that specifies the location
968 /// of the expression.
970 /// This can return one of two things: a simple address or a bitfield reference.
971 /// In either case, the LLVM Value* in the LValue structure is guaranteed to be
972 /// an LLVM pointer type.
974 /// If this returns a bitfield reference, nothing about the pointee type of the
975 /// LLVM value is known: For example, it may not be a pointer to an integer.
977 /// If this returns a normal address, and if the lvalue's C type is fixed size,
978 /// this method guarantees that the returned pointer type will point to an LLVM
979 /// type of the same size of the lvalue's type. If the lvalue has a variable
980 /// length type, this is not possible.
982 LValue CodeGenFunction::EmitLValue(const Expr *E) {
983 ApplyDebugLocation DL(*this, E);
984 switch (E->getStmtClass()) {
985 default: return EmitUnsupportedLValue(E, "l-value expression");
987 case Expr::ObjCPropertyRefExprClass:
988 llvm_unreachable("cannot emit a property reference directly");
990 case Expr::ObjCSelectorExprClass:
991 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
992 case Expr::ObjCIsaExprClass:
993 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
994 case Expr::BinaryOperatorClass:
995 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
996 case Expr::CompoundAssignOperatorClass: {
997 QualType Ty = E->getType();
998 if (const AtomicType *AT = Ty->getAs<AtomicType>())
999 Ty = AT->getValueType();
1000 if (!Ty->isAnyComplexType())
1001 return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
1002 return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
1004 case Expr::CallExprClass:
1005 case Expr::CXXMemberCallExprClass:
1006 case Expr::CXXOperatorCallExprClass:
1007 case Expr::UserDefinedLiteralClass:
1008 return EmitCallExprLValue(cast<CallExpr>(E));
1009 case Expr::VAArgExprClass:
1010 return EmitVAArgExprLValue(cast<VAArgExpr>(E));
1011 case Expr::DeclRefExprClass:
1012 return EmitDeclRefLValue(cast<DeclRefExpr>(E));
1013 case Expr::ParenExprClass:
1014 return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
1015 case Expr::GenericSelectionExprClass:
1016 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
1017 case Expr::PredefinedExprClass:
1018 return EmitPredefinedLValue(cast<PredefinedExpr>(E));
1019 case Expr::StringLiteralClass:
1020 return EmitStringLiteralLValue(cast<StringLiteral>(E));
1021 case Expr::ObjCEncodeExprClass:
1022 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
1023 case Expr::PseudoObjectExprClass:
1024 return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
1025 case Expr::InitListExprClass:
1026 return EmitInitListLValue(cast<InitListExpr>(E));
1027 case Expr::CXXTemporaryObjectExprClass:
1028 case Expr::CXXConstructExprClass:
1029 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
1030 case Expr::CXXBindTemporaryExprClass:
1031 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
1032 case Expr::CXXUuidofExprClass:
1033 return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
1034 case Expr::LambdaExprClass:
1035 return EmitLambdaLValue(cast<LambdaExpr>(E));
1037 case Expr::ExprWithCleanupsClass: {
1038 const auto *cleanups = cast<ExprWithCleanups>(E);
1039 enterFullExpression(cleanups);
1040 RunCleanupsScope Scope(*this);
1041 return EmitLValue(cleanups->getSubExpr());
1044 case Expr::CXXDefaultArgExprClass:
1045 return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
1046 case Expr::CXXDefaultInitExprClass: {
1047 CXXDefaultInitExprScope Scope(*this);
1048 return EmitLValue(cast<CXXDefaultInitExpr>(E)->getExpr());
1050 case Expr::CXXTypeidExprClass:
1051 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
1053 case Expr::ObjCMessageExprClass:
1054 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
1055 case Expr::ObjCIvarRefExprClass:
1056 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
1057 case Expr::StmtExprClass:
1058 return EmitStmtExprLValue(cast<StmtExpr>(E));
1059 case Expr::UnaryOperatorClass:
1060 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
1061 case Expr::ArraySubscriptExprClass:
1062 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
1063 case Expr::OMPArraySectionExprClass:
1064 return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E));
1065 case Expr::ExtVectorElementExprClass:
1066 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
1067 case Expr::MemberExprClass:
1068 return EmitMemberExpr(cast<MemberExpr>(E));
1069 case Expr::CompoundLiteralExprClass:
1070 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
1071 case Expr::ConditionalOperatorClass:
1072 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
1073 case Expr::BinaryConditionalOperatorClass:
1074 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
1075 case Expr::ChooseExprClass:
1076 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr());
1077 case Expr::OpaqueValueExprClass:
1078 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
1079 case Expr::SubstNonTypeTemplateParmExprClass:
1080 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
1081 case Expr::ImplicitCastExprClass:
1082 case Expr::CStyleCastExprClass:
1083 case Expr::CXXFunctionalCastExprClass:
1084 case Expr::CXXStaticCastExprClass:
1085 case Expr::CXXDynamicCastExprClass:
1086 case Expr::CXXReinterpretCastExprClass:
1087 case Expr::CXXConstCastExprClass:
1088 case Expr::ObjCBridgedCastExprClass:
1089 return EmitCastLValue(cast<CastExpr>(E));
1091 case Expr::MaterializeTemporaryExprClass:
1092 return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
1096 /// Given an object of the given canonical type, can we safely copy a
1097 /// value out of it based on its initializer?
1098 static bool isConstantEmittableObjectType(QualType type) {
1099 assert(type.isCanonical());
1100 assert(!type->isReferenceType());
1102 // Must be const-qualified but non-volatile.
1103 Qualifiers qs = type.getLocalQualifiers();
1104 if (!qs.hasConst() || qs.hasVolatile()) return false;
1106 // Otherwise, all object types satisfy this except C++ classes with
1107 // mutable subobjects or non-trivial copy/destroy behavior.
1108 if (const auto *RT = dyn_cast<RecordType>(type))
1109 if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
1110 if (RD->hasMutableFields() || !RD->isTrivial())
1116 /// Can we constant-emit a load of a reference to a variable of the
1117 /// given type? This is different from predicates like
1118 /// Decl::isUsableInConstantExpressions because we do want it to apply
1119 /// in situations that don't necessarily satisfy the language's rules
1120 /// for this (e.g. C++'s ODR-use rules). For example, we want to able
1121 /// to do this with const float variables even if those variables
1122 /// aren't marked 'constexpr'.
1123 enum ConstantEmissionKind {
1125 CEK_AsReferenceOnly,
1126 CEK_AsValueOrReference,
1129 static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
1130 type = type.getCanonicalType();
1131 if (const auto *ref = dyn_cast<ReferenceType>(type)) {
1132 if (isConstantEmittableObjectType(ref->getPointeeType()))
1133 return CEK_AsValueOrReference;
1134 return CEK_AsReferenceOnly;
1136 if (isConstantEmittableObjectType(type))
1137 return CEK_AsValueOnly;
1141 /// Try to emit a reference to the given value without producing it as
1142 /// an l-value. This is actually more than an optimization: we can't
1143 /// produce an l-value for variables that we never actually captured
1144 /// in a block or lambda, which means const int variables or constexpr
1145 /// literals or similar.
1146 CodeGenFunction::ConstantEmission
1147 CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
1148 ValueDecl *value = refExpr->getDecl();
1150 // The value needs to be an enum constant or a constant variable.
1151 ConstantEmissionKind CEK;
1152 if (isa<ParmVarDecl>(value)) {
1154 } else if (auto *var = dyn_cast<VarDecl>(value)) {
1155 CEK = checkVarTypeForConstantEmission(var->getType());
1156 } else if (isa<EnumConstantDecl>(value)) {
1157 CEK = CEK_AsValueOnly;
1161 if (CEK == CEK_None) return ConstantEmission();
1163 Expr::EvalResult result;
1164 bool resultIsReference;
1165 QualType resultType;
1167 // It's best to evaluate all the way as an r-value if that's permitted.
1168 if (CEK != CEK_AsReferenceOnly &&
1169 refExpr->EvaluateAsRValue(result, getContext())) {
1170 resultIsReference = false;
1171 resultType = refExpr->getType();
1173 // Otherwise, try to evaluate as an l-value.
1174 } else if (CEK != CEK_AsValueOnly &&
1175 refExpr->EvaluateAsLValue(result, getContext())) {
1176 resultIsReference = true;
1177 resultType = value->getType();
1181 return ConstantEmission();
1184 // In any case, if the initializer has side-effects, abandon ship.
1185 if (result.HasSideEffects)
1186 return ConstantEmission();
1188 // Emit as a constant.
1189 llvm::Constant *C = CGM.EmitConstantValue(result.Val, resultType, this);
1191 // Make sure we emit a debug reference to the global variable.
1192 // This should probably fire even for
1193 if (isa<VarDecl>(value)) {
1194 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
1195 EmitDeclRefExprDbgValue(refExpr, result.Val);
1197 assert(isa<EnumConstantDecl>(value));
1198 EmitDeclRefExprDbgValue(refExpr, result.Val);
1201 // If we emitted a reference constant, we need to dereference that.
1202 if (resultIsReference)
1203 return ConstantEmission::forReference(C);
1205 return ConstantEmission::forValue(C);
1208 llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
1209 SourceLocation Loc) {
1210 return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
1211 lvalue.getType(), Loc, lvalue.getAlignmentSource(),
1212 lvalue.getTBAAInfo(),
1213 lvalue.getTBAABaseType(), lvalue.getTBAAOffset(),
1214 lvalue.isNontemporal());
1217 static bool hasBooleanRepresentation(QualType Ty) {
1218 if (Ty->isBooleanType())
1221 if (const EnumType *ET = Ty->getAs<EnumType>())
1222 return ET->getDecl()->getIntegerType()->isBooleanType();
1224 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1225 return hasBooleanRepresentation(AT->getValueType());
1230 static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
1231 llvm::APInt &Min, llvm::APInt &End,
1232 bool StrictEnums, bool IsBool) {
1233 const EnumType *ET = Ty->getAs<EnumType>();
1234 bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
1235 ET && !ET->getDecl()->isFixed();
1236 if (!IsBool && !IsRegularCPlusPlusEnum)
1240 Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
1241 End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
1243 const EnumDecl *ED = ET->getDecl();
1244 llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
1245 unsigned Bitwidth = LTy->getScalarSizeInBits();
1246 unsigned NumNegativeBits = ED->getNumNegativeBits();
1247 unsigned NumPositiveBits = ED->getNumPositiveBits();
1249 if (NumNegativeBits) {
1250 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
1251 assert(NumBits <= Bitwidth);
1252 End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
1255 assert(NumPositiveBits <= Bitwidth);
1256 End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
1257 Min = llvm::APInt(Bitwidth, 0);
1263 llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
1264 llvm::APInt Min, End;
1265 if (!getRangeForType(*this, Ty, Min, End, CGM.getCodeGenOpts().StrictEnums,
1266 hasBooleanRepresentation(Ty)))
1269 llvm::MDBuilder MDHelper(getLLVMContext());
1270 return MDHelper.createRange(Min, End);
1273 llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile,
1276 AlignmentSource AlignSource,
1277 llvm::MDNode *TBAAInfo,
1278 QualType TBAABaseType,
1279 uint64_t TBAAOffset,
1280 bool isNontemporal) {
1281 // For better performance, handle vector loads differently.
1282 if (Ty->isVectorType()) {
1283 const llvm::Type *EltTy = Addr.getElementType();
1285 const auto *VTy = cast<llvm::VectorType>(EltTy);
1287 // Handle vectors of size 3 like size 4 for better performance.
1288 if (VTy->getNumElements() == 3) {
1290 // Bitcast to vec4 type.
1291 llvm::VectorType *vec4Ty = llvm::VectorType::get(VTy->getElementType(),
1293 Address Cast = Builder.CreateElementBitCast(Addr, vec4Ty, "castToVec4");
1295 llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4");
1297 // Shuffle vector to get vec3.
1298 V = Builder.CreateShuffleVector(V, llvm::UndefValue::get(vec4Ty),
1299 {0, 1, 2}, "extractVec");
1300 return EmitFromMemory(V, Ty);
1304 // Atomic operations have to be done on integral types.
1305 LValue AtomicLValue =
1306 LValue::MakeAddr(Addr, Ty, getContext(), AlignSource, TBAAInfo);
1307 if (Ty->isAtomicType() || LValueIsSuitableForInlineAtomic(AtomicLValue)) {
1308 return EmitAtomicLoad(AtomicLValue, Loc).getScalarVal();
1311 llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
1312 if (isNontemporal) {
1313 llvm::MDNode *Node = llvm::MDNode::get(
1314 Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1315 Load->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1318 llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
1321 CGM.DecorateInstructionWithTBAA(Load, TBAAPath,
1322 false /*ConvertTypeToTag*/);
1325 bool IsBool = hasBooleanRepresentation(Ty) ||
1326 NSAPI(CGM.getContext()).isObjCBOOLType(Ty);
1327 bool NeedsBoolCheck = SanOpts.has(SanitizerKind::Bool) && IsBool;
1328 bool NeedsEnumCheck =
1329 SanOpts.has(SanitizerKind::Enum) && Ty->getAs<EnumType>();
1330 if (NeedsBoolCheck || NeedsEnumCheck) {
1331 SanitizerScope SanScope(this);
1332 llvm::APInt Min, End;
1333 if (getRangeForType(*this, Ty, Min, End, /*StrictEnums=*/true, IsBool)) {
1337 Check = Builder.CreateICmpULE(
1338 Load, llvm::ConstantInt::get(getLLVMContext(), End));
1340 llvm::Value *Upper = Builder.CreateICmpSLE(
1341 Load, llvm::ConstantInt::get(getLLVMContext(), End));
1342 llvm::Value *Lower = Builder.CreateICmpSGE(
1343 Load, llvm::ConstantInt::get(getLLVMContext(), Min));
1344 Check = Builder.CreateAnd(Upper, Lower);
1346 llvm::Constant *StaticArgs[] = {
1347 EmitCheckSourceLocation(Loc),
1348 EmitCheckTypeDescriptor(Ty)
1350 SanitizerMask Kind = NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
1351 EmitCheck(std::make_pair(Check, Kind), SanitizerHandler::LoadInvalidValue,
1352 StaticArgs, EmitCheckValue(Load));
1354 } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
1355 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
1356 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
1358 return EmitFromMemory(Load, Ty);
1361 llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
1362 // Bool has a different representation in memory than in registers.
1363 if (hasBooleanRepresentation(Ty)) {
1364 // This should really always be an i1, but sometimes it's already
1365 // an i8, and it's awkward to track those cases down.
1366 if (Value->getType()->isIntegerTy(1))
1367 return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
1368 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1369 "wrong value rep of bool");
1375 llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
1376 // Bool has a different representation in memory than in registers.
1377 if (hasBooleanRepresentation(Ty)) {
1378 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1379 "wrong value rep of bool");
1380 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
1386 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr,
1387 bool Volatile, QualType Ty,
1388 AlignmentSource AlignSource,
1389 llvm::MDNode *TBAAInfo,
1390 bool isInit, QualType TBAABaseType,
1391 uint64_t TBAAOffset,
1392 bool isNontemporal) {
1394 // Handle vectors differently to get better performance.
1395 if (Ty->isVectorType()) {
1396 llvm::Type *SrcTy = Value->getType();
1397 auto *VecTy = cast<llvm::VectorType>(SrcTy);
1398 // Handle vec3 special.
1399 if (VecTy->getNumElements() == 3) {
1400 // Our source is a vec3, do a shuffle vector to make it a vec4.
1401 llvm::Constant *Mask[] = {Builder.getInt32(0), Builder.getInt32(1),
1402 Builder.getInt32(2),
1403 llvm::UndefValue::get(Builder.getInt32Ty())};
1404 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1405 Value = Builder.CreateShuffleVector(Value,
1406 llvm::UndefValue::get(VecTy),
1407 MaskV, "extractVec");
1408 SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
1410 if (Addr.getElementType() != SrcTy) {
1411 Addr = Builder.CreateElementBitCast(Addr, SrcTy, "storetmp");
1415 Value = EmitToMemory(Value, Ty);
1417 LValue AtomicLValue =
1418 LValue::MakeAddr(Addr, Ty, getContext(), AlignSource, TBAAInfo);
1419 if (Ty->isAtomicType() ||
1420 (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) {
1421 EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit);
1425 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
1426 if (isNontemporal) {
1427 llvm::MDNode *Node =
1428 llvm::MDNode::get(Store->getContext(),
1429 llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1430 Store->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1433 llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
1436 CGM.DecorateInstructionWithTBAA(Store, TBAAPath,
1437 false /*ConvertTypeToTag*/);
1441 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
1443 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
1444 lvalue.getType(), lvalue.getAlignmentSource(),
1445 lvalue.getTBAAInfo(), isInit, lvalue.getTBAABaseType(),
1446 lvalue.getTBAAOffset(), lvalue.isNontemporal());
1449 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1450 /// method emits the address of the lvalue, then loads the result as an rvalue,
1451 /// returning the rvalue.
1452 RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
1453 if (LV.isObjCWeak()) {
1454 // load of a __weak object.
1455 Address AddrWeakObj = LV.getAddress();
1456 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1459 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
1460 // In MRC mode, we do a load+autorelease.
1461 if (!getLangOpts().ObjCAutoRefCount) {
1462 return RValue::get(EmitARCLoadWeak(LV.getAddress()));
1465 // In ARC mode, we load retained and then consume the value.
1466 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
1467 Object = EmitObjCConsumeObject(LV.getType(), Object);
1468 return RValue::get(Object);
1471 if (LV.isSimple()) {
1472 assert(!LV.getType()->isFunctionType());
1474 // Everything needs a load.
1475 return RValue::get(EmitLoadOfScalar(LV, Loc));
1478 if (LV.isVectorElt()) {
1479 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
1480 LV.isVolatileQualified());
1481 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
1485 // If this is a reference to a subset of the elements of a vector, either
1486 // shuffle the input or extract/insert them as appropriate.
1487 if (LV.isExtVectorElt())
1488 return EmitLoadOfExtVectorElementLValue(LV);
1490 // Global Register variables always invoke intrinsics
1491 if (LV.isGlobalReg())
1492 return EmitLoadOfGlobalRegLValue(LV);
1494 assert(LV.isBitField() && "Unknown LValue type!");
1495 return EmitLoadOfBitfieldLValue(LV);
1498 RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV) {
1499 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
1501 // Get the output type.
1502 llvm::Type *ResLTy = ConvertType(LV.getType());
1504 Address Ptr = LV.getBitFieldAddress();
1505 llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
1507 if (Info.IsSigned) {
1508 assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
1509 unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
1511 Val = Builder.CreateShl(Val, HighBits, "bf.shl");
1512 if (Info.Offset + HighBits)
1513 Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
1516 Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
1517 if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
1518 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
1522 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
1524 return RValue::get(Val);
1527 // If this is a reference to a subset of the elements of a vector, create an
1528 // appropriate shufflevector.
1529 RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
1530 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
1531 LV.isVolatileQualified());
1533 const llvm::Constant *Elts = LV.getExtVectorElts();
1535 // If the result of the expression is a non-vector type, we must be extracting
1536 // a single element. Just codegen as an extractelement.
1537 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1539 unsigned InIdx = getAccessedFieldNo(0, Elts);
1540 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
1541 return RValue::get(Builder.CreateExtractElement(Vec, Elt));
1544 // Always use shuffle vector to try to retain the original program structure
1545 unsigned NumResultElts = ExprVT->getNumElements();
1547 SmallVector<llvm::Constant*, 4> Mask;
1548 for (unsigned i = 0; i != NumResultElts; ++i)
1549 Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
1551 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1552 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
1554 return RValue::get(Vec);
1557 /// @brief Generates lvalue for partial ext_vector access.
1558 Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
1559 Address VectorAddress = LV.getExtVectorAddress();
1560 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1561 QualType EQT = ExprVT->getElementType();
1562 llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
1564 Address CastToPointerElement =
1565 Builder.CreateElementBitCast(VectorAddress, VectorElementTy,
1566 "conv.ptr.element");
1568 const llvm::Constant *Elts = LV.getExtVectorElts();
1569 unsigned ix = getAccessedFieldNo(0, Elts);
1571 Address VectorBasePtrPlusIx =
1572 Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
1573 getContext().getTypeSizeInChars(EQT),
1576 return VectorBasePtrPlusIx;
1579 /// @brief Load of global gamed gegisters are always calls to intrinsics.
1580 RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
1581 assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
1582 "Bad type for register variable");
1583 llvm::MDNode *RegName = cast<llvm::MDNode>(
1584 cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
1586 // We accept integer and pointer types only
1587 llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
1588 llvm::Type *Ty = OrigTy;
1589 if (OrigTy->isPointerTy())
1590 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1591 llvm::Type *Types[] = { Ty };
1593 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
1594 llvm::Value *Call = Builder.CreateCall(
1595 F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
1596 if (OrigTy->isPointerTy())
1597 Call = Builder.CreateIntToPtr(Call, OrigTy);
1598 return RValue::get(Call);
1602 /// EmitStoreThroughLValue - Store the specified rvalue into the specified
1603 /// lvalue, where both are guaranteed to the have the same type, and that type
1605 void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
1607 if (!Dst.isSimple()) {
1608 if (Dst.isVectorElt()) {
1609 // Read/modify/write the vector, inserting the new element.
1610 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
1611 Dst.isVolatileQualified());
1612 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
1613 Dst.getVectorIdx(), "vecins");
1614 Builder.CreateStore(Vec, Dst.getVectorAddress(),
1615 Dst.isVolatileQualified());
1619 // If this is an update of extended vector elements, insert them as
1621 if (Dst.isExtVectorElt())
1622 return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
1624 if (Dst.isGlobalReg())
1625 return EmitStoreThroughGlobalRegLValue(Src, Dst);
1627 assert(Dst.isBitField() && "Unknown LValue type");
1628 return EmitStoreThroughBitfieldLValue(Src, Dst);
1631 // There's special magic for assigning into an ARC-qualified l-value.
1632 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
1634 case Qualifiers::OCL_None:
1635 llvm_unreachable("present but none");
1637 case Qualifiers::OCL_ExplicitNone:
1641 case Qualifiers::OCL_Strong:
1643 Src = RValue::get(EmitARCRetain(Dst.getType(), Src.getScalarVal()));
1646 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
1649 case Qualifiers::OCL_Weak:
1651 // Initialize and then skip the primitive store.
1652 EmitARCInitWeak(Dst.getAddress(), Src.getScalarVal());
1654 EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
1657 case Qualifiers::OCL_Autoreleasing:
1658 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
1659 Src.getScalarVal()));
1660 // fall into the normal path
1665 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
1666 // load of a __weak object.
1667 Address LvalueDst = Dst.getAddress();
1668 llvm::Value *src = Src.getScalarVal();
1669 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
1673 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
1674 // load of a __strong object.
1675 Address LvalueDst = Dst.getAddress();
1676 llvm::Value *src = Src.getScalarVal();
1677 if (Dst.isObjCIvar()) {
1678 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
1679 llvm::Type *ResultType = IntPtrTy;
1680 Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp());
1681 llvm::Value *RHS = dst.getPointer();
1682 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1684 Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType,
1685 "sub.ptr.lhs.cast");
1686 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
1687 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
1689 } else if (Dst.isGlobalObjCRef()) {
1690 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
1691 Dst.isThreadLocalRef());
1694 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
1698 assert(Src.isScalar() && "Can't emit an agg store with this method");
1699 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
1702 void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
1703 llvm::Value **Result) {
1704 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
1705 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
1706 Address Ptr = Dst.getBitFieldAddress();
1708 // Get the source value, truncated to the width of the bit-field.
1709 llvm::Value *SrcVal = Src.getScalarVal();
1711 // Cast the source to the storage type and shift it into place.
1712 SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
1713 /*IsSigned=*/false);
1714 llvm::Value *MaskedVal = SrcVal;
1716 // See if there are other bits in the bitfield's storage we'll need to load
1717 // and mask together with source before storing.
1718 if (Info.StorageSize != Info.Size) {
1719 assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
1721 Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
1723 // Mask the source value as needed.
1724 if (!hasBooleanRepresentation(Dst.getType()))
1725 SrcVal = Builder.CreateAnd(SrcVal,
1726 llvm::APInt::getLowBitsSet(Info.StorageSize,
1731 SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
1733 // Mask out the original value.
1734 Val = Builder.CreateAnd(Val,
1735 ~llvm::APInt::getBitsSet(Info.StorageSize,
1737 Info.Offset + Info.Size),
1740 // Or together the unchanged values and the source value.
1741 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
1743 assert(Info.Offset == 0);
1746 // Write the new value back out.
1747 Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
1749 // Return the new value of the bit-field, if requested.
1751 llvm::Value *ResultVal = MaskedVal;
1753 // Sign extend the value if needed.
1754 if (Info.IsSigned) {
1755 assert(Info.Size <= Info.StorageSize);
1756 unsigned HighBits = Info.StorageSize - Info.Size;
1758 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
1759 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
1763 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
1765 *Result = EmitFromMemory(ResultVal, Dst.getType());
1769 void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
1771 // This access turns into a read/modify/write of the vector. Load the input
1773 llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(),
1774 Dst.isVolatileQualified());
1775 const llvm::Constant *Elts = Dst.getExtVectorElts();
1777 llvm::Value *SrcVal = Src.getScalarVal();
1779 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
1780 unsigned NumSrcElts = VTy->getNumElements();
1781 unsigned NumDstElts = Vec->getType()->getVectorNumElements();
1782 if (NumDstElts == NumSrcElts) {
1783 // Use shuffle vector is the src and destination are the same number of
1784 // elements and restore the vector mask since it is on the side it will be
1786 SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
1787 for (unsigned i = 0; i != NumSrcElts; ++i)
1788 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
1790 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1791 Vec = Builder.CreateShuffleVector(SrcVal,
1792 llvm::UndefValue::get(Vec->getType()),
1794 } else if (NumDstElts > NumSrcElts) {
1795 // Extended the source vector to the same length and then shuffle it
1796 // into the destination.
1797 // FIXME: since we're shuffling with undef, can we just use the indices
1798 // into that? This could be simpler.
1799 SmallVector<llvm::Constant*, 4> ExtMask;
1800 for (unsigned i = 0; i != NumSrcElts; ++i)
1801 ExtMask.push_back(Builder.getInt32(i));
1802 ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
1803 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
1804 llvm::Value *ExtSrcVal =
1805 Builder.CreateShuffleVector(SrcVal,
1806 llvm::UndefValue::get(SrcVal->getType()),
1809 SmallVector<llvm::Constant*, 4> Mask;
1810 for (unsigned i = 0; i != NumDstElts; ++i)
1811 Mask.push_back(Builder.getInt32(i));
1813 // When the vector size is odd and .odd or .hi is used, the last element
1814 // of the Elts constant array will be one past the size of the vector.
1815 // Ignore the last element here, if it is greater than the mask size.
1816 if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
1819 // modify when what gets shuffled in
1820 for (unsigned i = 0; i != NumSrcElts; ++i)
1821 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
1822 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1823 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
1825 // We should never shorten the vector
1826 llvm_unreachable("unexpected shorten vector length");
1829 // If the Src is a scalar (not a vector) it must be updating one element.
1830 unsigned InIdx = getAccessedFieldNo(0, Elts);
1831 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
1832 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
1835 Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
1836 Dst.isVolatileQualified());
1839 /// @brief Store of global named registers are always calls to intrinsics.
1840 void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
1841 assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
1842 "Bad type for register variable");
1843 llvm::MDNode *RegName = cast<llvm::MDNode>(
1844 cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
1845 assert(RegName && "Register LValue is not metadata");
1847 // We accept integer and pointer types only
1848 llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
1849 llvm::Type *Ty = OrigTy;
1850 if (OrigTy->isPointerTy())
1851 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1852 llvm::Type *Types[] = { Ty };
1854 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
1855 llvm::Value *Value = Src.getScalarVal();
1856 if (OrigTy->isPointerTy())
1857 Value = Builder.CreatePtrToInt(Value, Ty);
1859 F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
1862 // setObjCGCLValueClass - sets class of the lvalue for the purpose of
1863 // generating write-barries API. It is currently a global, ivar,
1865 static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
1867 bool IsMemberAccess=false) {
1868 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
1871 if (isa<ObjCIvarRefExpr>(E)) {
1872 QualType ExpTy = E->getType();
1873 if (IsMemberAccess && ExpTy->isPointerType()) {
1874 // If ivar is a structure pointer, assigning to field of
1875 // this struct follows gcc's behavior and makes it a non-ivar
1876 // writer-barrier conservatively.
1877 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1878 if (ExpTy->isRecordType()) {
1879 LV.setObjCIvar(false);
1883 LV.setObjCIvar(true);
1884 auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
1885 LV.setBaseIvarExp(Exp->getBase());
1886 LV.setObjCArray(E->getType()->isArrayType());
1890 if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
1891 if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
1892 if (VD->hasGlobalStorage()) {
1893 LV.setGlobalObjCRef(true);
1894 LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
1897 LV.setObjCArray(E->getType()->isArrayType());
1901 if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
1902 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
1906 if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
1907 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
1908 if (LV.isObjCIvar()) {
1909 // If cast is to a structure pointer, follow gcc's behavior and make it
1910 // a non-ivar write-barrier.
1911 QualType ExpTy = E->getType();
1912 if (ExpTy->isPointerType())
1913 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1914 if (ExpTy->isRecordType())
1915 LV.setObjCIvar(false);
1920 if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
1921 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
1925 if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
1926 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
1930 if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
1931 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
1935 if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
1936 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
1940 if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
1941 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
1942 if (LV.isObjCIvar() && !LV.isObjCArray())
1943 // Using array syntax to assigning to what an ivar points to is not
1944 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
1945 LV.setObjCIvar(false);
1946 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
1947 // Using array syntax to assigning to what global points to is not
1948 // same as assigning to the global itself. {id *G;} G[i] = 0;
1949 LV.setGlobalObjCRef(false);
1953 if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
1954 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
1955 // We don't know if member is an 'ivar', but this flag is looked at
1956 // only in the context of LV.isObjCIvar().
1957 LV.setObjCArray(E->getType()->isArrayType());
1962 static llvm::Value *
1963 EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
1964 llvm::Value *V, llvm::Type *IRType,
1965 StringRef Name = StringRef()) {
1966 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
1967 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
1970 static LValue EmitThreadPrivateVarDeclLValue(
1971 CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
1972 llvm::Type *RealVarTy, SourceLocation Loc) {
1973 Addr = CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
1974 Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy);
1975 return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
1978 Address CodeGenFunction::EmitLoadOfReference(Address Addr,
1979 const ReferenceType *RefTy,
1980 AlignmentSource *Source) {
1981 llvm::Value *Ptr = Builder.CreateLoad(Addr);
1982 return Address(Ptr, getNaturalTypeAlignment(RefTy->getPointeeType(),
1983 Source, /*forPointee*/ true));
1987 LValue CodeGenFunction::EmitLoadOfReferenceLValue(Address RefAddr,
1988 const ReferenceType *RefTy) {
1989 AlignmentSource Source;
1990 Address Addr = EmitLoadOfReference(RefAddr, RefTy, &Source);
1991 return MakeAddrLValue(Addr, RefTy->getPointeeType(), Source);
1994 Address CodeGenFunction::EmitLoadOfPointer(Address Ptr,
1995 const PointerType *PtrTy,
1996 AlignmentSource *Source) {
1997 llvm::Value *Addr = Builder.CreateLoad(Ptr);
1998 return Address(Addr, getNaturalTypeAlignment(PtrTy->getPointeeType(), Source,
1999 /*forPointeeType=*/true));
2002 LValue CodeGenFunction::EmitLoadOfPointerLValue(Address PtrAddr,
2003 const PointerType *PtrTy) {
2004 AlignmentSource Source;
2005 Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &Source);
2006 return MakeAddrLValue(Addr, PtrTy->getPointeeType(), Source);
2009 static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
2010 const Expr *E, const VarDecl *VD) {
2011 QualType T = E->getType();
2013 // If it's thread_local, emit a call to its wrapper function instead.
2014 if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
2015 CGF.CGM.getCXXABI().usesThreadWrapperFunction())
2016 return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
2018 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
2019 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
2020 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
2021 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
2022 Address Addr(V, Alignment);
2024 // Emit reference to the private copy of the variable if it is an OpenMP
2025 // threadprivate variable.
2026 if (CGF.getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>())
2027 return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
2029 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2030 LV = CGF.EmitLoadOfReferenceLValue(Addr, RefTy);
2032 LV = CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
2034 setObjCGCLValueClass(CGF.getContext(), E, LV);
2038 static llvm::Constant *EmitFunctionDeclPointer(CodeGenModule &CGM,
2039 const FunctionDecl *FD) {
2040 if (FD->hasAttr<WeakRefAttr>()) {
2041 ConstantAddress aliasee = CGM.GetWeakRefReference(FD);
2042 return aliasee.getPointer();
2045 llvm::Constant *V = CGM.GetAddrOfFunction(FD);
2046 if (!FD->hasPrototype()) {
2047 if (const FunctionProtoType *Proto =
2048 FD->getType()->getAs<FunctionProtoType>()) {
2049 // Ugly case: for a K&R-style definition, the type of the definition
2050 // isn't the same as the type of a use. Correct for this with a
2052 QualType NoProtoType =
2053 CGM.getContext().getFunctionNoProtoType(Proto->getReturnType());
2054 NoProtoType = CGM.getContext().getPointerType(NoProtoType);
2055 V = llvm::ConstantExpr::getBitCast(V,
2056 CGM.getTypes().ConvertType(NoProtoType));
2062 static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
2063 const Expr *E, const FunctionDecl *FD) {
2064 llvm::Value *V = EmitFunctionDeclPointer(CGF.CGM, FD);
2065 CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
2066 return CGF.MakeAddrLValue(V, E->getType(), Alignment, AlignmentSource::Decl);
2069 static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
2070 llvm::Value *ThisValue) {
2071 QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
2072 LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
2073 return CGF.EmitLValueForField(LV, FD);
2076 /// Named Registers are named metadata pointing to the register name
2077 /// which will be read from/written to as an argument to the intrinsic
2078 /// @llvm.read/write_register.
2079 /// So far, only the name is being passed down, but other options such as
2080 /// register type, allocation type or even optimization options could be
2081 /// passed down via the metadata node.
2082 static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
2083 SmallString<64> Name("llvm.named.register.");
2084 AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
2085 assert(Asm->getLabel().size() < 64-Name.size() &&
2086 "Register name too big");
2087 Name.append(Asm->getLabel());
2088 llvm::NamedMDNode *M =
2089 CGM.getModule().getOrInsertNamedMetadata(Name);
2090 if (M->getNumOperands() == 0) {
2091 llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
2093 llvm::Metadata *Ops[] = {Str};
2094 M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2097 CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
2100 llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
2101 return LValue::MakeGlobalReg(Address(Ptr, Alignment), VD->getType());
2104 LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
2105 const NamedDecl *ND = E->getDecl();
2106 QualType T = E->getType();
2108 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2109 // Global Named registers access via intrinsics only
2110 if (VD->getStorageClass() == SC_Register &&
2111 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
2112 return EmitGlobalNamedRegister(VD, CGM);
2114 // A DeclRefExpr for a reference initialized by a constant expression can
2115 // appear without being odr-used. Directly emit the constant initializer.
2116 const Expr *Init = VD->getAnyInitializer(VD);
2117 if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() &&
2118 VD->isUsableInConstantExpressions(getContext()) &&
2119 VD->checkInitIsICE() &&
2120 // Do not emit if it is private OpenMP variable.
2121 !(E->refersToEnclosingVariableOrCapture() && CapturedStmtInfo &&
2122 LocalDeclMap.count(VD))) {
2123 llvm::Constant *Val =
2124 CGM.EmitConstantValue(*VD->evaluateValue(), VD->getType(), this);
2125 assert(Val && "failed to emit reference constant expression");
2126 // FIXME: Eventually we will want to emit vector element references.
2128 // Should we be using the alignment of the constant pointer we emitted?
2129 CharUnits Alignment = getNaturalTypeAlignment(E->getType(), nullptr,
2132 return MakeAddrLValue(Address(Val, Alignment), T, AlignmentSource::Decl);
2135 // Check for captured variables.
2136 if (E->refersToEnclosingVariableOrCapture()) {
2137 if (auto *FD = LambdaCaptureFields.lookup(VD))
2138 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
2139 else if (CapturedStmtInfo) {
2140 auto I = LocalDeclMap.find(VD);
2141 if (I != LocalDeclMap.end()) {
2142 if (auto RefTy = VD->getType()->getAs<ReferenceType>())
2143 return EmitLoadOfReferenceLValue(I->second, RefTy);
2144 return MakeAddrLValue(I->second, T);
2147 EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
2148 CapturedStmtInfo->getContextValue());
2149 return MakeAddrLValue(
2150 Address(CapLVal.getPointer(), getContext().getDeclAlign(VD)),
2151 CapLVal.getType(), AlignmentSource::Decl);
2154 assert(isa<BlockDecl>(CurCodeDecl));
2155 Address addr = GetAddrOfBlockDecl(VD, VD->hasAttr<BlocksAttr>());
2156 return MakeAddrLValue(addr, T, AlignmentSource::Decl);
2160 // FIXME: We should be able to assert this for FunctionDecls as well!
2161 // FIXME: We should be able to assert this for all DeclRefExprs, not just
2162 // those with a valid source location.
2163 assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
2164 !E->getLocation().isValid()) &&
2165 "Should not use decl without marking it used!");
2167 if (ND->hasAttr<WeakRefAttr>()) {
2168 const auto *VD = cast<ValueDecl>(ND);
2169 ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
2170 return MakeAddrLValue(Aliasee, T, AlignmentSource::Decl);
2173 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2174 // Check if this is a global variable.
2175 if (VD->hasLinkage() || VD->isStaticDataMember())
2176 return EmitGlobalVarDeclLValue(*this, E, VD);
2178 Address addr = Address::invalid();
2180 // The variable should generally be present in the local decl map.
2181 auto iter = LocalDeclMap.find(VD);
2182 if (iter != LocalDeclMap.end()) {
2183 addr = iter->second;
2185 // Otherwise, it might be static local we haven't emitted yet for
2186 // some reason; most likely, because it's in an outer function.
2187 } else if (VD->isStaticLocal()) {
2188 addr = Address(CGM.getOrCreateStaticVarDecl(
2189 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false)),
2190 getContext().getDeclAlign(VD));
2192 // No other cases for now.
2194 llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
2198 // Check for OpenMP threadprivate variables.
2199 if (getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
2200 return EmitThreadPrivateVarDeclLValue(
2201 *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
2205 // Drill into block byref variables.
2206 bool isBlockByref = VD->hasAttr<BlocksAttr>();
2208 addr = emitBlockByrefAddress(addr, VD);
2211 // Drill into reference types.
2213 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2214 LV = EmitLoadOfReferenceLValue(addr, RefTy);
2216 LV = MakeAddrLValue(addr, T, AlignmentSource::Decl);
2219 bool isLocalStorage = VD->hasLocalStorage();
2221 bool NonGCable = isLocalStorage &&
2222 !VD->getType()->isReferenceType() &&
2225 LV.getQuals().removeObjCGCAttr();
2229 bool isImpreciseLifetime =
2230 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
2231 if (isImpreciseLifetime)
2232 LV.setARCPreciseLifetime(ARCImpreciseLifetime);
2233 setObjCGCLValueClass(getContext(), E, LV);
2237 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
2238 return EmitFunctionDeclLValue(*this, E, FD);
2240 // FIXME: While we're emitting a binding from an enclosing scope, all other
2241 // DeclRefExprs we see should be implicitly treated as if they also refer to
2242 // an enclosing scope.
2243 if (const auto *BD = dyn_cast<BindingDecl>(ND))
2244 return EmitLValue(BD->getBinding());
2246 llvm_unreachable("Unhandled DeclRefExpr");
2249 LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
2250 // __extension__ doesn't affect lvalue-ness.
2251 if (E->getOpcode() == UO_Extension)
2252 return EmitLValue(E->getSubExpr());
2254 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
2255 switch (E->getOpcode()) {
2256 default: llvm_unreachable("Unknown unary operator lvalue!");
2258 QualType T = E->getSubExpr()->getType()->getPointeeType();
2259 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
2261 AlignmentSource AlignSource;
2262 Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &AlignSource);
2263 LValue LV = MakeAddrLValue(Addr, T, AlignSource);
2264 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
2266 // We should not generate __weak write barrier on indirect reference
2267 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
2268 // But, we continue to generate __strong write barrier on indirect write
2269 // into a pointer to object.
2270 if (getLangOpts().ObjC1 &&
2271 getLangOpts().getGC() != LangOptions::NonGC &&
2273 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
2278 LValue LV = EmitLValue(E->getSubExpr());
2279 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
2281 // __real is valid on scalars. This is a faster way of testing that.
2282 // __imag can only produce an rvalue on scalars.
2283 if (E->getOpcode() == UO_Real &&
2284 !LV.getAddress().getElementType()->isStructTy()) {
2285 assert(E->getSubExpr()->getType()->isArithmeticType());
2289 QualType T = ExprTy->castAs<ComplexType>()->getElementType();
2292 (E->getOpcode() == UO_Real
2293 ? emitAddrOfRealComponent(LV.getAddress(), LV.getType())
2294 : emitAddrOfImagComponent(LV.getAddress(), LV.getType()));
2295 LValue ElemLV = MakeAddrLValue(Component, T, LV.getAlignmentSource());
2296 ElemLV.getQuals().addQualifiers(LV.getQuals());
2301 LValue LV = EmitLValue(E->getSubExpr());
2302 bool isInc = E->getOpcode() == UO_PreInc;
2304 if (E->getType()->isAnyComplexType())
2305 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
2307 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
2313 LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
2314 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
2315 E->getType(), AlignmentSource::Decl);
2318 LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
2319 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
2320 E->getType(), AlignmentSource::Decl);
2323 LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
2324 auto SL = E->getFunctionName();
2325 assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
2326 StringRef FnName = CurFn->getName();
2327 if (FnName.startswith("\01"))
2328 FnName = FnName.substr(1);
2329 StringRef NameItems[] = {
2330 PredefinedExpr::getIdentTypeName(E->getIdentType()), FnName};
2331 std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
2332 if (auto *BD = dyn_cast<BlockDecl>(CurCodeDecl)) {
2333 std::string Name = SL->getString();
2334 if (!Name.empty()) {
2335 unsigned Discriminator =
2336 CGM.getCXXABI().getMangleContext().getBlockId(BD, true);
2338 Name += "_" + Twine(Discriminator + 1).str();
2339 auto C = CGM.GetAddrOfConstantCString(Name, GVName.c_str());
2340 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
2342 auto C = CGM.GetAddrOfConstantCString(FnName, GVName.c_str());
2343 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
2346 auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
2347 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
2350 /// Emit a type description suitable for use by a runtime sanitizer library. The
2351 /// format of a type descriptor is
2354 /// { i16 TypeKind, i16 TypeInfo }
2357 /// followed by an array of i8 containing the type name. TypeKind is 0 for an
2358 /// integer, 1 for a floating point value, and -1 for anything else.
2359 llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
2360 // Only emit each type's descriptor once.
2361 if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
2364 uint16_t TypeKind = -1;
2365 uint16_t TypeInfo = 0;
2367 if (T->isIntegerType()) {
2369 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
2370 (T->isSignedIntegerType() ? 1 : 0);
2371 } else if (T->isFloatingType()) {
2373 TypeInfo = getContext().getTypeSize(T);
2376 // Format the type name as if for a diagnostic, including quotes and
2377 // optionally an 'aka'.
2378 SmallString<32> Buffer;
2379 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
2380 (intptr_t)T.getAsOpaquePtr(),
2381 StringRef(), StringRef(), None, Buffer,
2384 llvm::Constant *Components[] = {
2385 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
2386 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
2388 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
2390 auto *GV = new llvm::GlobalVariable(
2391 CGM.getModule(), Descriptor->getType(),
2392 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
2393 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2394 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
2396 // Remember the descriptor for this type.
2397 CGM.setTypeDescriptorInMap(T, GV);
2402 llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
2403 llvm::Type *TargetTy = IntPtrTy;
2405 // Floating-point types which fit into intptr_t are bitcast to integers
2406 // and then passed directly (after zero-extension, if necessary).
2407 if (V->getType()->isFloatingPointTy()) {
2408 unsigned Bits = V->getType()->getPrimitiveSizeInBits();
2409 if (Bits <= TargetTy->getIntegerBitWidth())
2410 V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
2414 // Integers which fit in intptr_t are zero-extended and passed directly.
2415 if (V->getType()->isIntegerTy() &&
2416 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
2417 return Builder.CreateZExt(V, TargetTy);
2419 // Pointers are passed directly, everything else is passed by address.
2420 if (!V->getType()->isPointerTy()) {
2421 Address Ptr = CreateDefaultAlignTempAlloca(V->getType());
2422 Builder.CreateStore(V, Ptr);
2423 V = Ptr.getPointer();
2425 return Builder.CreatePtrToInt(V, TargetTy);
2428 /// \brief Emit a representation of a SourceLocation for passing to a handler
2429 /// in a sanitizer runtime library. The format for this data is:
2431 /// struct SourceLocation {
2432 /// const char *Filename;
2433 /// int32_t Line, Column;
2436 /// For an invalid SourceLocation, the Filename pointer is null.
2437 llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
2438 llvm::Constant *Filename;
2441 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
2442 if (PLoc.isValid()) {
2443 StringRef FilenameString = PLoc.getFilename();
2445 int PathComponentsToStrip =
2446 CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
2447 if (PathComponentsToStrip < 0) {
2448 assert(PathComponentsToStrip != INT_MIN);
2449 int PathComponentsToKeep = -PathComponentsToStrip;
2450 auto I = llvm::sys::path::rbegin(FilenameString);
2451 auto E = llvm::sys::path::rend(FilenameString);
2452 while (I != E && --PathComponentsToKeep)
2455 FilenameString = FilenameString.substr(I - E);
2456 } else if (PathComponentsToStrip > 0) {
2457 auto I = llvm::sys::path::begin(FilenameString);
2458 auto E = llvm::sys::path::end(FilenameString);
2459 while (I != E && PathComponentsToStrip--)
2464 FilenameString.substr(I - llvm::sys::path::begin(FilenameString));
2466 FilenameString = llvm::sys::path::filename(FilenameString);
2469 auto FilenameGV = CGM.GetAddrOfConstantCString(FilenameString, ".src");
2470 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
2471 cast<llvm::GlobalVariable>(FilenameGV.getPointer()));
2472 Filename = FilenameGV.getPointer();
2473 Line = PLoc.getLine();
2474 Column = PLoc.getColumn();
2476 Filename = llvm::Constant::getNullValue(Int8PtrTy);
2480 llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
2481 Builder.getInt32(Column)};
2483 return llvm::ConstantStruct::getAnon(Data);
2487 /// \brief Specify under what conditions this check can be recovered
2488 enum class CheckRecoverableKind {
2489 /// Always terminate program execution if this check fails.
2491 /// Check supports recovering, runtime has both fatal (noreturn) and
2492 /// non-fatal handlers for this check.
2494 /// Runtime conditionally aborts, always need to support recovery.
2499 static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
2500 assert(llvm::countPopulation(Kind) == 1);
2502 case SanitizerKind::Vptr:
2503 return CheckRecoverableKind::AlwaysRecoverable;
2504 case SanitizerKind::Return:
2505 case SanitizerKind::Unreachable:
2506 return CheckRecoverableKind::Unrecoverable;
2508 return CheckRecoverableKind::Recoverable;
2513 struct SanitizerHandlerInfo {
2514 char const *const Name;
2519 const SanitizerHandlerInfo SanitizerHandlers[] = {
2520 #define SANITIZER_CHECK(Enum, Name, Version) {#Name, Version},
2521 LIST_SANITIZER_CHECKS
2522 #undef SANITIZER_CHECK
2525 static void emitCheckHandlerCall(CodeGenFunction &CGF,
2526 llvm::FunctionType *FnType,
2527 ArrayRef<llvm::Value *> FnArgs,
2528 SanitizerHandler CheckHandler,
2529 CheckRecoverableKind RecoverKind, bool IsFatal,
2530 llvm::BasicBlock *ContBB) {
2531 assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
2532 bool NeedsAbortSuffix =
2533 IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
2534 const SanitizerHandlerInfo &CheckInfo = SanitizerHandlers[CheckHandler];
2535 const StringRef CheckName = CheckInfo.Name;
2536 std::string FnName =
2537 ("__ubsan_handle_" + CheckName +
2538 (CheckInfo.Version ? "_v" + llvm::utostr(CheckInfo.Version) : "") +
2539 (NeedsAbortSuffix ? "_abort" : ""))
2542 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
2544 llvm::AttrBuilder B;
2546 B.addAttribute(llvm::Attribute::NoReturn)
2547 .addAttribute(llvm::Attribute::NoUnwind);
2549 B.addAttribute(llvm::Attribute::UWTable);
2551 llvm::Value *Fn = CGF.CGM.CreateRuntimeFunction(
2553 llvm::AttributeSet::get(CGF.getLLVMContext(),
2554 llvm::AttributeSet::FunctionIndex, B),
2556 llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
2558 HandlerCall->setDoesNotReturn();
2559 CGF.Builder.CreateUnreachable();
2561 CGF.Builder.CreateBr(ContBB);
2565 void CodeGenFunction::EmitCheck(
2566 ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
2567 SanitizerHandler CheckHandler, ArrayRef<llvm::Constant *> StaticArgs,
2568 ArrayRef<llvm::Value *> DynamicArgs) {
2569 assert(IsSanitizerScope);
2570 assert(Checked.size() > 0);
2571 assert(CheckHandler >= 0 &&
2572 CheckHandler < sizeof(SanitizerHandlers) / sizeof(*SanitizerHandlers));
2573 const StringRef CheckName = SanitizerHandlers[CheckHandler].Name;
2575 llvm::Value *FatalCond = nullptr;
2576 llvm::Value *RecoverableCond = nullptr;
2577 llvm::Value *TrapCond = nullptr;
2578 for (int i = 0, n = Checked.size(); i < n; ++i) {
2579 llvm::Value *Check = Checked[i].first;
2580 // -fsanitize-trap= overrides -fsanitize-recover=.
2581 llvm::Value *&Cond =
2582 CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
2584 : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
2587 Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
2591 EmitTrapCheck(TrapCond);
2592 if (!FatalCond && !RecoverableCond)
2595 llvm::Value *JointCond;
2596 if (FatalCond && RecoverableCond)
2597 JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
2599 JointCond = FatalCond ? FatalCond : RecoverableCond;
2602 CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
2603 assert(SanOpts.has(Checked[0].second));
2605 for (int i = 1, n = Checked.size(); i < n; ++i) {
2606 assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
2607 "All recoverable kinds in a single check must be same!");
2608 assert(SanOpts.has(Checked[i].second));
2612 llvm::BasicBlock *Cont = createBasicBlock("cont");
2613 llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
2614 llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
2615 // Give hint that we very much don't expect to execute the handler
2616 // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
2617 llvm::MDBuilder MDHelper(getLLVMContext());
2618 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2619 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
2620 EmitBlock(Handlers);
2622 // Handler functions take an i8* pointing to the (handler-specific) static
2623 // information block, followed by a sequence of intptr_t arguments
2624 // representing operand values.
2625 SmallVector<llvm::Value *, 4> Args;
2626 SmallVector<llvm::Type *, 4> ArgTypes;
2627 Args.reserve(DynamicArgs.size() + 1);
2628 ArgTypes.reserve(DynamicArgs.size() + 1);
2630 // Emit handler arguments and create handler function type.
2631 if (!StaticArgs.empty()) {
2632 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2634 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2635 llvm::GlobalVariable::PrivateLinkage, Info);
2636 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2637 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2638 Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
2639 ArgTypes.push_back(Int8PtrTy);
2642 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
2643 Args.push_back(EmitCheckValue(DynamicArgs[i]));
2644 ArgTypes.push_back(IntPtrTy);
2647 llvm::FunctionType *FnType =
2648 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
2650 if (!FatalCond || !RecoverableCond) {
2651 // Simple case: we need to generate a single handler call, either
2652 // fatal, or non-fatal.
2653 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind,
2654 (FatalCond != nullptr), Cont);
2656 // Emit two handler calls: first one for set of unrecoverable checks,
2657 // another one for recoverable.
2658 llvm::BasicBlock *NonFatalHandlerBB =
2659 createBasicBlock("non_fatal." + CheckName);
2660 llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
2661 Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
2662 EmitBlock(FatalHandlerBB);
2663 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, true,
2665 EmitBlock(NonFatalHandlerBB);
2666 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, false,
2673 void CodeGenFunction::EmitCfiSlowPathCheck(
2674 SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId,
2675 llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) {
2676 llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
2678 llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
2679 llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
2681 llvm::MDBuilder MDHelper(getLLVMContext());
2682 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2683 BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
2687 bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind);
2689 llvm::CallInst *CheckCall;
2691 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2693 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2694 llvm::GlobalVariable::PrivateLinkage, Info);
2695 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2696 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2698 llvm::Constant *SlowPathDiagFn = CGM.getModule().getOrInsertFunction(
2699 "__cfi_slowpath_diag",
2700 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
2702 CheckCall = Builder.CreateCall(
2704 {TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)});
2706 llvm::Constant *SlowPathFn = CGM.getModule().getOrInsertFunction(
2708 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
2709 CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
2712 CheckCall->setDoesNotThrow();
2717 // This function is basically a switch over the CFI failure kind, which is
2718 // extracted from CFICheckFailData (1st function argument). Each case is either
2719 // llvm.trap or a call to one of the two runtime handlers, based on
2720 // -fsanitize-trap and -fsanitize-recover settings. Default case (invalid
2721 // failure kind) traps, but this should really never happen. CFICheckFailData
2722 // can be nullptr if the calling module has -fsanitize-trap behavior for this
2723 // check kind; in this case __cfi_check_fail traps as well.
2724 void CodeGenFunction::EmitCfiCheckFail() {
2725 SanitizerScope SanScope(this);
2726 FunctionArgList Args;
2727 ImplicitParamDecl ArgData(getContext(), nullptr, SourceLocation(), nullptr,
2728 getContext().VoidPtrTy);
2729 ImplicitParamDecl ArgAddr(getContext(), nullptr, SourceLocation(), nullptr,
2730 getContext().VoidPtrTy);
2731 Args.push_back(&ArgData);
2732 Args.push_back(&ArgAddr);
2734 const CGFunctionInfo &FI =
2735 CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args);
2737 llvm::Function *F = llvm::Function::Create(
2738 llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false),
2739 llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule());
2740 F->setVisibility(llvm::GlobalValue::HiddenVisibility);
2742 StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args,
2746 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false,
2747 CGM.getContext().VoidPtrTy, ArgData.getLocation());
2749 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false,
2750 CGM.getContext().VoidPtrTy, ArgAddr.getLocation());
2752 // Data == nullptr means the calling module has trap behaviour for this check.
2753 llvm::Value *DataIsNotNullPtr =
2754 Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy));
2755 EmitTrapCheck(DataIsNotNullPtr);
2757 llvm::StructType *SourceLocationTy =
2758 llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty, nullptr);
2759 llvm::StructType *CfiCheckFailDataTy =
2760 llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy, nullptr);
2762 llvm::Value *V = Builder.CreateConstGEP2_32(
2764 Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0,
2766 Address CheckKindAddr(V, getIntAlign());
2767 llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr);
2769 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
2770 CGM.getLLVMContext(),
2771 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
2772 llvm::Value *ValidVtable = Builder.CreateZExt(
2773 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
2774 {Addr, AllVtables}),
2777 const std::pair<int, SanitizerMask> CheckKinds[] = {
2778 {CFITCK_VCall, SanitizerKind::CFIVCall},
2779 {CFITCK_NVCall, SanitizerKind::CFINVCall},
2780 {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast},
2781 {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast},
2782 {CFITCK_ICall, SanitizerKind::CFIICall}};
2784 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 5> Checks;
2785 for (auto CheckKindMaskPair : CheckKinds) {
2786 int Kind = CheckKindMaskPair.first;
2787 SanitizerMask Mask = CheckKindMaskPair.second;
2789 Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind));
2790 if (CGM.getLangOpts().Sanitize.has(Mask))
2791 EmitCheck(std::make_pair(Cond, Mask), SanitizerHandler::CFICheckFail, {},
2792 {Data, Addr, ValidVtable});
2794 EmitTrapCheck(Cond);
2798 // The only reference to this function will be created during LTO link.
2799 // Make sure it survives until then.
2800 CGM.addUsedGlobal(F);
2803 void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) {
2804 llvm::BasicBlock *Cont = createBasicBlock("cont");
2806 // If we're optimizing, collapse all calls to trap down to just one per
2807 // function to save on code size.
2808 if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
2809 TrapBB = createBasicBlock("trap");
2810 Builder.CreateCondBr(Checked, Cont, TrapBB);
2812 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
2813 TrapCall->setDoesNotReturn();
2814 TrapCall->setDoesNotThrow();
2815 Builder.CreateUnreachable();
2817 Builder.CreateCondBr(Checked, Cont, TrapBB);
2823 llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
2824 llvm::CallInst *TrapCall = Builder.CreateCall(CGM.getIntrinsic(IntrID));
2826 if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
2827 auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
2828 CGM.getCodeGenOpts().TrapFuncName);
2829 TrapCall->addAttribute(llvm::AttributeSet::FunctionIndex, A);
2835 Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E,
2836 AlignmentSource *AlignSource) {
2837 assert(E->getType()->isArrayType() &&
2838 "Array to pointer decay must have array source type!");
2840 // Expressions of array type can't be bitfields or vector elements.
2841 LValue LV = EmitLValue(E);
2842 Address Addr = LV.getAddress();
2843 if (AlignSource) *AlignSource = LV.getAlignmentSource();
2845 // If the array type was an incomplete type, we need to make sure
2846 // the decay ends up being the right type.
2847 llvm::Type *NewTy = ConvertType(E->getType());
2848 Addr = Builder.CreateElementBitCast(Addr, NewTy);
2850 // Note that VLA pointers are always decayed, so we don't need to do
2852 if (!E->getType()->isVariableArrayType()) {
2853 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
2854 "Expected pointer to array");
2855 Addr = Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(), "arraydecay");
2858 QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
2859 return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType));
2862 /// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
2863 /// array to pointer, return the array subexpression.
2864 static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
2865 // If this isn't just an array->pointer decay, bail out.
2866 const auto *CE = dyn_cast<CastExpr>(E);
2867 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
2870 // If this is a decay from variable width array, bail out.
2871 const Expr *SubExpr = CE->getSubExpr();
2872 if (SubExpr->getType()->isVariableArrayType())
2878 static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF,
2880 ArrayRef<llvm::Value*> indices,
2882 const llvm::Twine &name = "arrayidx") {
2884 return CGF.Builder.CreateInBoundsGEP(ptr, indices, name);
2886 return CGF.Builder.CreateGEP(ptr, indices, name);
2890 static CharUnits getArrayElementAlign(CharUnits arrayAlign,
2892 CharUnits eltSize) {
2893 // If we have a constant index, we can use the exact offset of the
2894 // element we're accessing.
2895 if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
2896 CharUnits offset = constantIdx->getZExtValue() * eltSize;
2897 return arrayAlign.alignmentAtOffset(offset);
2899 // Otherwise, use the worst-case alignment for any element.
2901 return arrayAlign.alignmentOfArrayElement(eltSize);
2905 static QualType getFixedSizeElementType(const ASTContext &ctx,
2906 const VariableArrayType *vla) {
2909 eltType = vla->getElementType();
2910 } while ((vla = ctx.getAsVariableArrayType(eltType)));
2914 static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
2915 ArrayRef<llvm::Value*> indices,
2916 QualType eltType, bool inbounds,
2917 const llvm::Twine &name = "arrayidx") {
2918 // All the indices except that last must be zero.
2920 for (auto idx : indices.drop_back())
2921 assert(isa<llvm::ConstantInt>(idx) &&
2922 cast<llvm::ConstantInt>(idx)->isZero());
2925 // Determine the element size of the statically-sized base. This is
2926 // the thing that the indices are expressed in terms of.
2927 if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
2928 eltType = getFixedSizeElementType(CGF.getContext(), vla);
2931 // We can use that to compute the best alignment of the element.
2932 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
2933 CharUnits eltAlign =
2934 getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
2936 llvm::Value *eltPtr =
2937 emitArraySubscriptGEP(CGF, addr.getPointer(), indices, inbounds, name);
2938 return Address(eltPtr, eltAlign);
2941 LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
2943 // The index must always be an integer, which is not an aggregate. Emit it
2944 // in lexical order (this complexity is, sadly, required by C++17).
2945 llvm::Value *IdxPre =
2946 (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E->getIdx()) : nullptr;
2947 auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * {
2949 if (E->getLHS() != E->getIdx()) {
2950 assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS");
2951 Idx = EmitScalarExpr(E->getIdx());
2954 QualType IdxTy = E->getIdx()->getType();
2955 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
2957 if (SanOpts.has(SanitizerKind::ArrayBounds))
2958 EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
2960 // Extend or truncate the index type to 32 or 64-bits.
2961 if (Promote && Idx->getType() != IntPtrTy)
2962 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
2968 // If the base is a vector type, then we are forming a vector element lvalue
2969 // with this subscript.
2970 if (E->getBase()->getType()->isVectorType() &&
2971 !isa<ExtVectorElementExpr>(E->getBase())) {
2972 // Emit the vector as an lvalue to get its address.
2973 LValue LHS = EmitLValue(E->getBase());
2974 auto *Idx = EmitIdxAfterBase(/*Promote*/false);
2975 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
2976 return LValue::MakeVectorElt(LHS.getAddress(), Idx,
2977 E->getBase()->getType(),
2978 LHS.getAlignmentSource());
2981 // All the other cases basically behave like simple offsetting.
2983 // Handle the extvector case we ignored above.
2984 if (isa<ExtVectorElementExpr>(E->getBase())) {
2985 LValue LV = EmitLValue(E->getBase());
2986 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
2987 Address Addr = EmitExtVectorElementLValue(LV);
2989 QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
2990 Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true);
2991 return MakeAddrLValue(Addr, EltType, LV.getAlignmentSource());
2994 AlignmentSource AlignSource;
2995 Address Addr = Address::invalid();
2996 if (const VariableArrayType *vla =
2997 getContext().getAsVariableArrayType(E->getType())) {
2998 // The base must be a pointer, which is not an aggregate. Emit
2999 // it. It needs to be emitted first in case it's what captures
3001 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
3002 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3004 // The element count here is the total number of non-VLA elements.
3005 llvm::Value *numElements = getVLASize(vla).first;
3007 // Effectively, the multiply by the VLA size is part of the GEP.
3008 // GEP indexes are signed, and scaling an index isn't permitted to
3009 // signed-overflow, so we use the same semantics for our explicit
3010 // multiply. We suppress this if overflow is not undefined behavior.
3011 if (getLangOpts().isSignedOverflowDefined()) {
3012 Idx = Builder.CreateMul(Idx, numElements);
3014 Idx = Builder.CreateNSWMul(Idx, numElements);
3017 Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
3018 !getLangOpts().isSignedOverflowDefined());
3020 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
3021 // Indexing over an interface, as in "NSString *P; P[4];"
3023 // Emit the base pointer.
3024 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
3025 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3027 CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
3028 llvm::Value *InterfaceSizeVal =
3029 llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());
3031 llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
3033 // We don't necessarily build correct LLVM struct types for ObjC
3034 // interfaces, so we can't rely on GEP to do this scaling
3035 // correctly, so we need to cast to i8*. FIXME: is this actually
3036 // true? A lot of other things in the fragile ABI would break...
3037 llvm::Type *OrigBaseTy = Addr.getType();
3038 Addr = Builder.CreateElementBitCast(Addr, Int8Ty);
3041 CharUnits EltAlign =
3042 getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
3043 llvm::Value *EltPtr =
3044 emitArraySubscriptGEP(*this, Addr.getPointer(), ScaledIdx, false);
3045 Addr = Address(EltPtr, EltAlign);
3048 Addr = Builder.CreateBitCast(Addr, OrigBaseTy);
3049 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3050 // If this is A[i] where A is an array, the frontend will have decayed the
3051 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3052 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3053 // "gep x, i" here. Emit one "gep A, 0, i".
3054 assert(Array->getType()->isArrayType() &&
3055 "Array to pointer decay must have array source type!");
3057 // For simple multidimensional array indexing, set the 'accessed' flag for
3058 // better bounds-checking of the base expression.
3059 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3060 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3062 ArrayLV = EmitLValue(Array);
3063 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3065 // Propagate the alignment from the array itself to the result.
3066 Addr = emitArraySubscriptGEP(*this, ArrayLV.getAddress(),
3067 {CGM.getSize(CharUnits::Zero()), Idx},
3069 !getLangOpts().isSignedOverflowDefined());
3070 AlignSource = ArrayLV.getAlignmentSource();
3072 // The base must be a pointer; emit it with an estimate of its alignment.
3073 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
3074 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3075 Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
3076 !getLangOpts().isSignedOverflowDefined());
3079 LValue LV = MakeAddrLValue(Addr, E->getType(), AlignSource);
3081 // TODO: Preserve/extend path TBAA metadata?
3083 if (getLangOpts().ObjC1 &&
3084 getLangOpts().getGC() != LangOptions::NonGC) {
3085 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
3086 setObjCGCLValueClass(getContext(), E, LV);
3091 static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base,
3092 AlignmentSource &AlignSource,
3093 QualType BaseTy, QualType ElTy,
3094 bool IsLowerBound) {
3096 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParenImpCasts())) {
3097 BaseLVal = CGF.EmitOMPArraySectionExpr(ASE, IsLowerBound);
3098 if (BaseTy->isArrayType()) {
3099 Address Addr = BaseLVal.getAddress();
3100 AlignSource = BaseLVal.getAlignmentSource();
3102 // If the array type was an incomplete type, we need to make sure
3103 // the decay ends up being the right type.
3104 llvm::Type *NewTy = CGF.ConvertType(BaseTy);
3105 Addr = CGF.Builder.CreateElementBitCast(Addr, NewTy);
3107 // Note that VLA pointers are always decayed, so we don't need to do
3109 if (!BaseTy->isVariableArrayType()) {
3110 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3111 "Expected pointer to array");
3112 Addr = CGF.Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(),
3116 return CGF.Builder.CreateElementBitCast(Addr,
3117 CGF.ConvertTypeForMem(ElTy));
3119 CharUnits Align = CGF.getNaturalTypeAlignment(ElTy, &AlignSource);
3120 return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress()), Align);
3122 return CGF.EmitPointerWithAlignment(Base, &AlignSource);
3125 LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
3126 bool IsLowerBound) {
3129 dyn_cast<OMPArraySectionExpr>(E->getBase()->IgnoreParenImpCasts()))
3130 BaseTy = OMPArraySectionExpr::getBaseOriginalType(ASE);
3132 BaseTy = E->getBase()->getType();
3133 QualType ResultExprTy;
3134 if (auto *AT = getContext().getAsArrayType(BaseTy))
3135 ResultExprTy = AT->getElementType();
3137 ResultExprTy = BaseTy->getPointeeType();
3138 llvm::Value *Idx = nullptr;
3139 if (IsLowerBound || E->getColonLoc().isInvalid()) {
3140 // Requesting lower bound or upper bound, but without provided length and
3141 // without ':' symbol for the default length -> length = 1.
3142 // Idx = LowerBound ?: 0;
3143 if (auto *LowerBound = E->getLowerBound()) {
3144 Idx = Builder.CreateIntCast(
3145 EmitScalarExpr(LowerBound), IntPtrTy,
3146 LowerBound->getType()->hasSignedIntegerRepresentation());
3148 Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
3150 // Try to emit length or lower bound as constant. If this is possible, 1
3151 // is subtracted from constant length or lower bound. Otherwise, emit LLVM
3152 // IR (LB + Len) - 1.
3153 auto &C = CGM.getContext();
3154 auto *Length = E->getLength();
3155 llvm::APSInt ConstLength;
3157 // Idx = LowerBound + Length - 1;
3158 if (Length->isIntegerConstantExpr(ConstLength, C)) {
3159 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3162 auto *LowerBound = E->getLowerBound();
3163 llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
3164 if (LowerBound && LowerBound->isIntegerConstantExpr(ConstLowerBound, C)) {
3165 ConstLowerBound = ConstLowerBound.zextOrTrunc(PointerWidthInBits);
3166 LowerBound = nullptr;
3170 else if (!LowerBound)
3173 if (Length || LowerBound) {
3174 auto *LowerBoundVal =
3176 ? Builder.CreateIntCast(
3177 EmitScalarExpr(LowerBound), IntPtrTy,
3178 LowerBound->getType()->hasSignedIntegerRepresentation())
3179 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
3182 ? Builder.CreateIntCast(
3183 EmitScalarExpr(Length), IntPtrTy,
3184 Length->getType()->hasSignedIntegerRepresentation())
3185 : llvm::ConstantInt::get(IntPtrTy, ConstLength);
3186 Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
3188 !getLangOpts().isSignedOverflowDefined());
3189 if (Length && LowerBound) {
3190 Idx = Builder.CreateSub(
3191 Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
3192 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3195 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
3197 // Idx = ArraySize - 1;
3198 QualType ArrayTy = BaseTy->isPointerType()
3199 ? E->getBase()->IgnoreParenImpCasts()->getType()
3201 if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) {
3202 Length = VAT->getSizeExpr();
3203 if (Length->isIntegerConstantExpr(ConstLength, C))
3206 auto *CAT = C.getAsConstantArrayType(ArrayTy);
3207 ConstLength = CAT->getSize();
3210 auto *LengthVal = Builder.CreateIntCast(
3211 EmitScalarExpr(Length), IntPtrTy,
3212 Length->getType()->hasSignedIntegerRepresentation());
3213 Idx = Builder.CreateSub(
3214 LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
3215 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3217 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3219 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
3225 Address EltPtr = Address::invalid();
3226 AlignmentSource AlignSource;
3227 if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
3228 // The base must be a pointer, which is not an aggregate. Emit
3229 // it. It needs to be emitted first in case it's what captures
3232 emitOMPArraySectionBase(*this, E->getBase(), AlignSource, BaseTy,
3233 VLA->getElementType(), IsLowerBound);
3234 // The element count here is the total number of non-VLA elements.
3235 llvm::Value *NumElements = getVLASize(VLA).first;
3237 // Effectively, the multiply by the VLA size is part of the GEP.
3238 // GEP indexes are signed, and scaling an index isn't permitted to
3239 // signed-overflow, so we use the same semantics for our explicit
3240 // multiply. We suppress this if overflow is not undefined behavior.
3241 if (getLangOpts().isSignedOverflowDefined())
3242 Idx = Builder.CreateMul(Idx, NumElements);
3244 Idx = Builder.CreateNSWMul(Idx, NumElements);
3245 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(),
3246 !getLangOpts().isSignedOverflowDefined());
3247 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3248 // If this is A[i] where A is an array, the frontend will have decayed the
3249 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3250 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3251 // "gep x, i" here. Emit one "gep A, 0, i".
3252 assert(Array->getType()->isArrayType() &&
3253 "Array to pointer decay must have array source type!");
3255 // For simple multidimensional array indexing, set the 'accessed' flag for
3256 // better bounds-checking of the base expression.
3257 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3258 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3260 ArrayLV = EmitLValue(Array);
3262 // Propagate the alignment from the array itself to the result.
3263 EltPtr = emitArraySubscriptGEP(
3264 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
3265 ResultExprTy, !getLangOpts().isSignedOverflowDefined());
3266 AlignSource = ArrayLV.getAlignmentSource();
3268 Address Base = emitOMPArraySectionBase(*this, E->getBase(), AlignSource,
3269 BaseTy, ResultExprTy, IsLowerBound);
3270 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy,
3271 !getLangOpts().isSignedOverflowDefined());
3274 return MakeAddrLValue(EltPtr, ResultExprTy, AlignSource);
3277 LValue CodeGenFunction::
3278 EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
3279 // Emit the base vector as an l-value.
3282 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
3284 // If it is a pointer to a vector, emit the address and form an lvalue with
3286 AlignmentSource AlignSource;
3287 Address Ptr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
3288 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
3289 Base = MakeAddrLValue(Ptr, PT->getPointeeType(), AlignSource);
3290 Base.getQuals().removeObjCGCAttr();
3291 } else if (E->getBase()->isGLValue()) {
3292 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
3293 // emit the base as an lvalue.
3294 assert(E->getBase()->getType()->isVectorType());
3295 Base = EmitLValue(E->getBase());
3297 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
3298 assert(E->getBase()->getType()->isVectorType() &&
3299 "Result must be a vector");
3300 llvm::Value *Vec = EmitScalarExpr(E->getBase());
3302 // Store the vector to memory (because LValue wants an address).
3303 Address VecMem = CreateMemTemp(E->getBase()->getType());
3304 Builder.CreateStore(Vec, VecMem);
3305 Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
3306 AlignmentSource::Decl);
3310 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
3312 // Encode the element access list into a vector of unsigned indices.
3313 SmallVector<uint32_t, 4> Indices;
3314 E->getEncodedElementAccess(Indices);
3316 if (Base.isSimple()) {
3317 llvm::Constant *CV =
3318 llvm::ConstantDataVector::get(getLLVMContext(), Indices);
3319 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
3320 Base.getAlignmentSource());
3322 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
3324 llvm::Constant *BaseElts = Base.getExtVectorElts();
3325 SmallVector<llvm::Constant *, 4> CElts;
3327 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
3328 CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
3329 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
3330 return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
3331 Base.getAlignmentSource());
3334 LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
3335 Expr *BaseExpr = E->getBase();
3337 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
3340 AlignmentSource AlignSource;
3341 Address Addr = EmitPointerWithAlignment(BaseExpr, &AlignSource);
3342 QualType PtrTy = BaseExpr->getType()->getPointeeType();
3343 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy);
3344 BaseLV = MakeAddrLValue(Addr, PtrTy, AlignSource);
3346 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
3348 NamedDecl *ND = E->getMemberDecl();
3349 if (auto *Field = dyn_cast<FieldDecl>(ND)) {
3350 LValue LV = EmitLValueForField(BaseLV, Field);
3351 setObjCGCLValueClass(getContext(), E, LV);
3355 if (auto *VD = dyn_cast<VarDecl>(ND))
3356 return EmitGlobalVarDeclLValue(*this, E, VD);
3358 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
3359 return EmitFunctionDeclLValue(*this, E, FD);
3361 llvm_unreachable("Unhandled member declaration!");
3364 /// Given that we are currently emitting a lambda, emit an l-value for
3365 /// one of its members.
3366 LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
3367 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
3368 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
3369 QualType LambdaTagType =
3370 getContext().getTagDeclType(Field->getParent());
3371 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
3372 return EmitLValueForField(LambdaLV, Field);
3375 /// Drill down to the storage of a field without walking into
3376 /// reference types.
3378 /// The resulting address doesn't necessarily have the right type.
3379 static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
3380 const FieldDecl *field) {
3381 const RecordDecl *rec = field->getParent();
3384 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
3387 // Adjust the alignment down to the given offset.
3388 // As a special case, if the LLVM field index is 0, we know that this
3390 assert((idx != 0 || CGF.getContext().getASTRecordLayout(rec)
3391 .getFieldOffset(field->getFieldIndex()) == 0) &&
3392 "LLVM field at index zero had non-zero offset?");
3394 auto &recLayout = CGF.getContext().getASTRecordLayout(rec);
3395 auto offsetInBits = recLayout.getFieldOffset(field->getFieldIndex());
3396 offset = CGF.getContext().toCharUnitsFromBits(offsetInBits);
3399 return CGF.Builder.CreateStructGEP(base, idx, offset, field->getName());
3402 LValue CodeGenFunction::EmitLValueForField(LValue base,
3403 const FieldDecl *field) {
3404 AlignmentSource fieldAlignSource =
3405 getFieldAlignmentSource(base.getAlignmentSource());
3407 if (field->isBitField()) {
3408 const CGRecordLayout &RL =
3409 CGM.getTypes().getCGRecordLayout(field->getParent());
3410 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
3411 Address Addr = base.getAddress();
3412 unsigned Idx = RL.getLLVMFieldNo(field);
3414 // For structs, we GEP to the field that the record layout suggests.
3415 Addr = Builder.CreateStructGEP(Addr, Idx, Info.StorageOffset,
3417 // Get the access type.
3418 llvm::Type *FieldIntTy =
3419 llvm::Type::getIntNTy(getLLVMContext(), Info.StorageSize);
3420 if (Addr.getElementType() != FieldIntTy)
3421 Addr = Builder.CreateElementBitCast(Addr, FieldIntTy);
3423 QualType fieldType =
3424 field->getType().withCVRQualifiers(base.getVRQualifiers());
3425 return LValue::MakeBitfield(Addr, Info, fieldType, fieldAlignSource);
3428 const RecordDecl *rec = field->getParent();
3429 QualType type = field->getType();
3431 bool mayAlias = rec->hasAttr<MayAliasAttr>();
3433 Address addr = base.getAddress();
3434 unsigned cvr = base.getVRQualifiers();
3435 bool TBAAPath = CGM.getCodeGenOpts().StructPathTBAA;
3436 if (rec->isUnion()) {
3437 // For unions, there is no pointer adjustment.
3438 assert(!type->isReferenceType() && "union has reference member");
3439 // TODO: handle path-aware TBAA for union.
3442 // For structs, we GEP to the field that the record layout suggests.
3443 addr = emitAddrOfFieldStorage(*this, addr, field);
3445 // If this is a reference field, load the reference right now.
3446 if (const ReferenceType *refType = type->getAs<ReferenceType>()) {
3447 llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
3448 if (cvr & Qualifiers::Volatile) load->setVolatile(true);
3450 // Loading the reference will disable path-aware TBAA.
3452 if (CGM.shouldUseTBAA()) {
3455 tbaa = CGM.getTBAAInfo(getContext().CharTy);
3457 tbaa = CGM.getTBAAInfo(type);
3459 CGM.DecorateInstructionWithTBAA(load, tbaa);
3463 type = refType->getPointeeType();
3465 CharUnits alignment =
3466 getNaturalTypeAlignment(type, &fieldAlignSource, /*pointee*/ true);
3467 addr = Address(load, alignment);
3469 // Qualifiers on the struct don't apply to the referencee, and
3470 // we'll pick up CVR from the actual type later, so reset these
3471 // additional qualifiers now.
3476 // Make sure that the address is pointing to the right type. This is critical
3477 // for both unions and structs. A union needs a bitcast, a struct element
3478 // will need a bitcast if the LLVM type laid out doesn't match the desired
3480 addr = Builder.CreateElementBitCast(addr,
3481 CGM.getTypes().ConvertTypeForMem(type),
3484 if (field->hasAttr<AnnotateAttr>())
3485 addr = EmitFieldAnnotations(field, addr);
3487 LValue LV = MakeAddrLValue(addr, type, fieldAlignSource);
3488 LV.getQuals().addCVRQualifiers(cvr);
3490 const ASTRecordLayout &Layout =
3491 getContext().getASTRecordLayout(field->getParent());
3492 // Set the base type to be the base type of the base LValue and
3493 // update offset to be relative to the base type.
3494 LV.setTBAABaseType(mayAlias ? getContext().CharTy : base.getTBAABaseType());
3495 LV.setTBAAOffset(mayAlias ? 0 : base.getTBAAOffset() +
3496 Layout.getFieldOffset(field->getFieldIndex()) /
3497 getContext().getCharWidth());
3500 // __weak attribute on a field is ignored.
3501 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
3502 LV.getQuals().removeObjCGCAttr();
3504 // Fields of may_alias structs act like 'char' for TBAA purposes.
3505 // FIXME: this should get propagated down through anonymous structs
3507 if (mayAlias && LV.getTBAAInfo())
3508 LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy));
3514 CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
3515 const FieldDecl *Field) {
3516 QualType FieldType = Field->getType();
3518 if (!FieldType->isReferenceType())
3519 return EmitLValueForField(Base, Field);
3521 Address V = emitAddrOfFieldStorage(*this, Base.getAddress(), Field);
3523 // Make sure that the address is pointing to the right type.
3524 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
3525 V = Builder.CreateElementBitCast(V, llvmType, Field->getName());
3527 // TODO: access-path TBAA?
3528 auto FieldAlignSource = getFieldAlignmentSource(Base.getAlignmentSource());
3529 return MakeAddrLValue(V, FieldType, FieldAlignSource);
3532 LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
3533 if (E->isFileScope()) {
3534 ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
3535 return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl);
3537 if (E->getType()->isVariablyModifiedType())
3538 // make sure to emit the VLA size.
3539 EmitVariablyModifiedType(E->getType());
3541 Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
3542 const Expr *InitExpr = E->getInitializer();
3543 LValue Result = MakeAddrLValue(DeclPtr, E->getType(), AlignmentSource::Decl);
3545 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
3551 LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
3552 if (!E->isGLValue())
3553 // Initializing an aggregate temporary in C++11: T{...}.
3554 return EmitAggExprToLValue(E);
3556 // An lvalue initializer list must be initializing a reference.
3557 assert(E->isTransparent() && "non-transparent glvalue init list");
3558 return EmitLValue(E->getInit(0));
3561 /// Emit the operand of a glvalue conditional operator. This is either a glvalue
3562 /// or a (possibly-parenthesized) throw-expression. If this is a throw, no
3563 /// LValue is returned and the current block has been terminated.
3564 static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
3565 const Expr *Operand) {
3566 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
3567 CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
3571 return CGF.EmitLValue(Operand);
3574 LValue CodeGenFunction::
3575 EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
3576 if (!expr->isGLValue()) {
3577 // ?: here should be an aggregate.
3578 assert(hasAggregateEvaluationKind(expr->getType()) &&
3579 "Unexpected conditional operator!");
3580 return EmitAggExprToLValue(expr);
3583 OpaqueValueMapping binding(*this, expr);
3585 const Expr *condExpr = expr->getCond();
3587 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
3588 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
3589 if (!CondExprBool) std::swap(live, dead);
3591 if (!ContainsLabel(dead)) {
3592 // If the true case is live, we need to track its region.
3594 incrementProfileCounter(expr);
3595 return EmitLValue(live);
3599 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
3600 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
3601 llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
3603 ConditionalEvaluation eval(*this);
3604 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr));
3606 // Any temporaries created here are conditional.
3607 EmitBlock(lhsBlock);
3608 incrementProfileCounter(expr);
3610 Optional<LValue> lhs =
3611 EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
3614 if (lhs && !lhs->isSimple())
3615 return EmitUnsupportedLValue(expr, "conditional operator");
3617 lhsBlock = Builder.GetInsertBlock();
3619 Builder.CreateBr(contBlock);
3621 // Any temporaries created here are conditional.
3622 EmitBlock(rhsBlock);
3624 Optional<LValue> rhs =
3625 EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
3627 if (rhs && !rhs->isSimple())
3628 return EmitUnsupportedLValue(expr, "conditional operator");
3629 rhsBlock = Builder.GetInsertBlock();
3631 EmitBlock(contBlock);
3634 llvm::PHINode *phi = Builder.CreatePHI(lhs->getPointer()->getType(),
3636 phi->addIncoming(lhs->getPointer(), lhsBlock);
3637 phi->addIncoming(rhs->getPointer(), rhsBlock);
3638 Address result(phi, std::min(lhs->getAlignment(), rhs->getAlignment()));
3639 AlignmentSource alignSource =
3640 std::max(lhs->getAlignmentSource(), rhs->getAlignmentSource());
3641 return MakeAddrLValue(result, expr->getType(), alignSource);
3643 assert((lhs || rhs) &&
3644 "both operands of glvalue conditional are throw-expressions?");
3645 return lhs ? *lhs : *rhs;
3649 /// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
3650 /// type. If the cast is to a reference, we can have the usual lvalue result,
3651 /// otherwise if a cast is needed by the code generator in an lvalue context,
3652 /// then it must mean that we need the address of an aggregate in order to
3653 /// access one of its members. This can happen for all the reasons that casts
3654 /// are permitted with aggregate result, including noop aggregate casts, and
3655 /// cast from scalar to union.
3656 LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
3657 switch (E->getCastKind()) {
3660 case CK_ArrayToPointerDecay:
3661 case CK_FunctionToPointerDecay:
3662 case CK_NullToMemberPointer:
3663 case CK_NullToPointer:
3664 case CK_IntegralToPointer:
3665 case CK_PointerToIntegral:
3666 case CK_PointerToBoolean:
3667 case CK_VectorSplat:
3668 case CK_IntegralCast:
3669 case CK_BooleanToSignedIntegral:
3670 case CK_IntegralToBoolean:
3671 case CK_IntegralToFloating:
3672 case CK_FloatingToIntegral:
3673 case CK_FloatingToBoolean:
3674 case CK_FloatingCast:
3675 case CK_FloatingRealToComplex:
3676 case CK_FloatingComplexToReal:
3677 case CK_FloatingComplexToBoolean:
3678 case CK_FloatingComplexCast:
3679 case CK_FloatingComplexToIntegralComplex:
3680 case CK_IntegralRealToComplex:
3681 case CK_IntegralComplexToReal:
3682 case CK_IntegralComplexToBoolean:
3683 case CK_IntegralComplexCast:
3684 case CK_IntegralComplexToFloatingComplex:
3685 case CK_DerivedToBaseMemberPointer:
3686 case CK_BaseToDerivedMemberPointer:
3687 case CK_MemberPointerToBoolean:
3688 case CK_ReinterpretMemberPointer:
3689 case CK_AnyPointerToBlockPointerCast:
3690 case CK_ARCProduceObject:
3691 case CK_ARCConsumeObject:
3692 case CK_ARCReclaimReturnedObject:
3693 case CK_ARCExtendBlockObject:
3694 case CK_CopyAndAutoreleaseBlockObject:
3695 case CK_AddressSpaceConversion:
3696 case CK_IntToOCLSampler:
3697 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
3700 llvm_unreachable("dependent cast kind in IR gen!");
3702 case CK_BuiltinFnToFnPtr:
3703 llvm_unreachable("builtin functions are handled elsewhere");
3705 // These are never l-values; just use the aggregate emission code.
3706 case CK_NonAtomicToAtomic:
3707 case CK_AtomicToNonAtomic:
3708 return EmitAggExprToLValue(E);
3711 LValue LV = EmitLValue(E->getSubExpr());
3712 Address V = LV.getAddress();
3713 const auto *DCE = cast<CXXDynamicCastExpr>(E);
3714 return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
3717 case CK_ConstructorConversion:
3718 case CK_UserDefinedConversion:
3719 case CK_CPointerToObjCPointerCast:
3720 case CK_BlockPointerToObjCPointerCast:
3722 case CK_LValueToRValue:
3723 return EmitLValue(E->getSubExpr());
3725 case CK_UncheckedDerivedToBase:
3726 case CK_DerivedToBase: {
3727 const RecordType *DerivedClassTy =
3728 E->getSubExpr()->getType()->getAs<RecordType>();
3729 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
3731 LValue LV = EmitLValue(E->getSubExpr());
3732 Address This = LV.getAddress();
3734 // Perform the derived-to-base conversion
3735 Address Base = GetAddressOfBaseClass(
3736 This, DerivedClassDecl, E->path_begin(), E->path_end(),
3737 /*NullCheckValue=*/false, E->getExprLoc());
3739 return MakeAddrLValue(Base, E->getType(), LV.getAlignmentSource());
3742 return EmitAggExprToLValue(E);
3743 case CK_BaseToDerived: {
3744 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
3745 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
3747 LValue LV = EmitLValue(E->getSubExpr());
3749 // Perform the base-to-derived conversion
3751 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
3752 E->path_begin(), E->path_end(),
3753 /*NullCheckValue=*/false);
3755 // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
3756 // performed and the object is not of the derived type.
3757 if (sanitizePerformTypeCheck())
3758 EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
3759 Derived.getPointer(), E->getType());
3761 if (SanOpts.has(SanitizerKind::CFIDerivedCast))
3762 EmitVTablePtrCheckForCast(E->getType(), Derived.getPointer(),
3763 /*MayBeNull=*/false,
3764 CFITCK_DerivedCast, E->getLocStart());
3766 return MakeAddrLValue(Derived, E->getType(), LV.getAlignmentSource());
3768 case CK_LValueBitCast: {
3769 // This must be a reinterpret_cast (or c-style equivalent).
3770 const auto *CE = cast<ExplicitCastExpr>(E);
3772 CGM.EmitExplicitCastExprType(CE, this);
3773 LValue LV = EmitLValue(E->getSubExpr());
3774 Address V = Builder.CreateBitCast(LV.getAddress(),
3775 ConvertType(CE->getTypeAsWritten()));
3777 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
3778 EmitVTablePtrCheckForCast(E->getType(), V.getPointer(),
3779 /*MayBeNull=*/false,
3780 CFITCK_UnrelatedCast, E->getLocStart());
3782 return MakeAddrLValue(V, E->getType(), LV.getAlignmentSource());
3784 case CK_ObjCObjectLValueCast: {
3785 LValue LV = EmitLValue(E->getSubExpr());
3786 Address V = Builder.CreateElementBitCast(LV.getAddress(),
3787 ConvertType(E->getType()));
3788 return MakeAddrLValue(V, E->getType(), LV.getAlignmentSource());
3790 case CK_ZeroToOCLQueue:
3791 llvm_unreachable("NULL to OpenCL queue lvalue cast is not valid");
3792 case CK_ZeroToOCLEvent:
3793 llvm_unreachable("NULL to OpenCL event lvalue cast is not valid");
3796 llvm_unreachable("Unhandled lvalue cast kind?");
3799 LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
3800 assert(OpaqueValueMappingData::shouldBindAsLValue(e));
3801 return getOpaqueLValueMapping(e);
3804 RValue CodeGenFunction::EmitRValueForField(LValue LV,
3805 const FieldDecl *FD,
3806 SourceLocation Loc) {
3807 QualType FT = FD->getType();
3808 LValue FieldLV = EmitLValueForField(LV, FD);
3809 switch (getEvaluationKind(FT)) {
3811 return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
3813 return FieldLV.asAggregateRValue();
3815 // This routine is used to load fields one-by-one to perform a copy, so
3816 // don't load reference fields.
3817 if (FD->getType()->isReferenceType())
3818 return RValue::get(FieldLV.getPointer());
3819 return EmitLoadOfLValue(FieldLV, Loc);
3821 llvm_unreachable("bad evaluation kind");
3824 //===--------------------------------------------------------------------===//
3825 // Expression Emission
3826 //===--------------------------------------------------------------------===//
3828 RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
3829 ReturnValueSlot ReturnValue) {
3830 // Builtins never have block type.
3831 if (E->getCallee()->getType()->isBlockPointerType())
3832 return EmitBlockCallExpr(E, ReturnValue);
3834 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
3835 return EmitCXXMemberCallExpr(CE, ReturnValue);
3837 if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
3838 return EmitCUDAKernelCallExpr(CE, ReturnValue);
3840 if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
3841 if (const CXXMethodDecl *MD =
3842 dyn_cast_or_null<CXXMethodDecl>(CE->getCalleeDecl()))
3843 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
3845 CGCallee callee = EmitCallee(E->getCallee());
3847 if (callee.isBuiltin()) {
3848 return EmitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(),
3852 if (callee.isPseudoDestructor()) {
3853 return EmitCXXPseudoDestructorExpr(callee.getPseudoDestructorExpr());
3856 return EmitCall(E->getCallee()->getType(), callee, E, ReturnValue);
3859 /// Emit a CallExpr without considering whether it might be a subclass.
3860 RValue CodeGenFunction::EmitSimpleCallExpr(const CallExpr *E,
3861 ReturnValueSlot ReturnValue) {
3862 CGCallee Callee = EmitCallee(E->getCallee());
3863 return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue);
3866 static CGCallee EmitDirectCallee(CodeGenFunction &CGF, const FunctionDecl *FD) {
3867 if (auto builtinID = FD->getBuiltinID()) {
3868 return CGCallee::forBuiltin(builtinID, FD);
3871 llvm::Constant *calleePtr = EmitFunctionDeclPointer(CGF.CGM, FD);
3872 return CGCallee::forDirect(calleePtr, FD);
3875 CGCallee CodeGenFunction::EmitCallee(const Expr *E) {
3876 E = E->IgnoreParens();
3878 // Look through function-to-pointer decay.
3879 if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) {
3880 if (ICE->getCastKind() == CK_FunctionToPointerDecay ||
3881 ICE->getCastKind() == CK_BuiltinFnToFnPtr) {
3882 return EmitCallee(ICE->getSubExpr());
3885 // Resolve direct calls.
3886 } else if (auto DRE = dyn_cast<DeclRefExpr>(E)) {
3887 if (auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
3888 return EmitDirectCallee(*this, FD);
3890 } else if (auto ME = dyn_cast<MemberExpr>(E)) {
3891 if (auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) {
3892 EmitIgnoredExpr(ME->getBase());
3893 return EmitDirectCallee(*this, FD);
3896 // Look through template substitutions.
3897 } else if (auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
3898 return EmitCallee(NTTP->getReplacement());
3900 // Treat pseudo-destructor calls differently.
3901 } else if (auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) {
3902 return CGCallee::forPseudoDestructor(PDE);
3905 // Otherwise, we have an indirect reference.
3906 llvm::Value *calleePtr;
3907 QualType functionType;
3908 if (auto ptrType = E->getType()->getAs<PointerType>()) {
3909 calleePtr = EmitScalarExpr(E);
3910 functionType = ptrType->getPointeeType();
3912 functionType = E->getType();
3913 calleePtr = EmitLValue(E).getPointer();
3915 assert(functionType->isFunctionType());
3916 CGCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(),
3917 E->getReferencedDeclOfCallee());
3918 CGCallee callee(calleeInfo, calleePtr);
3922 LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
3923 // Comma expressions just emit their LHS then their RHS as an l-value.
3924 if (E->getOpcode() == BO_Comma) {
3925 EmitIgnoredExpr(E->getLHS());
3926 EnsureInsertPoint();
3927 return EmitLValue(E->getRHS());
3930 if (E->getOpcode() == BO_PtrMemD ||
3931 E->getOpcode() == BO_PtrMemI)
3932 return EmitPointerToDataMemberBinaryExpr(E);
3934 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
3936 // Note that in all of these cases, __block variables need the RHS
3937 // evaluated first just in case the variable gets moved by the RHS.
3939 switch (getEvaluationKind(E->getType())) {
3941 switch (E->getLHS()->getType().getObjCLifetime()) {
3942 case Qualifiers::OCL_Strong:
3943 return EmitARCStoreStrong(E, /*ignored*/ false).first;
3945 case Qualifiers::OCL_Autoreleasing:
3946 return EmitARCStoreAutoreleasing(E).first;
3948 // No reason to do any of these differently.
3949 case Qualifiers::OCL_None:
3950 case Qualifiers::OCL_ExplicitNone:
3951 case Qualifiers::OCL_Weak:
3955 RValue RV = EmitAnyExpr(E->getRHS());
3956 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
3957 EmitStoreThroughLValue(RV, LV);
3962 return EmitComplexAssignmentLValue(E);
3965 return EmitAggExprToLValue(E);
3967 llvm_unreachable("bad evaluation kind");
3970 LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
3971 RValue RV = EmitCallExpr(E);
3974 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
3975 AlignmentSource::Decl);
3977 assert(E->getCallReturnType(getContext())->isReferenceType() &&
3978 "Can't have a scalar return unless the return type is a "
3981 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
3984 LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
3985 // FIXME: This shouldn't require another copy.
3986 return EmitAggExprToLValue(E);
3989 LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
3990 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
3991 && "binding l-value to type which needs a temporary");
3992 AggValueSlot Slot = CreateAggTemp(E->getType());
3993 EmitCXXConstructExpr(E, Slot);
3994 return MakeAddrLValue(Slot.getAddress(), E->getType(),
3995 AlignmentSource::Decl);
3999 CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
4000 return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType());
4003 Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
4004 return Builder.CreateElementBitCast(CGM.GetAddrOfUuidDescriptor(E),
4005 ConvertType(E->getType()));
4008 LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
4009 return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(),
4010 AlignmentSource::Decl);
4014 CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
4015 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
4016 Slot.setExternallyDestructed();
4017 EmitAggExpr(E->getSubExpr(), Slot);
4018 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
4019 return MakeAddrLValue(Slot.getAddress(), E->getType(),
4020 AlignmentSource::Decl);
4024 CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
4025 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
4026 EmitLambdaExpr(E, Slot);
4027 return MakeAddrLValue(Slot.getAddress(), E->getType(),
4028 AlignmentSource::Decl);
4031 LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
4032 RValue RV = EmitObjCMessageExpr(E);
4035 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
4036 AlignmentSource::Decl);
4038 assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
4039 "Can't have a scalar return unless the return type is a "
4042 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
4045 LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
4047 CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
4048 return MakeAddrLValue(V, E->getType(), AlignmentSource::Decl);
4051 llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
4052 const ObjCIvarDecl *Ivar) {
4053 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
4056 LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
4057 llvm::Value *BaseValue,
4058 const ObjCIvarDecl *Ivar,
4059 unsigned CVRQualifiers) {
4060 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
4061 Ivar, CVRQualifiers);
4064 LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
4065 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
4066 llvm::Value *BaseValue = nullptr;
4067 const Expr *BaseExpr = E->getBase();
4068 Qualifiers BaseQuals;
4071 BaseValue = EmitScalarExpr(BaseExpr);
4072 ObjectTy = BaseExpr->getType()->getPointeeType();
4073 BaseQuals = ObjectTy.getQualifiers();
4075 LValue BaseLV = EmitLValue(BaseExpr);
4076 BaseValue = BaseLV.getPointer();
4077 ObjectTy = BaseExpr->getType();
4078 BaseQuals = ObjectTy.getQualifiers();
4082 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
4083 BaseQuals.getCVRQualifiers());
4084 setObjCGCLValueClass(getContext(), E, LV);
4088 LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
4089 // Can only get l-value for message expression returning aggregate type
4090 RValue RV = EmitAnyExprToTemp(E);
4091 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
4092 AlignmentSource::Decl);
4095 RValue CodeGenFunction::EmitCall(QualType CalleeType, const CGCallee &OrigCallee,
4096 const CallExpr *E, ReturnValueSlot ReturnValue,
4097 llvm::Value *Chain) {
4098 // Get the actual function type. The callee type will always be a pointer to
4099 // function type or a block pointer type.
4100 assert(CalleeType->isFunctionPointerType() &&
4101 "Call must have function pointer type!");
4103 const Decl *TargetDecl = OrigCallee.getAbstractInfo().getCalleeDecl();
4105 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
4106 // We can only guarantee that a function is called from the correct
4107 // context/function based on the appropriate target attributes,
4108 // so only check in the case where we have both always_inline and target
4109 // since otherwise we could be making a conditional call after a check for
4110 // the proper cpu features (and it won't cause code generation issues due to
4111 // function based code generation).
4112 if (TargetDecl->hasAttr<AlwaysInlineAttr>() &&
4113 TargetDecl->hasAttr<TargetAttr>())
4114 checkTargetFeatures(E, FD);
4116 CalleeType = getContext().getCanonicalType(CalleeType);
4118 const auto *FnType =
4119 cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
4121 CGCallee Callee = OrigCallee;
4123 if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
4124 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4125 if (llvm::Constant *PrefixSig =
4126 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
4127 SanitizerScope SanScope(this);
4128 llvm::Constant *FTRTTIConst =
4129 CGM.GetAddrOfRTTIDescriptor(QualType(FnType, 0), /*ForEH=*/true);
4130 llvm::Type *PrefixStructTyElems[] = {
4131 PrefixSig->getType(),
4132 FTRTTIConst->getType()
4134 llvm::StructType *PrefixStructTy = llvm::StructType::get(
4135 CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true);
4137 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4139 llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
4140 CalleePtr, llvm::PointerType::getUnqual(PrefixStructTy));
4141 llvm::Value *CalleeSigPtr =
4142 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0);
4143 llvm::Value *CalleeSig =
4144 Builder.CreateAlignedLoad(CalleeSigPtr, getIntAlign());
4145 llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
4147 llvm::BasicBlock *Cont = createBasicBlock("cont");
4148 llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
4149 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
4151 EmitBlock(TypeCheck);
4152 llvm::Value *CalleeRTTIPtr =
4153 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1);
4154 llvm::Value *CalleeRTTI =
4155 Builder.CreateAlignedLoad(CalleeRTTIPtr, getPointerAlign());
4156 llvm::Value *CalleeRTTIMatch =
4157 Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
4158 llvm::Constant *StaticData[] = {
4159 EmitCheckSourceLocation(E->getLocStart()),
4160 EmitCheckTypeDescriptor(CalleeType)
4162 EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
4163 SanitizerHandler::FunctionTypeMismatch, StaticData, CalleePtr);
4165 Builder.CreateBr(Cont);
4170 // If we are checking indirect calls and this call is indirect, check that the
4171 // function pointer is a member of the bit set for the function type.
4172 if (SanOpts.has(SanitizerKind::CFIICall) &&
4173 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4174 SanitizerScope SanScope(this);
4175 EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
4177 llvm::Metadata *MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0));
4178 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
4180 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4181 llvm::Value *CastedCallee = Builder.CreateBitCast(CalleePtr, Int8PtrTy);
4182 llvm::Value *TypeTest = Builder.CreateCall(
4183 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedCallee, TypeId});
4185 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
4186 llvm::Constant *StaticData[] = {
4187 llvm::ConstantInt::get(Int8Ty, CFITCK_ICall),
4188 EmitCheckSourceLocation(E->getLocStart()),
4189 EmitCheckTypeDescriptor(QualType(FnType, 0)),
4191 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
4192 EmitCfiSlowPathCheck(SanitizerKind::CFIICall, TypeTest, CrossDsoTypeId,
4193 CastedCallee, StaticData);
4195 EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIICall),
4196 SanitizerHandler::CFICheckFail, StaticData,
4197 {CastedCallee, llvm::UndefValue::get(IntPtrTy)});
4203 Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
4204 CGM.getContext().VoidPtrTy);
4206 // C++17 requires that we evaluate arguments to a call using assignment syntax
4207 // right-to-left, and that we evaluate arguments to certain other operators
4208 // left-to-right. Note that we allow this to override the order dictated by
4209 // the calling convention on the MS ABI, which means that parameter
4210 // destruction order is not necessarily reverse construction order.
4211 // FIXME: Revisit this based on C++ committee response to unimplementability.
4212 EvaluationOrder Order = EvaluationOrder::Default;
4213 if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
4214 if (OCE->isAssignmentOp())
4215 Order = EvaluationOrder::ForceRightToLeft;
4217 switch (OCE->getOperator()) {
4219 case OO_GreaterGreater:
4224 Order = EvaluationOrder::ForceLeftToRight;
4232 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(),
4233 E->getDirectCallee(), /*ParamsToSkip*/ 0, Order);
4235 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
4236 Args, FnType, /*isChainCall=*/Chain);
4239 // If the expression that denotes the called function has a type
4240 // that does not include a prototype, [the default argument
4241 // promotions are performed]. If the number of arguments does not
4242 // equal the number of parameters, the behavior is undefined. If
4243 // the function is defined with a type that includes a prototype,
4244 // and either the prototype ends with an ellipsis (, ...) or the
4245 // types of the arguments after promotion are not compatible with
4246 // the types of the parameters, the behavior is undefined. If the
4247 // function is defined with a type that does not include a
4248 // prototype, and the types of the arguments after promotion are
4249 // not compatible with those of the parameters after promotion,
4250 // the behavior is undefined [except in some trivial cases].
4251 // That is, in the general case, we should assume that a call
4252 // through an unprototyped function type works like a *non-variadic*
4253 // call. The way we make this work is to cast to the exact type
4254 // of the promoted arguments.
4256 // Chain calls use this same code path to add the invisible chain parameter
4257 // to the function type.
4258 if (isa<FunctionNoProtoType>(FnType) || Chain) {
4259 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
4260 CalleeTy = CalleeTy->getPointerTo();
4262 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4263 CalleePtr = Builder.CreateBitCast(CalleePtr, CalleeTy, "callee.knr.cast");
4264 Callee.setFunctionPointer(CalleePtr);
4267 return EmitCall(FnInfo, Callee, ReturnValue, Args);
4270 LValue CodeGenFunction::
4271 EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
4272 Address BaseAddr = Address::invalid();
4273 if (E->getOpcode() == BO_PtrMemI) {
4274 BaseAddr = EmitPointerWithAlignment(E->getLHS());
4276 BaseAddr = EmitLValue(E->getLHS()).getAddress();
4279 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
4281 const MemberPointerType *MPT
4282 = E->getRHS()->getType()->getAs<MemberPointerType>();
4284 AlignmentSource AlignSource;
4285 Address MemberAddr =
4286 EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT,
4289 return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), AlignSource);
4292 /// Given the address of a temporary variable, produce an r-value of
4294 RValue CodeGenFunction::convertTempToRValue(Address addr,
4296 SourceLocation loc) {
4297 LValue lvalue = MakeAddrLValue(addr, type, AlignmentSource::Decl);
4298 switch (getEvaluationKind(type)) {
4300 return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
4302 return lvalue.asAggregateRValue();
4304 return RValue::get(EmitLoadOfScalar(lvalue, loc));
4306 llvm_unreachable("bad evaluation kind");
4309 void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
4310 assert(Val->getType()->isFPOrFPVectorTy());
4311 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
4314 llvm::MDBuilder MDHelper(getLLVMContext());
4315 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
4317 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
4321 struct LValueOrRValue {
4327 static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
4328 const PseudoObjectExpr *E,
4330 AggValueSlot slot) {
4331 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
4333 // Find the result expression, if any.
4334 const Expr *resultExpr = E->getResultExpr();
4335 LValueOrRValue result;
4337 for (PseudoObjectExpr::const_semantics_iterator
4338 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
4339 const Expr *semantic = *i;
4341 // If this semantic expression is an opaque value, bind it
4342 // to the result of its source expression.
4343 if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
4345 // If this is the result expression, we may need to evaluate
4346 // directly into the slot.
4347 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
4349 if (ov == resultExpr && ov->isRValue() && !forLValue &&
4350 CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
4351 CGF.EmitAggExpr(ov->getSourceExpr(), slot);
4353 LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
4354 AlignmentSource::Decl);
4355 opaqueData = OVMA::bind(CGF, ov, LV);
4356 result.RV = slot.asRValue();
4358 // Otherwise, emit as normal.
4360 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
4362 // If this is the result, also evaluate the result now.
4363 if (ov == resultExpr) {
4365 result.LV = CGF.EmitLValue(ov);
4367 result.RV = CGF.EmitAnyExpr(ov, slot);
4371 opaques.push_back(opaqueData);
4373 // Otherwise, if the expression is the result, evaluate it
4374 // and remember the result.
4375 } else if (semantic == resultExpr) {
4377 result.LV = CGF.EmitLValue(semantic);
4379 result.RV = CGF.EmitAnyExpr(semantic, slot);
4381 // Otherwise, evaluate the expression in an ignored context.
4383 CGF.EmitIgnoredExpr(semantic);
4387 // Unbind all the opaques now.
4388 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
4389 opaques[i].unbind(CGF);
4394 RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
4395 AggValueSlot slot) {
4396 return emitPseudoObjectExpr(*this, E, false, slot).RV;
4399 LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
4400 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;