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, CGM.getDataLayout().getAllocaAddrSpace(),
75 nullptr, Name, AllocaInsertPt);
78 /// CreateDefaultAlignTempAlloca - This creates an alloca with the
79 /// default alignment of the corresponding LLVM type, which is *not*
80 /// guaranteed to be related in any way to the expected alignment of
81 /// an AST type that might have been lowered to Ty.
82 Address CodeGenFunction::CreateDefaultAlignTempAlloca(llvm::Type *Ty,
85 CharUnits::fromQuantity(CGM.getDataLayout().getABITypeAlignment(Ty));
86 return CreateTempAlloca(Ty, Align, Name);
89 void CodeGenFunction::InitTempAlloca(Address Var, llvm::Value *Init) {
90 assert(isa<llvm::AllocaInst>(Var.getPointer()));
91 auto *Store = new llvm::StoreInst(Init, Var.getPointer());
92 Store->setAlignment(Var.getAlignment().getQuantity());
93 llvm::BasicBlock *Block = AllocaInsertPt->getParent();
94 Block->getInstList().insertAfter(AllocaInsertPt->getIterator(), Store);
97 Address CodeGenFunction::CreateIRTemp(QualType Ty, const Twine &Name) {
98 CharUnits Align = getContext().getTypeAlignInChars(Ty);
99 return CreateTempAlloca(ConvertType(Ty), Align, Name);
102 Address CodeGenFunction::CreateMemTemp(QualType Ty, const Twine &Name) {
103 // FIXME: Should we prefer the preferred type alignment here?
104 return CreateMemTemp(Ty, getContext().getTypeAlignInChars(Ty), Name);
107 Address CodeGenFunction::CreateMemTemp(QualType Ty, CharUnits Align,
109 return CreateTempAlloca(ConvertTypeForMem(Ty), Align, Name);
112 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
113 /// expression and compare the result against zero, returning an Int1Ty value.
114 llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
115 PGO.setCurrentStmt(E);
116 if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
117 llvm::Value *MemPtr = EmitScalarExpr(E);
118 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
121 QualType BoolTy = getContext().BoolTy;
122 SourceLocation Loc = E->getExprLoc();
123 if (!E->getType()->isAnyComplexType())
124 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy, Loc);
126 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(), BoolTy,
130 /// EmitIgnoredExpr - Emit code to compute the specified expression,
131 /// ignoring the result.
132 void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
134 return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
136 // Just emit it as an l-value and drop the result.
140 /// EmitAnyExpr - Emit code to compute the specified expression which
141 /// can have any type. The result is returned as an RValue struct.
142 /// If this is an aggregate expression, AggSlot indicates where the
143 /// result should be returned.
144 RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
145 AggValueSlot aggSlot,
147 switch (getEvaluationKind(E->getType())) {
149 return RValue::get(EmitScalarExpr(E, ignoreResult));
151 return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
153 if (!ignoreResult && aggSlot.isIgnored())
154 aggSlot = CreateAggTemp(E->getType(), "agg-temp");
155 EmitAggExpr(E, aggSlot);
156 return aggSlot.asRValue();
158 llvm_unreachable("bad evaluation kind");
161 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
162 /// always be accessible even if no aggregate location is provided.
163 RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
164 AggValueSlot AggSlot = AggValueSlot::ignored();
166 if (hasAggregateEvaluationKind(E->getType()))
167 AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
168 return EmitAnyExpr(E, AggSlot);
171 /// EmitAnyExprToMem - Evaluate an expression into a given memory
173 void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
177 // FIXME: This function should take an LValue as an argument.
178 switch (getEvaluationKind(E->getType())) {
180 EmitComplexExprIntoLValue(E, MakeAddrLValue(Location, E->getType()),
184 case TEK_Aggregate: {
185 EmitAggExpr(E, AggValueSlot::forAddr(Location, Quals,
186 AggValueSlot::IsDestructed_t(IsInit),
187 AggValueSlot::DoesNotNeedGCBarriers,
188 AggValueSlot::IsAliased_t(!IsInit)));
193 RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
194 LValue LV = MakeAddrLValue(Location, E->getType());
195 EmitStoreThroughLValue(RV, LV);
199 llvm_unreachable("bad evaluation kind");
203 pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M,
204 const Expr *E, Address ReferenceTemporary) {
205 // Objective-C++ ARC:
206 // If we are binding a reference to a temporary that has ownership, we
207 // need to perform retain/release operations on the temporary.
209 // FIXME: This should be looking at E, not M.
210 if (auto Lifetime = M->getType().getObjCLifetime()) {
212 case Qualifiers::OCL_None:
213 case Qualifiers::OCL_ExplicitNone:
214 // Carry on to normal cleanup handling.
217 case Qualifiers::OCL_Autoreleasing:
218 // Nothing to do; cleaned up by an autorelease pool.
221 case Qualifiers::OCL_Strong:
222 case Qualifiers::OCL_Weak:
223 switch (StorageDuration Duration = M->getStorageDuration()) {
225 // Note: we intentionally do not register a cleanup to release
226 // the object on program termination.
230 // FIXME: We should probably register a cleanup in this case.
234 case SD_FullExpression:
235 CodeGenFunction::Destroyer *Destroy;
236 CleanupKind CleanupKind;
237 if (Lifetime == Qualifiers::OCL_Strong) {
238 const ValueDecl *VD = M->getExtendingDecl();
240 VD && isa<VarDecl>(VD) && VD->hasAttr<ObjCPreciseLifetimeAttr>();
241 CleanupKind = CGF.getARCCleanupKind();
242 Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise
243 : &CodeGenFunction::destroyARCStrongImprecise;
245 // __weak objects always get EH cleanups; otherwise, exceptions
246 // could cause really nasty crashes instead of mere leaks.
247 CleanupKind = NormalAndEHCleanup;
248 Destroy = &CodeGenFunction::destroyARCWeak;
250 if (Duration == SD_FullExpression)
251 CGF.pushDestroy(CleanupKind, ReferenceTemporary,
252 M->getType(), *Destroy,
253 CleanupKind & EHCleanup);
255 CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
257 *Destroy, CleanupKind & EHCleanup);
261 llvm_unreachable("temporary cannot have dynamic storage duration");
263 llvm_unreachable("unknown storage duration");
267 CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
268 if (const RecordType *RT =
269 E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
270 // Get the destructor for the reference temporary.
271 auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
272 if (!ClassDecl->hasTrivialDestructor())
273 ReferenceTemporaryDtor = ClassDecl->getDestructor();
276 if (!ReferenceTemporaryDtor)
279 // Call the destructor for the temporary.
280 switch (M->getStorageDuration()) {
283 llvm::Constant *CleanupFn;
284 llvm::Constant *CleanupArg;
285 if (E->getType()->isArrayType()) {
286 CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper(
287 ReferenceTemporary, E->getType(),
288 CodeGenFunction::destroyCXXObject, CGF.getLangOpts().Exceptions,
289 dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
290 CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
292 CleanupFn = CGF.CGM.getAddrOfCXXStructor(ReferenceTemporaryDtor,
293 StructorType::Complete);
294 CleanupArg = cast<llvm::Constant>(ReferenceTemporary.getPointer());
296 CGF.CGM.getCXXABI().registerGlobalDtor(
297 CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
301 case SD_FullExpression:
302 CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(),
303 CodeGenFunction::destroyCXXObject,
304 CGF.getLangOpts().Exceptions);
308 CGF.pushLifetimeExtendedDestroy(NormalAndEHCleanup,
309 ReferenceTemporary, E->getType(),
310 CodeGenFunction::destroyCXXObject,
311 CGF.getLangOpts().Exceptions);
315 llvm_unreachable("temporary cannot have dynamic storage duration");
320 createReferenceTemporary(CodeGenFunction &CGF,
321 const MaterializeTemporaryExpr *M, const Expr *Inner) {
322 switch (M->getStorageDuration()) {
323 case SD_FullExpression:
325 // If we have a constant temporary array or record try to promote it into a
326 // constant global under the same rules a normal constant would've been
327 // promoted. This is easier on the optimizer and generally emits fewer
329 QualType Ty = Inner->getType();
330 if (CGF.CGM.getCodeGenOpts().MergeAllConstants &&
331 (Ty->isArrayType() || Ty->isRecordType()) &&
332 CGF.CGM.isTypeConstant(Ty, true))
333 if (llvm::Constant *Init = CGF.CGM.EmitConstantExpr(Inner, Ty, &CGF)) {
334 auto *GV = new llvm::GlobalVariable(
335 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
336 llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp");
337 CharUnits alignment = CGF.getContext().getTypeAlignInChars(Ty);
338 GV->setAlignment(alignment.getQuantity());
339 // FIXME: Should we put the new global into a COMDAT?
340 return Address(GV, alignment);
342 return CGF.CreateMemTemp(Ty, "ref.tmp");
346 return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
349 llvm_unreachable("temporary can't have dynamic storage duration");
351 llvm_unreachable("unknown storage duration");
354 LValue CodeGenFunction::
355 EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *M) {
356 const Expr *E = M->GetTemporaryExpr();
358 // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
359 // as that will cause the lifetime adjustment to be lost for ARC
360 auto ownership = M->getType().getObjCLifetime();
361 if (ownership != Qualifiers::OCL_None &&
362 ownership != Qualifiers::OCL_ExplicitNone) {
363 Address Object = createReferenceTemporary(*this, M, E);
364 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
365 Object = Address(llvm::ConstantExpr::getBitCast(Var,
366 ConvertTypeForMem(E->getType())
367 ->getPointerTo(Object.getAddressSpace())),
368 Object.getAlignment());
370 // createReferenceTemporary will promote the temporary to a global with a
371 // constant initializer if it can. It can only do this to a value of
372 // ARC-manageable type if the value is global and therefore "immune" to
373 // ref-counting operations. Therefore we have no need to emit either a
374 // dynamic initialization or a cleanup and we can just return the address
376 if (Var->hasInitializer())
377 return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
379 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
381 LValue RefTempDst = MakeAddrLValue(Object, M->getType(),
382 AlignmentSource::Decl);
384 switch (getEvaluationKind(E->getType())) {
385 default: llvm_unreachable("expected scalar or aggregate expression");
387 EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
389 case TEK_Aggregate: {
390 EmitAggExpr(E, AggValueSlot::forAddr(Object,
391 E->getType().getQualifiers(),
392 AggValueSlot::IsDestructed,
393 AggValueSlot::DoesNotNeedGCBarriers,
394 AggValueSlot::IsNotAliased));
399 pushTemporaryCleanup(*this, M, E, Object);
403 SmallVector<const Expr *, 2> CommaLHSs;
404 SmallVector<SubobjectAdjustment, 2> Adjustments;
405 E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
407 for (const auto &Ignored : CommaLHSs)
408 EmitIgnoredExpr(Ignored);
410 if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
411 if (opaque->getType()->isRecordType()) {
412 assert(Adjustments.empty());
413 return EmitOpaqueValueLValue(opaque);
417 // Create and initialize the reference temporary.
418 Address Object = createReferenceTemporary(*this, M, E);
419 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
420 Object = Address(llvm::ConstantExpr::getBitCast(
421 Var, ConvertTypeForMem(E->getType())->getPointerTo()),
422 Object.getAlignment());
423 // If the temporary is a global and has a constant initializer or is a
424 // constant temporary that we promoted to a global, we may have already
426 if (!Var->hasInitializer()) {
427 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
428 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
431 switch (M->getStorageDuration()) {
433 case SD_FullExpression:
434 if (auto *Size = EmitLifetimeStart(
435 CGM.getDataLayout().getTypeAllocSize(Object.getElementType()),
436 Object.getPointer())) {
437 if (M->getStorageDuration() == SD_Automatic)
438 pushCleanupAfterFullExpr<CallLifetimeEnd>(NormalEHLifetimeMarker,
441 pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, Object,
448 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
450 pushTemporaryCleanup(*this, M, E, Object);
452 // Perform derived-to-base casts and/or field accesses, to get from the
453 // temporary object we created (and, potentially, for which we extended
454 // the lifetime) to the subobject we're binding the reference to.
455 for (unsigned I = Adjustments.size(); I != 0; --I) {
456 SubobjectAdjustment &Adjustment = Adjustments[I-1];
457 switch (Adjustment.Kind) {
458 case SubobjectAdjustment::DerivedToBaseAdjustment:
460 GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
461 Adjustment.DerivedToBase.BasePath->path_begin(),
462 Adjustment.DerivedToBase.BasePath->path_end(),
463 /*NullCheckValue=*/ false, E->getExprLoc());
466 case SubobjectAdjustment::FieldAdjustment: {
467 LValue LV = MakeAddrLValue(Object, E->getType(),
468 AlignmentSource::Decl);
469 LV = EmitLValueForField(LV, Adjustment.Field);
470 assert(LV.isSimple() &&
471 "materialized temporary field is not a simple lvalue");
472 Object = LV.getAddress();
476 case SubobjectAdjustment::MemberPointerAdjustment: {
477 llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
478 Object = EmitCXXMemberDataPointerAddress(E, Object, Ptr,
485 return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
489 CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) {
490 // Emit the expression as an lvalue.
491 LValue LV = EmitLValue(E);
492 assert(LV.isSimple());
493 llvm::Value *Value = LV.getPointer();
495 if (sanitizePerformTypeCheck() && !E->getType()->isFunctionType()) {
496 // C++11 [dcl.ref]p5 (as amended by core issue 453):
497 // If a glvalue to which a reference is directly bound designates neither
498 // an existing object or function of an appropriate type nor a region of
499 // storage of suitable size and alignment to contain an object of the
500 // reference's type, the behavior is undefined.
501 QualType Ty = E->getType();
502 EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
505 return RValue::get(Value);
509 /// getAccessedFieldNo - Given an encoded value and a result number, return the
510 /// input field number being accessed.
511 unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
512 const llvm::Constant *Elts) {
513 return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
517 /// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
518 static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
520 llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
521 llvm::Value *K47 = Builder.getInt64(47);
522 llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
523 llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
524 llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
525 llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
526 return Builder.CreateMul(B1, KMul);
529 bool CodeGenFunction::sanitizePerformTypeCheck() const {
530 return SanOpts.has(SanitizerKind::Null) |
531 SanOpts.has(SanitizerKind::Alignment) |
532 SanOpts.has(SanitizerKind::ObjectSize) |
533 SanOpts.has(SanitizerKind::Vptr);
536 /// Check if a runtime null check for \p Ptr can be omitted.
537 static bool canOmitPointerNullCheck(llvm::Value *Ptr) {
538 // Note: do not perform any constant-folding in this function. That is best
539 // left to the IR builder.
541 // Pointers to alloca'd memory are non-null.
542 return isa<llvm::AllocaInst>(Ptr->stripPointerCastsNoFollowAliases());
545 void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
546 llvm::Value *Ptr, QualType Ty,
548 SanitizerSet SkippedChecks) {
549 if (!sanitizePerformTypeCheck())
552 // Don't check pointers outside the default address space. The null check
553 // isn't correct, the object-size check isn't supported by LLVM, and we can't
554 // communicate the addresses to the runtime handler for the vptr check.
555 if (Ptr->getType()->getPointerAddressSpace())
558 SanitizerScope SanScope(this);
560 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 3> Checks;
561 llvm::BasicBlock *Done = nullptr;
563 bool AllowNullPointers = TCK == TCK_DowncastPointer || TCK == TCK_Upcast ||
564 TCK == TCK_UpcastToVirtualBase;
565 if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
566 !SkippedChecks.has(SanitizerKind::Null) &&
567 !canOmitPointerNullCheck(Ptr)) {
568 // The glvalue must not be an empty glvalue.
569 llvm::Value *IsNonNull = Builder.CreateIsNotNull(Ptr);
571 if (AllowNullPointers) {
572 // When performing pointer casts, it's OK if the value is null.
573 // Skip the remaining checks in that case.
574 Done = createBasicBlock("null");
575 llvm::BasicBlock *Rest = createBasicBlock("not.null");
576 Builder.CreateCondBr(IsNonNull, Rest, Done);
579 Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null));
583 if (SanOpts.has(SanitizerKind::ObjectSize) &&
584 !SkippedChecks.has(SanitizerKind::ObjectSize) &&
585 !Ty->isIncompleteType()) {
586 uint64_t Size = getContext().getTypeSizeInChars(Ty).getQuantity();
588 // The glvalue must refer to a large enough storage region.
589 // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
591 // FIXME: Get object address space
592 llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
593 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
594 llvm::Value *Min = Builder.getFalse();
595 llvm::Value *NullIsUnknown = Builder.getFalse();
596 llvm::Value *CastAddr = Builder.CreateBitCast(Ptr, Int8PtrTy);
597 llvm::Value *LargeEnough = Builder.CreateICmpUGE(
598 Builder.CreateCall(F, {CastAddr, Min, NullIsUnknown}),
599 llvm::ConstantInt::get(IntPtrTy, Size));
600 Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
603 uint64_t AlignVal = 0;
605 if (SanOpts.has(SanitizerKind::Alignment) &&
606 !SkippedChecks.has(SanitizerKind::Alignment)) {
607 AlignVal = Alignment.getQuantity();
608 if (!Ty->isIncompleteType() && !AlignVal)
609 AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity();
611 // The glvalue must be suitably aligned.
614 Builder.CreateAnd(Builder.CreatePtrToInt(Ptr, IntPtrTy),
615 llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
616 llvm::Value *Aligned =
617 Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
618 Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
622 if (Checks.size() > 0) {
623 // Make sure we're not losing information. Alignment needs to be a power of
625 assert(!AlignVal || (uint64_t)1 << llvm::Log2_64(AlignVal) == AlignVal);
626 llvm::Constant *StaticData[] = {
627 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(Ty),
628 llvm::ConstantInt::get(Int8Ty, AlignVal ? llvm::Log2_64(AlignVal) : 1),
629 llvm::ConstantInt::get(Int8Ty, TCK)};
630 EmitCheck(Checks, SanitizerHandler::TypeMismatch, StaticData, Ptr);
633 // If possible, check that the vptr indicates that there is a subobject of
634 // type Ty at offset zero within this object.
636 // C++11 [basic.life]p5,6:
637 // [For storage which does not refer to an object within its lifetime]
638 // The program has undefined behavior if:
639 // -- the [pointer or glvalue] is used to access a non-static data member
640 // or call a non-static member function
641 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
642 if (SanOpts.has(SanitizerKind::Vptr) &&
643 !SkippedChecks.has(SanitizerKind::Vptr) &&
644 (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
645 TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
646 TCK == TCK_UpcastToVirtualBase) &&
647 RD && RD->hasDefinition() && RD->isDynamicClass()) {
648 // Compute a hash of the mangled name of the type.
650 // FIXME: This is not guaranteed to be deterministic! Move to a
651 // fingerprinting mechanism once LLVM provides one. For the time
652 // being the implementation happens to be deterministic.
653 SmallString<64> MangledName;
654 llvm::raw_svector_ostream Out(MangledName);
655 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
658 // Blacklist based on the mangled type.
659 if (!CGM.getContext().getSanitizerBlacklist().isBlacklistedType(
661 llvm::hash_code TypeHash = hash_value(Out.str());
663 // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
664 llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
665 llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
666 Address VPtrAddr(Builder.CreateBitCast(Ptr, VPtrTy), getPointerAlign());
667 llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
668 llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
670 llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
671 Hash = Builder.CreateTrunc(Hash, IntPtrTy);
673 // Look the hash up in our cache.
674 const int CacheSize = 128;
675 llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
676 llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
677 "__ubsan_vptr_type_cache");
678 llvm::Value *Slot = Builder.CreateAnd(Hash,
679 llvm::ConstantInt::get(IntPtrTy,
681 llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
682 llvm::Value *CacheVal =
683 Builder.CreateAlignedLoad(Builder.CreateInBoundsGEP(Cache, Indices),
686 // If the hash isn't in the cache, call a runtime handler to perform the
687 // hard work of checking whether the vptr is for an object of the right
688 // type. This will either fill in the cache and return, or produce a
690 llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
691 llvm::Constant *StaticData[] = {
692 EmitCheckSourceLocation(Loc),
693 EmitCheckTypeDescriptor(Ty),
694 CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
695 llvm::ConstantInt::get(Int8Ty, TCK)
697 llvm::Value *DynamicData[] = { Ptr, Hash };
698 EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
699 SanitizerHandler::DynamicTypeCacheMiss, StaticData,
705 Builder.CreateBr(Done);
710 /// Determine whether this expression refers to a flexible array member in a
711 /// struct. We disable array bounds checks for such members.
712 static bool isFlexibleArrayMemberExpr(const Expr *E) {
713 // For compatibility with existing code, we treat arrays of length 0 or
714 // 1 as flexible array members.
715 const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe();
716 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
717 if (CAT->getSize().ugt(1))
719 } else if (!isa<IncompleteArrayType>(AT))
722 E = E->IgnoreParens();
724 // A flexible array member must be the last member in the class.
725 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
726 // FIXME: If the base type of the member expr is not FD->getParent(),
727 // this should not be treated as a flexible array member access.
728 if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
729 RecordDecl::field_iterator FI(
730 DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
731 return ++FI == FD->getParent()->field_end();
733 } else if (const auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) {
734 return IRE->getDecl()->getNextIvar() == nullptr;
740 /// If Base is known to point to the start of an array, return the length of
741 /// that array. Return 0 if the length cannot be determined.
742 static llvm::Value *getArrayIndexingBound(
743 CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType) {
744 // For the vector indexing extension, the bound is the number of elements.
745 if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
746 IndexedType = Base->getType();
747 return CGF.Builder.getInt32(VT->getNumElements());
750 Base = Base->IgnoreParens();
752 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
753 if (CE->getCastKind() == CK_ArrayToPointerDecay &&
754 !isFlexibleArrayMemberExpr(CE->getSubExpr())) {
755 IndexedType = CE->getSubExpr()->getType();
756 const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
757 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
758 return CGF.Builder.getInt(CAT->getSize());
759 else if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
760 return CGF.getVLASize(VAT).first;
767 void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
768 llvm::Value *Index, QualType IndexType,
770 assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
771 "should not be called unless adding bounds checks");
772 SanitizerScope SanScope(this);
774 QualType IndexedType;
775 llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType);
779 bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
780 llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
781 llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
783 llvm::Constant *StaticData[] = {
784 EmitCheckSourceLocation(E->getExprLoc()),
785 EmitCheckTypeDescriptor(IndexedType),
786 EmitCheckTypeDescriptor(IndexType)
788 llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
789 : Builder.CreateICmpULE(IndexVal, BoundVal);
790 EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds),
791 SanitizerHandler::OutOfBounds, StaticData, Index);
795 CodeGenFunction::ComplexPairTy CodeGenFunction::
796 EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
797 bool isInc, bool isPre) {
798 ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
800 llvm::Value *NextVal;
801 if (isa<llvm::IntegerType>(InVal.first->getType())) {
802 uint64_t AmountVal = isInc ? 1 : -1;
803 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
805 // Add the inc/dec to the real part.
806 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
808 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
809 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
812 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
814 // Add the inc/dec to the real part.
815 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
818 ComplexPairTy IncVal(NextVal, InVal.second);
820 // Store the updated result through the lvalue.
821 EmitStoreOfComplex(IncVal, LV, /*init*/ false);
823 // If this is a postinc, return the value read from memory, otherwise use the
825 return isPre ? IncVal : InVal;
828 void CodeGenModule::EmitExplicitCastExprType(const ExplicitCastExpr *E,
829 CodeGenFunction *CGF) {
830 // Bind VLAs in the cast type.
831 if (CGF && E->getType()->isVariablyModifiedType())
832 CGF->EmitVariablyModifiedType(E->getType());
834 if (CGDebugInfo *DI = getModuleDebugInfo())
835 DI->EmitExplicitCastType(E->getType());
838 //===----------------------------------------------------------------------===//
839 // LValue Expression Emission
840 //===----------------------------------------------------------------------===//
842 /// EmitPointerWithAlignment - Given an expression of pointer type, try to
843 /// derive a more accurate bound on the alignment of the pointer.
844 Address CodeGenFunction::EmitPointerWithAlignment(const Expr *E,
845 AlignmentSource *Source) {
846 // We allow this with ObjC object pointers because of fragile ABIs.
847 assert(E->getType()->isPointerType() ||
848 E->getType()->isObjCObjectPointerType());
849 E = E->IgnoreParens();
852 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
853 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
854 CGM.EmitExplicitCastExprType(ECE, this);
856 switch (CE->getCastKind()) {
857 // Non-converting casts (but not C's implicit conversion from void*).
860 if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) {
861 if (PtrTy->getPointeeType()->isVoidType())
864 AlignmentSource InnerSource;
865 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), &InnerSource);
866 if (Source) *Source = InnerSource;
868 // If this is an explicit bitcast, and the source l-value is
869 // opaque, honor the alignment of the casted-to type.
870 if (isa<ExplicitCastExpr>(CE) &&
871 InnerSource != AlignmentSource::Decl) {
872 Addr = Address(Addr.getPointer(),
873 getNaturalPointeeTypeAlignment(E->getType(), Source));
876 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast) &&
877 CE->getCastKind() == CK_BitCast) {
878 if (auto PT = E->getType()->getAs<PointerType>())
879 EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr.getPointer(),
881 CodeGenFunction::CFITCK_UnrelatedCast,
885 return Builder.CreateBitCast(Addr, ConvertType(E->getType()));
889 // Array-to-pointer decay.
890 case CK_ArrayToPointerDecay:
891 return EmitArrayToPointerDecay(CE->getSubExpr(), Source);
893 // Derived-to-base conversions.
894 case CK_UncheckedDerivedToBase:
895 case CK_DerivedToBase: {
896 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), Source);
897 auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
898 return GetAddressOfBaseClass(Addr, Derived,
899 CE->path_begin(), CE->path_end(),
900 ShouldNullCheckClassCastValue(CE),
904 // TODO: Is there any reason to treat base-to-derived conversions
912 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
913 if (UO->getOpcode() == UO_AddrOf) {
914 LValue LV = EmitLValue(UO->getSubExpr());
915 if (Source) *Source = LV.getAlignmentSource();
916 return LV.getAddress();
920 // TODO: conditional operators, comma.
922 // Otherwise, use the alignment of the type.
923 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(), Source);
924 return Address(EmitScalarExpr(E), Align);
927 RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
928 if (Ty->isVoidType())
929 return RValue::get(nullptr);
931 switch (getEvaluationKind(Ty)) {
934 ConvertType(Ty->castAs<ComplexType>()->getElementType());
935 llvm::Value *U = llvm::UndefValue::get(EltTy);
936 return RValue::getComplex(std::make_pair(U, U));
939 // If this is a use of an undefined aggregate type, the aggregate must have an
940 // identifiable address. Just because the contents of the value are undefined
941 // doesn't mean that the address can't be taken and compared.
942 case TEK_Aggregate: {
943 Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
944 return RValue::getAggregate(DestPtr);
948 return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
950 llvm_unreachable("bad evaluation kind");
953 RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
955 ErrorUnsupported(E, Name);
956 return GetUndefRValue(E->getType());
959 LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
961 ErrorUnsupported(E, Name);
962 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
963 return MakeAddrLValue(Address(llvm::UndefValue::get(Ty), CharUnits::One()),
967 bool CodeGenFunction::IsWrappedCXXThis(const Expr *Obj) {
968 const Expr *Base = Obj;
969 while (!isa<CXXThisExpr>(Base)) {
970 // The result of a dynamic_cast can be null.
971 if (isa<CXXDynamicCastExpr>(Base))
974 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
975 Base = CE->getSubExpr();
976 } else if (const auto *PE = dyn_cast<ParenExpr>(Base)) {
977 Base = PE->getSubExpr();
978 } else if (const auto *UO = dyn_cast<UnaryOperator>(Base)) {
979 if (UO->getOpcode() == UO_Extension)
980 Base = UO->getSubExpr();
990 LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
992 if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
993 LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
996 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple()) {
997 SanitizerSet SkippedChecks;
998 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
999 bool IsBaseCXXThis = IsWrappedCXXThis(ME->getBase());
1001 SkippedChecks.set(SanitizerKind::Alignment, true);
1002 if (IsBaseCXXThis || isa<DeclRefExpr>(ME->getBase()))
1003 SkippedChecks.set(SanitizerKind::Null, true);
1005 EmitTypeCheck(TCK, E->getExprLoc(), LV.getPointer(),
1006 E->getType(), LV.getAlignment(), SkippedChecks);
1011 /// EmitLValue - Emit code to compute a designator that specifies the location
1012 /// of the expression.
1014 /// This can return one of two things: a simple address or a bitfield reference.
1015 /// In either case, the LLVM Value* in the LValue structure is guaranteed to be
1016 /// an LLVM pointer type.
1018 /// If this returns a bitfield reference, nothing about the pointee type of the
1019 /// LLVM value is known: For example, it may not be a pointer to an integer.
1021 /// If this returns a normal address, and if the lvalue's C type is fixed size,
1022 /// this method guarantees that the returned pointer type will point to an LLVM
1023 /// type of the same size of the lvalue's type. If the lvalue has a variable
1024 /// length type, this is not possible.
1026 LValue CodeGenFunction::EmitLValue(const Expr *E) {
1027 ApplyDebugLocation DL(*this, E);
1028 switch (E->getStmtClass()) {
1029 default: return EmitUnsupportedLValue(E, "l-value expression");
1031 case Expr::ObjCPropertyRefExprClass:
1032 llvm_unreachable("cannot emit a property reference directly");
1034 case Expr::ObjCSelectorExprClass:
1035 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
1036 case Expr::ObjCIsaExprClass:
1037 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
1038 case Expr::BinaryOperatorClass:
1039 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
1040 case Expr::CompoundAssignOperatorClass: {
1041 QualType Ty = E->getType();
1042 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1043 Ty = AT->getValueType();
1044 if (!Ty->isAnyComplexType())
1045 return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
1046 return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
1048 case Expr::CallExprClass:
1049 case Expr::CXXMemberCallExprClass:
1050 case Expr::CXXOperatorCallExprClass:
1051 case Expr::UserDefinedLiteralClass:
1052 return EmitCallExprLValue(cast<CallExpr>(E));
1053 case Expr::VAArgExprClass:
1054 return EmitVAArgExprLValue(cast<VAArgExpr>(E));
1055 case Expr::DeclRefExprClass:
1056 return EmitDeclRefLValue(cast<DeclRefExpr>(E));
1057 case Expr::ParenExprClass:
1058 return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
1059 case Expr::GenericSelectionExprClass:
1060 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
1061 case Expr::PredefinedExprClass:
1062 return EmitPredefinedLValue(cast<PredefinedExpr>(E));
1063 case Expr::StringLiteralClass:
1064 return EmitStringLiteralLValue(cast<StringLiteral>(E));
1065 case Expr::ObjCEncodeExprClass:
1066 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
1067 case Expr::PseudoObjectExprClass:
1068 return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
1069 case Expr::InitListExprClass:
1070 return EmitInitListLValue(cast<InitListExpr>(E));
1071 case Expr::CXXTemporaryObjectExprClass:
1072 case Expr::CXXConstructExprClass:
1073 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
1074 case Expr::CXXBindTemporaryExprClass:
1075 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
1076 case Expr::CXXUuidofExprClass:
1077 return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
1078 case Expr::LambdaExprClass:
1079 return EmitLambdaLValue(cast<LambdaExpr>(E));
1081 case Expr::ExprWithCleanupsClass: {
1082 const auto *cleanups = cast<ExprWithCleanups>(E);
1083 enterFullExpression(cleanups);
1084 RunCleanupsScope Scope(*this);
1085 LValue LV = EmitLValue(cleanups->getSubExpr());
1086 if (LV.isSimple()) {
1087 // Defend against branches out of gnu statement expressions surrounded by
1089 llvm::Value *V = LV.getPointer();
1090 Scope.ForceCleanup({&V});
1091 return LValue::MakeAddr(Address(V, LV.getAlignment()), LV.getType(),
1092 getContext(), LV.getAlignmentSource(),
1095 // FIXME: Is it possible to create an ExprWithCleanups that produces a
1096 // bitfield lvalue or some other non-simple lvalue?
1100 case Expr::CXXDefaultArgExprClass:
1101 return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
1102 case Expr::CXXDefaultInitExprClass: {
1103 CXXDefaultInitExprScope Scope(*this);
1104 return EmitLValue(cast<CXXDefaultInitExpr>(E)->getExpr());
1106 case Expr::CXXTypeidExprClass:
1107 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
1109 case Expr::ObjCMessageExprClass:
1110 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
1111 case Expr::ObjCIvarRefExprClass:
1112 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
1113 case Expr::StmtExprClass:
1114 return EmitStmtExprLValue(cast<StmtExpr>(E));
1115 case Expr::UnaryOperatorClass:
1116 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
1117 case Expr::ArraySubscriptExprClass:
1118 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
1119 case Expr::OMPArraySectionExprClass:
1120 return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E));
1121 case Expr::ExtVectorElementExprClass:
1122 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
1123 case Expr::MemberExprClass:
1124 return EmitMemberExpr(cast<MemberExpr>(E));
1125 case Expr::CompoundLiteralExprClass:
1126 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
1127 case Expr::ConditionalOperatorClass:
1128 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
1129 case Expr::BinaryConditionalOperatorClass:
1130 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
1131 case Expr::ChooseExprClass:
1132 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr());
1133 case Expr::OpaqueValueExprClass:
1134 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
1135 case Expr::SubstNonTypeTemplateParmExprClass:
1136 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
1137 case Expr::ImplicitCastExprClass:
1138 case Expr::CStyleCastExprClass:
1139 case Expr::CXXFunctionalCastExprClass:
1140 case Expr::CXXStaticCastExprClass:
1141 case Expr::CXXDynamicCastExprClass:
1142 case Expr::CXXReinterpretCastExprClass:
1143 case Expr::CXXConstCastExprClass:
1144 case Expr::ObjCBridgedCastExprClass:
1145 return EmitCastLValue(cast<CastExpr>(E));
1147 case Expr::MaterializeTemporaryExprClass:
1148 return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
1152 /// Given an object of the given canonical type, can we safely copy a
1153 /// value out of it based on its initializer?
1154 static bool isConstantEmittableObjectType(QualType type) {
1155 assert(type.isCanonical());
1156 assert(!type->isReferenceType());
1158 // Must be const-qualified but non-volatile.
1159 Qualifiers qs = type.getLocalQualifiers();
1160 if (!qs.hasConst() || qs.hasVolatile()) return false;
1162 // Otherwise, all object types satisfy this except C++ classes with
1163 // mutable subobjects or non-trivial copy/destroy behavior.
1164 if (const auto *RT = dyn_cast<RecordType>(type))
1165 if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
1166 if (RD->hasMutableFields() || !RD->isTrivial())
1172 /// Can we constant-emit a load of a reference to a variable of the
1173 /// given type? This is different from predicates like
1174 /// Decl::isUsableInConstantExpressions because we do want it to apply
1175 /// in situations that don't necessarily satisfy the language's rules
1176 /// for this (e.g. C++'s ODR-use rules). For example, we want to able
1177 /// to do this with const float variables even if those variables
1178 /// aren't marked 'constexpr'.
1179 enum ConstantEmissionKind {
1181 CEK_AsReferenceOnly,
1182 CEK_AsValueOrReference,
1185 static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
1186 type = type.getCanonicalType();
1187 if (const auto *ref = dyn_cast<ReferenceType>(type)) {
1188 if (isConstantEmittableObjectType(ref->getPointeeType()))
1189 return CEK_AsValueOrReference;
1190 return CEK_AsReferenceOnly;
1192 if (isConstantEmittableObjectType(type))
1193 return CEK_AsValueOnly;
1197 /// Try to emit a reference to the given value without producing it as
1198 /// an l-value. This is actually more than an optimization: we can't
1199 /// produce an l-value for variables that we never actually captured
1200 /// in a block or lambda, which means const int variables or constexpr
1201 /// literals or similar.
1202 CodeGenFunction::ConstantEmission
1203 CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
1204 ValueDecl *value = refExpr->getDecl();
1206 // The value needs to be an enum constant or a constant variable.
1207 ConstantEmissionKind CEK;
1208 if (isa<ParmVarDecl>(value)) {
1210 } else if (auto *var = dyn_cast<VarDecl>(value)) {
1211 CEK = checkVarTypeForConstantEmission(var->getType());
1212 } else if (isa<EnumConstantDecl>(value)) {
1213 CEK = CEK_AsValueOnly;
1217 if (CEK == CEK_None) return ConstantEmission();
1219 Expr::EvalResult result;
1220 bool resultIsReference;
1221 QualType resultType;
1223 // It's best to evaluate all the way as an r-value if that's permitted.
1224 if (CEK != CEK_AsReferenceOnly &&
1225 refExpr->EvaluateAsRValue(result, getContext())) {
1226 resultIsReference = false;
1227 resultType = refExpr->getType();
1229 // Otherwise, try to evaluate as an l-value.
1230 } else if (CEK != CEK_AsValueOnly &&
1231 refExpr->EvaluateAsLValue(result, getContext())) {
1232 resultIsReference = true;
1233 resultType = value->getType();
1237 return ConstantEmission();
1240 // In any case, if the initializer has side-effects, abandon ship.
1241 if (result.HasSideEffects)
1242 return ConstantEmission();
1244 // Emit as a constant.
1245 llvm::Constant *C = CGM.EmitConstantValue(result.Val, resultType, this);
1247 // Make sure we emit a debug reference to the global variable.
1248 // This should probably fire even for
1249 if (isa<VarDecl>(value)) {
1250 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
1251 EmitDeclRefExprDbgValue(refExpr, result.Val);
1253 assert(isa<EnumConstantDecl>(value));
1254 EmitDeclRefExprDbgValue(refExpr, result.Val);
1257 // If we emitted a reference constant, we need to dereference that.
1258 if (resultIsReference)
1259 return ConstantEmission::forReference(C);
1261 return ConstantEmission::forValue(C);
1264 llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
1265 SourceLocation Loc) {
1266 return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
1267 lvalue.getType(), Loc, lvalue.getAlignmentSource(),
1268 lvalue.getTBAAInfo(),
1269 lvalue.getTBAABaseType(), lvalue.getTBAAOffset(),
1270 lvalue.isNontemporal());
1273 static bool hasBooleanRepresentation(QualType Ty) {
1274 if (Ty->isBooleanType())
1277 if (const EnumType *ET = Ty->getAs<EnumType>())
1278 return ET->getDecl()->getIntegerType()->isBooleanType();
1280 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1281 return hasBooleanRepresentation(AT->getValueType());
1286 static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
1287 llvm::APInt &Min, llvm::APInt &End,
1288 bool StrictEnums, bool IsBool) {
1289 const EnumType *ET = Ty->getAs<EnumType>();
1290 bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
1291 ET && !ET->getDecl()->isFixed();
1292 if (!IsBool && !IsRegularCPlusPlusEnum)
1296 Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
1297 End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
1299 const EnumDecl *ED = ET->getDecl();
1300 llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
1301 unsigned Bitwidth = LTy->getScalarSizeInBits();
1302 unsigned NumNegativeBits = ED->getNumNegativeBits();
1303 unsigned NumPositiveBits = ED->getNumPositiveBits();
1305 if (NumNegativeBits) {
1306 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
1307 assert(NumBits <= Bitwidth);
1308 End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
1311 assert(NumPositiveBits <= Bitwidth);
1312 End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
1313 Min = llvm::APInt(Bitwidth, 0);
1319 llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
1320 llvm::APInt Min, End;
1321 if (!getRangeForType(*this, Ty, Min, End, CGM.getCodeGenOpts().StrictEnums,
1322 hasBooleanRepresentation(Ty)))
1325 llvm::MDBuilder MDHelper(getLLVMContext());
1326 return MDHelper.createRange(Min, End);
1329 bool CodeGenFunction::EmitScalarRangeCheck(llvm::Value *Value, QualType Ty,
1330 SourceLocation Loc) {
1331 bool HasBoolCheck = SanOpts.has(SanitizerKind::Bool);
1332 bool HasEnumCheck = SanOpts.has(SanitizerKind::Enum);
1333 if (!HasBoolCheck && !HasEnumCheck)
1336 bool IsBool = hasBooleanRepresentation(Ty) ||
1337 NSAPI(CGM.getContext()).isObjCBOOLType(Ty);
1338 bool NeedsBoolCheck = HasBoolCheck && IsBool;
1339 bool NeedsEnumCheck = HasEnumCheck && Ty->getAs<EnumType>();
1340 if (!NeedsBoolCheck && !NeedsEnumCheck)
1343 // Single-bit booleans don't need to be checked. Special-case this to avoid
1344 // a bit width mismatch when handling bitfield values. This is handled by
1345 // EmitFromMemory for the non-bitfield case.
1347 cast<llvm::IntegerType>(Value->getType())->getBitWidth() == 1)
1350 llvm::APInt Min, End;
1351 if (!getRangeForType(*this, Ty, Min, End, /*StrictEnums=*/true, IsBool))
1354 SanitizerScope SanScope(this);
1358 Check = Builder.CreateICmpULE(
1359 Value, llvm::ConstantInt::get(getLLVMContext(), End));
1361 llvm::Value *Upper = Builder.CreateICmpSLE(
1362 Value, llvm::ConstantInt::get(getLLVMContext(), End));
1363 llvm::Value *Lower = Builder.CreateICmpSGE(
1364 Value, llvm::ConstantInt::get(getLLVMContext(), Min));
1365 Check = Builder.CreateAnd(Upper, Lower);
1367 llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc),
1368 EmitCheckTypeDescriptor(Ty)};
1369 SanitizerMask Kind =
1370 NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
1371 EmitCheck(std::make_pair(Check, Kind), SanitizerHandler::LoadInvalidValue,
1372 StaticArgs, EmitCheckValue(Value));
1376 llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile,
1379 AlignmentSource AlignSource,
1380 llvm::MDNode *TBAAInfo,
1381 QualType TBAABaseType,
1382 uint64_t TBAAOffset,
1383 bool isNontemporal) {
1384 if (!CGM.getCodeGenOpts().PreserveVec3Type) {
1385 // For better performance, handle vector loads differently.
1386 if (Ty->isVectorType()) {
1387 const llvm::Type *EltTy = Addr.getElementType();
1389 const auto *VTy = cast<llvm::VectorType>(EltTy);
1391 // Handle vectors of size 3 like size 4 for better performance.
1392 if (VTy->getNumElements() == 3) {
1394 // Bitcast to vec4 type.
1395 llvm::VectorType *vec4Ty =
1396 llvm::VectorType::get(VTy->getElementType(), 4);
1397 Address Cast = Builder.CreateElementBitCast(Addr, vec4Ty, "castToVec4");
1399 llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4");
1401 // Shuffle vector to get vec3.
1402 V = Builder.CreateShuffleVector(V, llvm::UndefValue::get(vec4Ty),
1403 {0, 1, 2}, "extractVec");
1404 return EmitFromMemory(V, Ty);
1409 // Atomic operations have to be done on integral types.
1410 LValue AtomicLValue =
1411 LValue::MakeAddr(Addr, Ty, getContext(), AlignSource, TBAAInfo);
1412 if (Ty->isAtomicType() || LValueIsSuitableForInlineAtomic(AtomicLValue)) {
1413 return EmitAtomicLoad(AtomicLValue, Loc).getScalarVal();
1416 llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
1417 if (isNontemporal) {
1418 llvm::MDNode *Node = llvm::MDNode::get(
1419 Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1420 Load->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1423 llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
1426 CGM.DecorateInstructionWithTBAA(Load, TBAAPath,
1427 false /*ConvertTypeToTag*/);
1430 if (EmitScalarRangeCheck(Load, Ty, Loc)) {
1431 // In order to prevent the optimizer from throwing away the check, don't
1432 // attach range metadata to the load.
1433 } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
1434 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
1435 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
1437 return EmitFromMemory(Load, Ty);
1440 llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
1441 // Bool has a different representation in memory than in registers.
1442 if (hasBooleanRepresentation(Ty)) {
1443 // This should really always be an i1, but sometimes it's already
1444 // an i8, and it's awkward to track those cases down.
1445 if (Value->getType()->isIntegerTy(1))
1446 return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
1447 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1448 "wrong value rep of bool");
1454 llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
1455 // Bool has a different representation in memory than in registers.
1456 if (hasBooleanRepresentation(Ty)) {
1457 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1458 "wrong value rep of bool");
1459 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
1465 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr,
1466 bool Volatile, QualType Ty,
1467 AlignmentSource AlignSource,
1468 llvm::MDNode *TBAAInfo,
1469 bool isInit, QualType TBAABaseType,
1470 uint64_t TBAAOffset,
1471 bool isNontemporal) {
1473 if (!CGM.getCodeGenOpts().PreserveVec3Type) {
1474 // Handle vectors differently to get better performance.
1475 if (Ty->isVectorType()) {
1476 llvm::Type *SrcTy = Value->getType();
1477 auto *VecTy = cast<llvm::VectorType>(SrcTy);
1478 // Handle vec3 special.
1479 if (VecTy->getNumElements() == 3) {
1480 // Our source is a vec3, do a shuffle vector to make it a vec4.
1481 llvm::Constant *Mask[] = {Builder.getInt32(0), Builder.getInt32(1),
1482 Builder.getInt32(2),
1483 llvm::UndefValue::get(Builder.getInt32Ty())};
1484 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1485 Value = Builder.CreateShuffleVector(Value, llvm::UndefValue::get(VecTy),
1486 MaskV, "extractVec");
1487 SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
1489 if (Addr.getElementType() != SrcTy) {
1490 Addr = Builder.CreateElementBitCast(Addr, SrcTy, "storetmp");
1495 Value = EmitToMemory(Value, Ty);
1497 LValue AtomicLValue =
1498 LValue::MakeAddr(Addr, Ty, getContext(), AlignSource, TBAAInfo);
1499 if (Ty->isAtomicType() ||
1500 (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) {
1501 EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit);
1505 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
1506 if (isNontemporal) {
1507 llvm::MDNode *Node =
1508 llvm::MDNode::get(Store->getContext(),
1509 llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1510 Store->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1513 llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
1516 CGM.DecorateInstructionWithTBAA(Store, TBAAPath,
1517 false /*ConvertTypeToTag*/);
1521 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
1523 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
1524 lvalue.getType(), lvalue.getAlignmentSource(),
1525 lvalue.getTBAAInfo(), isInit, lvalue.getTBAABaseType(),
1526 lvalue.getTBAAOffset(), lvalue.isNontemporal());
1529 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1530 /// method emits the address of the lvalue, then loads the result as an rvalue,
1531 /// returning the rvalue.
1532 RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
1533 if (LV.isObjCWeak()) {
1534 // load of a __weak object.
1535 Address AddrWeakObj = LV.getAddress();
1536 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1539 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
1540 // In MRC mode, we do a load+autorelease.
1541 if (!getLangOpts().ObjCAutoRefCount) {
1542 return RValue::get(EmitARCLoadWeak(LV.getAddress()));
1545 // In ARC mode, we load retained and then consume the value.
1546 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
1547 Object = EmitObjCConsumeObject(LV.getType(), Object);
1548 return RValue::get(Object);
1551 if (LV.isSimple()) {
1552 assert(!LV.getType()->isFunctionType());
1554 // Everything needs a load.
1555 return RValue::get(EmitLoadOfScalar(LV, Loc));
1558 if (LV.isVectorElt()) {
1559 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
1560 LV.isVolatileQualified());
1561 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
1565 // If this is a reference to a subset of the elements of a vector, either
1566 // shuffle the input or extract/insert them as appropriate.
1567 if (LV.isExtVectorElt())
1568 return EmitLoadOfExtVectorElementLValue(LV);
1570 // Global Register variables always invoke intrinsics
1571 if (LV.isGlobalReg())
1572 return EmitLoadOfGlobalRegLValue(LV);
1574 assert(LV.isBitField() && "Unknown LValue type!");
1575 return EmitLoadOfBitfieldLValue(LV, Loc);
1578 RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
1579 SourceLocation Loc) {
1580 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
1582 // Get the output type.
1583 llvm::Type *ResLTy = ConvertType(LV.getType());
1585 Address Ptr = LV.getBitFieldAddress();
1586 llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
1588 if (Info.IsSigned) {
1589 assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
1590 unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
1592 Val = Builder.CreateShl(Val, HighBits, "bf.shl");
1593 if (Info.Offset + HighBits)
1594 Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
1597 Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
1598 if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
1599 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
1603 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
1604 EmitScalarRangeCheck(Val, LV.getType(), Loc);
1605 return RValue::get(Val);
1608 // If this is a reference to a subset of the elements of a vector, create an
1609 // appropriate shufflevector.
1610 RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
1611 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
1612 LV.isVolatileQualified());
1614 const llvm::Constant *Elts = LV.getExtVectorElts();
1616 // If the result of the expression is a non-vector type, we must be extracting
1617 // a single element. Just codegen as an extractelement.
1618 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1620 unsigned InIdx = getAccessedFieldNo(0, Elts);
1621 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
1622 return RValue::get(Builder.CreateExtractElement(Vec, Elt));
1625 // Always use shuffle vector to try to retain the original program structure
1626 unsigned NumResultElts = ExprVT->getNumElements();
1628 SmallVector<llvm::Constant*, 4> Mask;
1629 for (unsigned i = 0; i != NumResultElts; ++i)
1630 Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
1632 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1633 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
1635 return RValue::get(Vec);
1638 /// @brief Generates lvalue for partial ext_vector access.
1639 Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
1640 Address VectorAddress = LV.getExtVectorAddress();
1641 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1642 QualType EQT = ExprVT->getElementType();
1643 llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
1645 Address CastToPointerElement =
1646 Builder.CreateElementBitCast(VectorAddress, VectorElementTy,
1647 "conv.ptr.element");
1649 const llvm::Constant *Elts = LV.getExtVectorElts();
1650 unsigned ix = getAccessedFieldNo(0, Elts);
1652 Address VectorBasePtrPlusIx =
1653 Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
1654 getContext().getTypeSizeInChars(EQT),
1657 return VectorBasePtrPlusIx;
1660 /// @brief Load of global gamed gegisters are always calls to intrinsics.
1661 RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
1662 assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
1663 "Bad type for register variable");
1664 llvm::MDNode *RegName = cast<llvm::MDNode>(
1665 cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
1667 // We accept integer and pointer types only
1668 llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
1669 llvm::Type *Ty = OrigTy;
1670 if (OrigTy->isPointerTy())
1671 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1672 llvm::Type *Types[] = { Ty };
1674 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
1675 llvm::Value *Call = Builder.CreateCall(
1676 F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
1677 if (OrigTy->isPointerTy())
1678 Call = Builder.CreateIntToPtr(Call, OrigTy);
1679 return RValue::get(Call);
1683 /// EmitStoreThroughLValue - Store the specified rvalue into the specified
1684 /// lvalue, where both are guaranteed to the have the same type, and that type
1686 void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
1688 if (!Dst.isSimple()) {
1689 if (Dst.isVectorElt()) {
1690 // Read/modify/write the vector, inserting the new element.
1691 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
1692 Dst.isVolatileQualified());
1693 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
1694 Dst.getVectorIdx(), "vecins");
1695 Builder.CreateStore(Vec, Dst.getVectorAddress(),
1696 Dst.isVolatileQualified());
1700 // If this is an update of extended vector elements, insert them as
1702 if (Dst.isExtVectorElt())
1703 return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
1705 if (Dst.isGlobalReg())
1706 return EmitStoreThroughGlobalRegLValue(Src, Dst);
1708 assert(Dst.isBitField() && "Unknown LValue type");
1709 return EmitStoreThroughBitfieldLValue(Src, Dst);
1712 // There's special magic for assigning into an ARC-qualified l-value.
1713 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
1715 case Qualifiers::OCL_None:
1716 llvm_unreachable("present but none");
1718 case Qualifiers::OCL_ExplicitNone:
1722 case Qualifiers::OCL_Strong:
1724 Src = RValue::get(EmitARCRetain(Dst.getType(), Src.getScalarVal()));
1727 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
1730 case Qualifiers::OCL_Weak:
1732 // Initialize and then skip the primitive store.
1733 EmitARCInitWeak(Dst.getAddress(), Src.getScalarVal());
1735 EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
1738 case Qualifiers::OCL_Autoreleasing:
1739 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
1740 Src.getScalarVal()));
1741 // fall into the normal path
1746 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
1747 // load of a __weak object.
1748 Address LvalueDst = Dst.getAddress();
1749 llvm::Value *src = Src.getScalarVal();
1750 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
1754 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
1755 // load of a __strong object.
1756 Address LvalueDst = Dst.getAddress();
1757 llvm::Value *src = Src.getScalarVal();
1758 if (Dst.isObjCIvar()) {
1759 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
1760 llvm::Type *ResultType = IntPtrTy;
1761 Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp());
1762 llvm::Value *RHS = dst.getPointer();
1763 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1765 Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType,
1766 "sub.ptr.lhs.cast");
1767 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
1768 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
1770 } else if (Dst.isGlobalObjCRef()) {
1771 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
1772 Dst.isThreadLocalRef());
1775 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
1779 assert(Src.isScalar() && "Can't emit an agg store with this method");
1780 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
1783 void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
1784 llvm::Value **Result) {
1785 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
1786 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
1787 Address Ptr = Dst.getBitFieldAddress();
1789 // Get the source value, truncated to the width of the bit-field.
1790 llvm::Value *SrcVal = Src.getScalarVal();
1792 // Cast the source to the storage type and shift it into place.
1793 SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
1794 /*IsSigned=*/false);
1795 llvm::Value *MaskedVal = SrcVal;
1797 // See if there are other bits in the bitfield's storage we'll need to load
1798 // and mask together with source before storing.
1799 if (Info.StorageSize != Info.Size) {
1800 assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
1802 Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
1804 // Mask the source value as needed.
1805 if (!hasBooleanRepresentation(Dst.getType()))
1806 SrcVal = Builder.CreateAnd(SrcVal,
1807 llvm::APInt::getLowBitsSet(Info.StorageSize,
1812 SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
1814 // Mask out the original value.
1815 Val = Builder.CreateAnd(Val,
1816 ~llvm::APInt::getBitsSet(Info.StorageSize,
1818 Info.Offset + Info.Size),
1821 // Or together the unchanged values and the source value.
1822 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
1824 assert(Info.Offset == 0);
1827 // Write the new value back out.
1828 Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
1830 // Return the new value of the bit-field, if requested.
1832 llvm::Value *ResultVal = MaskedVal;
1834 // Sign extend the value if needed.
1835 if (Info.IsSigned) {
1836 assert(Info.Size <= Info.StorageSize);
1837 unsigned HighBits = Info.StorageSize - Info.Size;
1839 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
1840 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
1844 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
1846 *Result = EmitFromMemory(ResultVal, Dst.getType());
1850 void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
1852 // This access turns into a read/modify/write of the vector. Load the input
1854 llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(),
1855 Dst.isVolatileQualified());
1856 const llvm::Constant *Elts = Dst.getExtVectorElts();
1858 llvm::Value *SrcVal = Src.getScalarVal();
1860 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
1861 unsigned NumSrcElts = VTy->getNumElements();
1862 unsigned NumDstElts = Vec->getType()->getVectorNumElements();
1863 if (NumDstElts == NumSrcElts) {
1864 // Use shuffle vector is the src and destination are the same number of
1865 // elements and restore the vector mask since it is on the side it will be
1867 SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
1868 for (unsigned i = 0; i != NumSrcElts; ++i)
1869 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
1871 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1872 Vec = Builder.CreateShuffleVector(SrcVal,
1873 llvm::UndefValue::get(Vec->getType()),
1875 } else if (NumDstElts > NumSrcElts) {
1876 // Extended the source vector to the same length and then shuffle it
1877 // into the destination.
1878 // FIXME: since we're shuffling with undef, can we just use the indices
1879 // into that? This could be simpler.
1880 SmallVector<llvm::Constant*, 4> ExtMask;
1881 for (unsigned i = 0; i != NumSrcElts; ++i)
1882 ExtMask.push_back(Builder.getInt32(i));
1883 ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
1884 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
1885 llvm::Value *ExtSrcVal =
1886 Builder.CreateShuffleVector(SrcVal,
1887 llvm::UndefValue::get(SrcVal->getType()),
1890 SmallVector<llvm::Constant*, 4> Mask;
1891 for (unsigned i = 0; i != NumDstElts; ++i)
1892 Mask.push_back(Builder.getInt32(i));
1894 // When the vector size is odd and .odd or .hi is used, the last element
1895 // of the Elts constant array will be one past the size of the vector.
1896 // Ignore the last element here, if it is greater than the mask size.
1897 if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
1900 // modify when what gets shuffled in
1901 for (unsigned i = 0; i != NumSrcElts; ++i)
1902 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
1903 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1904 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
1906 // We should never shorten the vector
1907 llvm_unreachable("unexpected shorten vector length");
1910 // If the Src is a scalar (not a vector) it must be updating one element.
1911 unsigned InIdx = getAccessedFieldNo(0, Elts);
1912 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
1913 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
1916 Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
1917 Dst.isVolatileQualified());
1920 /// @brief Store of global named registers are always calls to intrinsics.
1921 void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
1922 assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
1923 "Bad type for register variable");
1924 llvm::MDNode *RegName = cast<llvm::MDNode>(
1925 cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
1926 assert(RegName && "Register LValue is not metadata");
1928 // We accept integer and pointer types only
1929 llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
1930 llvm::Type *Ty = OrigTy;
1931 if (OrigTy->isPointerTy())
1932 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1933 llvm::Type *Types[] = { Ty };
1935 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
1936 llvm::Value *Value = Src.getScalarVal();
1937 if (OrigTy->isPointerTy())
1938 Value = Builder.CreatePtrToInt(Value, Ty);
1940 F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
1943 // setObjCGCLValueClass - sets class of the lvalue for the purpose of
1944 // generating write-barries API. It is currently a global, ivar,
1946 static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
1948 bool IsMemberAccess=false) {
1949 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
1952 if (isa<ObjCIvarRefExpr>(E)) {
1953 QualType ExpTy = E->getType();
1954 if (IsMemberAccess && ExpTy->isPointerType()) {
1955 // If ivar is a structure pointer, assigning to field of
1956 // this struct follows gcc's behavior and makes it a non-ivar
1957 // writer-barrier conservatively.
1958 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1959 if (ExpTy->isRecordType()) {
1960 LV.setObjCIvar(false);
1964 LV.setObjCIvar(true);
1965 auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
1966 LV.setBaseIvarExp(Exp->getBase());
1967 LV.setObjCArray(E->getType()->isArrayType());
1971 if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
1972 if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
1973 if (VD->hasGlobalStorage()) {
1974 LV.setGlobalObjCRef(true);
1975 LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
1978 LV.setObjCArray(E->getType()->isArrayType());
1982 if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
1983 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
1987 if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
1988 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
1989 if (LV.isObjCIvar()) {
1990 // If cast is to a structure pointer, follow gcc's behavior and make it
1991 // a non-ivar write-barrier.
1992 QualType ExpTy = E->getType();
1993 if (ExpTy->isPointerType())
1994 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1995 if (ExpTy->isRecordType())
1996 LV.setObjCIvar(false);
2001 if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
2002 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
2006 if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
2007 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2011 if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
2012 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2016 if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
2017 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2021 if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
2022 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
2023 if (LV.isObjCIvar() && !LV.isObjCArray())
2024 // Using array syntax to assigning to what an ivar points to is not
2025 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
2026 LV.setObjCIvar(false);
2027 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
2028 // Using array syntax to assigning to what global points to is not
2029 // same as assigning to the global itself. {id *G;} G[i] = 0;
2030 LV.setGlobalObjCRef(false);
2034 if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
2035 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
2036 // We don't know if member is an 'ivar', but this flag is looked at
2037 // only in the context of LV.isObjCIvar().
2038 LV.setObjCArray(E->getType()->isArrayType());
2043 static llvm::Value *
2044 EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
2045 llvm::Value *V, llvm::Type *IRType,
2046 StringRef Name = StringRef()) {
2047 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
2048 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
2051 static LValue EmitThreadPrivateVarDeclLValue(
2052 CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
2053 llvm::Type *RealVarTy, SourceLocation Loc) {
2054 Addr = CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
2055 Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy);
2056 return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
2059 Address CodeGenFunction::EmitLoadOfReference(Address Addr,
2060 const ReferenceType *RefTy,
2061 AlignmentSource *Source) {
2062 llvm::Value *Ptr = Builder.CreateLoad(Addr);
2063 return Address(Ptr, getNaturalTypeAlignment(RefTy->getPointeeType(),
2064 Source, /*forPointee*/ true));
2068 LValue CodeGenFunction::EmitLoadOfReferenceLValue(Address RefAddr,
2069 const ReferenceType *RefTy) {
2070 AlignmentSource Source;
2071 Address Addr = EmitLoadOfReference(RefAddr, RefTy, &Source);
2072 return MakeAddrLValue(Addr, RefTy->getPointeeType(), Source);
2075 Address CodeGenFunction::EmitLoadOfPointer(Address Ptr,
2076 const PointerType *PtrTy,
2077 AlignmentSource *Source) {
2078 llvm::Value *Addr = Builder.CreateLoad(Ptr);
2079 return Address(Addr, getNaturalTypeAlignment(PtrTy->getPointeeType(), Source,
2080 /*forPointeeType=*/true));
2083 LValue CodeGenFunction::EmitLoadOfPointerLValue(Address PtrAddr,
2084 const PointerType *PtrTy) {
2085 AlignmentSource Source;
2086 Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &Source);
2087 return MakeAddrLValue(Addr, PtrTy->getPointeeType(), Source);
2090 static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
2091 const Expr *E, const VarDecl *VD) {
2092 QualType T = E->getType();
2094 // If it's thread_local, emit a call to its wrapper function instead.
2095 if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
2096 CGF.CGM.getCXXABI().usesThreadWrapperFunction())
2097 return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
2099 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
2100 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
2101 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
2102 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
2103 Address Addr(V, Alignment);
2105 // Emit reference to the private copy of the variable if it is an OpenMP
2106 // threadprivate variable.
2107 if (CGF.getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>())
2108 return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
2110 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2111 LV = CGF.EmitLoadOfReferenceLValue(Addr, RefTy);
2113 LV = CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
2115 setObjCGCLValueClass(CGF.getContext(), E, LV);
2119 static llvm::Constant *EmitFunctionDeclPointer(CodeGenModule &CGM,
2120 const FunctionDecl *FD) {
2121 if (FD->hasAttr<WeakRefAttr>()) {
2122 ConstantAddress aliasee = CGM.GetWeakRefReference(FD);
2123 return aliasee.getPointer();
2126 llvm::Constant *V = CGM.GetAddrOfFunction(FD);
2127 if (!FD->hasPrototype()) {
2128 if (const FunctionProtoType *Proto =
2129 FD->getType()->getAs<FunctionProtoType>()) {
2130 // Ugly case: for a K&R-style definition, the type of the definition
2131 // isn't the same as the type of a use. Correct for this with a
2133 QualType NoProtoType =
2134 CGM.getContext().getFunctionNoProtoType(Proto->getReturnType());
2135 NoProtoType = CGM.getContext().getPointerType(NoProtoType);
2136 V = llvm::ConstantExpr::getBitCast(V,
2137 CGM.getTypes().ConvertType(NoProtoType));
2143 static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
2144 const Expr *E, const FunctionDecl *FD) {
2145 llvm::Value *V = EmitFunctionDeclPointer(CGF.CGM, FD);
2146 CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
2147 return CGF.MakeAddrLValue(V, E->getType(), Alignment, AlignmentSource::Decl);
2150 static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
2151 llvm::Value *ThisValue) {
2152 QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
2153 LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
2154 return CGF.EmitLValueForField(LV, FD);
2157 /// Named Registers are named metadata pointing to the register name
2158 /// which will be read from/written to as an argument to the intrinsic
2159 /// @llvm.read/write_register.
2160 /// So far, only the name is being passed down, but other options such as
2161 /// register type, allocation type or even optimization options could be
2162 /// passed down via the metadata node.
2163 static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
2164 SmallString<64> Name("llvm.named.register.");
2165 AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
2166 assert(Asm->getLabel().size() < 64-Name.size() &&
2167 "Register name too big");
2168 Name.append(Asm->getLabel());
2169 llvm::NamedMDNode *M =
2170 CGM.getModule().getOrInsertNamedMetadata(Name);
2171 if (M->getNumOperands() == 0) {
2172 llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
2174 llvm::Metadata *Ops[] = {Str};
2175 M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2178 CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
2181 llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
2182 return LValue::MakeGlobalReg(Address(Ptr, Alignment), VD->getType());
2185 LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
2186 const NamedDecl *ND = E->getDecl();
2187 QualType T = E->getType();
2189 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2190 // Global Named registers access via intrinsics only
2191 if (VD->getStorageClass() == SC_Register &&
2192 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
2193 return EmitGlobalNamedRegister(VD, CGM);
2195 // A DeclRefExpr for a reference initialized by a constant expression can
2196 // appear without being odr-used. Directly emit the constant initializer.
2197 const Expr *Init = VD->getAnyInitializer(VD);
2198 if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() &&
2199 VD->isUsableInConstantExpressions(getContext()) &&
2200 VD->checkInitIsICE() &&
2201 // Do not emit if it is private OpenMP variable.
2202 !(E->refersToEnclosingVariableOrCapture() && CapturedStmtInfo &&
2203 LocalDeclMap.count(VD))) {
2204 llvm::Constant *Val =
2205 CGM.EmitConstantValue(*VD->evaluateValue(), VD->getType(), this);
2206 assert(Val && "failed to emit reference constant expression");
2207 // FIXME: Eventually we will want to emit vector element references.
2209 // Should we be using the alignment of the constant pointer we emitted?
2210 CharUnits Alignment = getNaturalTypeAlignment(E->getType(), nullptr,
2213 return MakeAddrLValue(Address(Val, Alignment), T, AlignmentSource::Decl);
2216 // Check for captured variables.
2217 if (E->refersToEnclosingVariableOrCapture()) {
2218 if (auto *FD = LambdaCaptureFields.lookup(VD))
2219 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
2220 else if (CapturedStmtInfo) {
2221 auto I = LocalDeclMap.find(VD);
2222 if (I != LocalDeclMap.end()) {
2223 if (auto RefTy = VD->getType()->getAs<ReferenceType>())
2224 return EmitLoadOfReferenceLValue(I->second, RefTy);
2225 return MakeAddrLValue(I->second, T);
2228 EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
2229 CapturedStmtInfo->getContextValue());
2230 return MakeAddrLValue(
2231 Address(CapLVal.getPointer(), getContext().getDeclAlign(VD)),
2232 CapLVal.getType(), AlignmentSource::Decl);
2235 assert(isa<BlockDecl>(CurCodeDecl));
2236 Address addr = GetAddrOfBlockDecl(VD, VD->hasAttr<BlocksAttr>());
2237 return MakeAddrLValue(addr, T, AlignmentSource::Decl);
2241 // FIXME: We should be able to assert this for FunctionDecls as well!
2242 // FIXME: We should be able to assert this for all DeclRefExprs, not just
2243 // those with a valid source location.
2244 assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
2245 !E->getLocation().isValid()) &&
2246 "Should not use decl without marking it used!");
2248 if (ND->hasAttr<WeakRefAttr>()) {
2249 const auto *VD = cast<ValueDecl>(ND);
2250 ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
2251 return MakeAddrLValue(Aliasee, T, AlignmentSource::Decl);
2254 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2255 // Check if this is a global variable.
2256 if (VD->hasLinkage() || VD->isStaticDataMember())
2257 return EmitGlobalVarDeclLValue(*this, E, VD);
2259 Address addr = Address::invalid();
2261 // The variable should generally be present in the local decl map.
2262 auto iter = LocalDeclMap.find(VD);
2263 if (iter != LocalDeclMap.end()) {
2264 addr = iter->second;
2266 // Otherwise, it might be static local we haven't emitted yet for
2267 // some reason; most likely, because it's in an outer function.
2268 } else if (VD->isStaticLocal()) {
2269 addr = Address(CGM.getOrCreateStaticVarDecl(
2270 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false)),
2271 getContext().getDeclAlign(VD));
2273 // No other cases for now.
2275 llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
2279 // Check for OpenMP threadprivate variables.
2280 if (getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
2281 return EmitThreadPrivateVarDeclLValue(
2282 *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
2286 // Drill into block byref variables.
2287 bool isBlockByref = VD->hasAttr<BlocksAttr>();
2289 addr = emitBlockByrefAddress(addr, VD);
2292 // Drill into reference types.
2294 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2295 LV = EmitLoadOfReferenceLValue(addr, RefTy);
2297 LV = MakeAddrLValue(addr, T, AlignmentSource::Decl);
2300 bool isLocalStorage = VD->hasLocalStorage();
2302 bool NonGCable = isLocalStorage &&
2303 !VD->getType()->isReferenceType() &&
2306 LV.getQuals().removeObjCGCAttr();
2310 bool isImpreciseLifetime =
2311 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
2312 if (isImpreciseLifetime)
2313 LV.setARCPreciseLifetime(ARCImpreciseLifetime);
2314 setObjCGCLValueClass(getContext(), E, LV);
2318 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
2319 return EmitFunctionDeclLValue(*this, E, FD);
2321 // FIXME: While we're emitting a binding from an enclosing scope, all other
2322 // DeclRefExprs we see should be implicitly treated as if they also refer to
2323 // an enclosing scope.
2324 if (const auto *BD = dyn_cast<BindingDecl>(ND))
2325 return EmitLValue(BD->getBinding());
2327 llvm_unreachable("Unhandled DeclRefExpr");
2330 LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
2331 // __extension__ doesn't affect lvalue-ness.
2332 if (E->getOpcode() == UO_Extension)
2333 return EmitLValue(E->getSubExpr());
2335 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
2336 switch (E->getOpcode()) {
2337 default: llvm_unreachable("Unknown unary operator lvalue!");
2339 QualType T = E->getSubExpr()->getType()->getPointeeType();
2340 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
2342 AlignmentSource AlignSource;
2343 Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &AlignSource);
2344 LValue LV = MakeAddrLValue(Addr, T, AlignSource);
2345 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
2347 // We should not generate __weak write barrier on indirect reference
2348 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
2349 // But, we continue to generate __strong write barrier on indirect write
2350 // into a pointer to object.
2351 if (getLangOpts().ObjC1 &&
2352 getLangOpts().getGC() != LangOptions::NonGC &&
2354 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
2359 LValue LV = EmitLValue(E->getSubExpr());
2360 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
2362 // __real is valid on scalars. This is a faster way of testing that.
2363 // __imag can only produce an rvalue on scalars.
2364 if (E->getOpcode() == UO_Real &&
2365 !LV.getAddress().getElementType()->isStructTy()) {
2366 assert(E->getSubExpr()->getType()->isArithmeticType());
2370 QualType T = ExprTy->castAs<ComplexType>()->getElementType();
2373 (E->getOpcode() == UO_Real
2374 ? emitAddrOfRealComponent(LV.getAddress(), LV.getType())
2375 : emitAddrOfImagComponent(LV.getAddress(), LV.getType()));
2376 LValue ElemLV = MakeAddrLValue(Component, T, LV.getAlignmentSource());
2377 ElemLV.getQuals().addQualifiers(LV.getQuals());
2382 LValue LV = EmitLValue(E->getSubExpr());
2383 bool isInc = E->getOpcode() == UO_PreInc;
2385 if (E->getType()->isAnyComplexType())
2386 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
2388 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
2394 LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
2395 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
2396 E->getType(), AlignmentSource::Decl);
2399 LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
2400 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
2401 E->getType(), AlignmentSource::Decl);
2404 LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
2405 auto SL = E->getFunctionName();
2406 assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
2407 StringRef FnName = CurFn->getName();
2408 if (FnName.startswith("\01"))
2409 FnName = FnName.substr(1);
2410 StringRef NameItems[] = {
2411 PredefinedExpr::getIdentTypeName(E->getIdentType()), FnName};
2412 std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
2413 if (auto *BD = dyn_cast<BlockDecl>(CurCodeDecl)) {
2414 std::string Name = SL->getString();
2415 if (!Name.empty()) {
2416 unsigned Discriminator =
2417 CGM.getCXXABI().getMangleContext().getBlockId(BD, true);
2419 Name += "_" + Twine(Discriminator + 1).str();
2420 auto C = CGM.GetAddrOfConstantCString(Name, GVName.c_str());
2421 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
2423 auto C = CGM.GetAddrOfConstantCString(FnName, GVName.c_str());
2424 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
2427 auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
2428 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
2431 /// Emit a type description suitable for use by a runtime sanitizer library. The
2432 /// format of a type descriptor is
2435 /// { i16 TypeKind, i16 TypeInfo }
2438 /// followed by an array of i8 containing the type name. TypeKind is 0 for an
2439 /// integer, 1 for a floating point value, and -1 for anything else.
2440 llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
2441 // Only emit each type's descriptor once.
2442 if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
2445 uint16_t TypeKind = -1;
2446 uint16_t TypeInfo = 0;
2448 if (T->isIntegerType()) {
2450 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
2451 (T->isSignedIntegerType() ? 1 : 0);
2452 } else if (T->isFloatingType()) {
2454 TypeInfo = getContext().getTypeSize(T);
2457 // Format the type name as if for a diagnostic, including quotes and
2458 // optionally an 'aka'.
2459 SmallString<32> Buffer;
2460 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
2461 (intptr_t)T.getAsOpaquePtr(),
2462 StringRef(), StringRef(), None, Buffer,
2465 llvm::Constant *Components[] = {
2466 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
2467 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
2469 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
2471 auto *GV = new llvm::GlobalVariable(
2472 CGM.getModule(), Descriptor->getType(),
2473 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
2474 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2475 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
2477 // Remember the descriptor for this type.
2478 CGM.setTypeDescriptorInMap(T, GV);
2483 llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
2484 llvm::Type *TargetTy = IntPtrTy;
2486 // Floating-point types which fit into intptr_t are bitcast to integers
2487 // and then passed directly (after zero-extension, if necessary).
2488 if (V->getType()->isFloatingPointTy()) {
2489 unsigned Bits = V->getType()->getPrimitiveSizeInBits();
2490 if (Bits <= TargetTy->getIntegerBitWidth())
2491 V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
2495 // Integers which fit in intptr_t are zero-extended and passed directly.
2496 if (V->getType()->isIntegerTy() &&
2497 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
2498 return Builder.CreateZExt(V, TargetTy);
2500 // Pointers are passed directly, everything else is passed by address.
2501 if (!V->getType()->isPointerTy()) {
2502 Address Ptr = CreateDefaultAlignTempAlloca(V->getType());
2503 Builder.CreateStore(V, Ptr);
2504 V = Ptr.getPointer();
2506 return Builder.CreatePtrToInt(V, TargetTy);
2509 /// \brief Emit a representation of a SourceLocation for passing to a handler
2510 /// in a sanitizer runtime library. The format for this data is:
2512 /// struct SourceLocation {
2513 /// const char *Filename;
2514 /// int32_t Line, Column;
2517 /// For an invalid SourceLocation, the Filename pointer is null.
2518 llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
2519 llvm::Constant *Filename;
2522 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
2523 if (PLoc.isValid()) {
2524 StringRef FilenameString = PLoc.getFilename();
2526 int PathComponentsToStrip =
2527 CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
2528 if (PathComponentsToStrip < 0) {
2529 assert(PathComponentsToStrip != INT_MIN);
2530 int PathComponentsToKeep = -PathComponentsToStrip;
2531 auto I = llvm::sys::path::rbegin(FilenameString);
2532 auto E = llvm::sys::path::rend(FilenameString);
2533 while (I != E && --PathComponentsToKeep)
2536 FilenameString = FilenameString.substr(I - E);
2537 } else if (PathComponentsToStrip > 0) {
2538 auto I = llvm::sys::path::begin(FilenameString);
2539 auto E = llvm::sys::path::end(FilenameString);
2540 while (I != E && PathComponentsToStrip--)
2545 FilenameString.substr(I - llvm::sys::path::begin(FilenameString));
2547 FilenameString = llvm::sys::path::filename(FilenameString);
2550 auto FilenameGV = CGM.GetAddrOfConstantCString(FilenameString, ".src");
2551 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
2552 cast<llvm::GlobalVariable>(FilenameGV.getPointer()));
2553 Filename = FilenameGV.getPointer();
2554 Line = PLoc.getLine();
2555 Column = PLoc.getColumn();
2557 Filename = llvm::Constant::getNullValue(Int8PtrTy);
2561 llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
2562 Builder.getInt32(Column)};
2564 return llvm::ConstantStruct::getAnon(Data);
2568 /// \brief Specify under what conditions this check can be recovered
2569 enum class CheckRecoverableKind {
2570 /// Always terminate program execution if this check fails.
2572 /// Check supports recovering, runtime has both fatal (noreturn) and
2573 /// non-fatal handlers for this check.
2575 /// Runtime conditionally aborts, always need to support recovery.
2580 static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
2581 assert(llvm::countPopulation(Kind) == 1);
2583 case SanitizerKind::Vptr:
2584 return CheckRecoverableKind::AlwaysRecoverable;
2585 case SanitizerKind::Return:
2586 case SanitizerKind::Unreachable:
2587 return CheckRecoverableKind::Unrecoverable;
2589 return CheckRecoverableKind::Recoverable;
2594 struct SanitizerHandlerInfo {
2595 char const *const Name;
2600 const SanitizerHandlerInfo SanitizerHandlers[] = {
2601 #define SANITIZER_CHECK(Enum, Name, Version) {#Name, Version},
2602 LIST_SANITIZER_CHECKS
2603 #undef SANITIZER_CHECK
2606 static void emitCheckHandlerCall(CodeGenFunction &CGF,
2607 llvm::FunctionType *FnType,
2608 ArrayRef<llvm::Value *> FnArgs,
2609 SanitizerHandler CheckHandler,
2610 CheckRecoverableKind RecoverKind, bool IsFatal,
2611 llvm::BasicBlock *ContBB) {
2612 assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
2613 bool NeedsAbortSuffix =
2614 IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
2615 const SanitizerHandlerInfo &CheckInfo = SanitizerHandlers[CheckHandler];
2616 const StringRef CheckName = CheckInfo.Name;
2617 std::string FnName =
2618 ("__ubsan_handle_" + CheckName +
2619 (CheckInfo.Version ? "_v" + llvm::utostr(CheckInfo.Version) : "") +
2620 (NeedsAbortSuffix ? "_abort" : ""))
2623 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
2625 llvm::AttrBuilder B;
2627 B.addAttribute(llvm::Attribute::NoReturn)
2628 .addAttribute(llvm::Attribute::NoUnwind);
2630 B.addAttribute(llvm::Attribute::UWTable);
2632 llvm::Value *Fn = CGF.CGM.CreateRuntimeFunction(
2634 llvm::AttributeList::get(CGF.getLLVMContext(),
2635 llvm::AttributeList::FunctionIndex, B),
2637 llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
2639 HandlerCall->setDoesNotReturn();
2640 CGF.Builder.CreateUnreachable();
2642 CGF.Builder.CreateBr(ContBB);
2646 void CodeGenFunction::EmitCheck(
2647 ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
2648 SanitizerHandler CheckHandler, ArrayRef<llvm::Constant *> StaticArgs,
2649 ArrayRef<llvm::Value *> DynamicArgs) {
2650 assert(IsSanitizerScope);
2651 assert(Checked.size() > 0);
2652 assert(CheckHandler >= 0 &&
2653 CheckHandler < sizeof(SanitizerHandlers) / sizeof(*SanitizerHandlers));
2654 const StringRef CheckName = SanitizerHandlers[CheckHandler].Name;
2656 llvm::Value *FatalCond = nullptr;
2657 llvm::Value *RecoverableCond = nullptr;
2658 llvm::Value *TrapCond = nullptr;
2659 for (int i = 0, n = Checked.size(); i < n; ++i) {
2660 llvm::Value *Check = Checked[i].first;
2661 // -fsanitize-trap= overrides -fsanitize-recover=.
2662 llvm::Value *&Cond =
2663 CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
2665 : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
2668 Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
2672 EmitTrapCheck(TrapCond);
2673 if (!FatalCond && !RecoverableCond)
2676 llvm::Value *JointCond;
2677 if (FatalCond && RecoverableCond)
2678 JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
2680 JointCond = FatalCond ? FatalCond : RecoverableCond;
2683 CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
2684 assert(SanOpts.has(Checked[0].second));
2686 for (int i = 1, n = Checked.size(); i < n; ++i) {
2687 assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
2688 "All recoverable kinds in a single check must be same!");
2689 assert(SanOpts.has(Checked[i].second));
2693 llvm::BasicBlock *Cont = createBasicBlock("cont");
2694 llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
2695 llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
2696 // Give hint that we very much don't expect to execute the handler
2697 // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
2698 llvm::MDBuilder MDHelper(getLLVMContext());
2699 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2700 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
2701 EmitBlock(Handlers);
2703 // Handler functions take an i8* pointing to the (handler-specific) static
2704 // information block, followed by a sequence of intptr_t arguments
2705 // representing operand values.
2706 SmallVector<llvm::Value *, 4> Args;
2707 SmallVector<llvm::Type *, 4> ArgTypes;
2708 Args.reserve(DynamicArgs.size() + 1);
2709 ArgTypes.reserve(DynamicArgs.size() + 1);
2711 // Emit handler arguments and create handler function type.
2712 if (!StaticArgs.empty()) {
2713 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2715 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2716 llvm::GlobalVariable::PrivateLinkage, Info);
2717 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2718 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2719 Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
2720 ArgTypes.push_back(Int8PtrTy);
2723 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
2724 Args.push_back(EmitCheckValue(DynamicArgs[i]));
2725 ArgTypes.push_back(IntPtrTy);
2728 llvm::FunctionType *FnType =
2729 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
2731 if (!FatalCond || !RecoverableCond) {
2732 // Simple case: we need to generate a single handler call, either
2733 // fatal, or non-fatal.
2734 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind,
2735 (FatalCond != nullptr), Cont);
2737 // Emit two handler calls: first one for set of unrecoverable checks,
2738 // another one for recoverable.
2739 llvm::BasicBlock *NonFatalHandlerBB =
2740 createBasicBlock("non_fatal." + CheckName);
2741 llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
2742 Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
2743 EmitBlock(FatalHandlerBB);
2744 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, true,
2746 EmitBlock(NonFatalHandlerBB);
2747 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, false,
2754 void CodeGenFunction::EmitCfiSlowPathCheck(
2755 SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId,
2756 llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) {
2757 llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
2759 llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
2760 llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
2762 llvm::MDBuilder MDHelper(getLLVMContext());
2763 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2764 BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
2768 bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind);
2770 llvm::CallInst *CheckCall;
2772 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2774 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2775 llvm::GlobalVariable::PrivateLinkage, Info);
2776 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2777 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2779 llvm::Constant *SlowPathDiagFn = CGM.getModule().getOrInsertFunction(
2780 "__cfi_slowpath_diag",
2781 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
2783 CheckCall = Builder.CreateCall(
2785 {TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)});
2787 llvm::Constant *SlowPathFn = CGM.getModule().getOrInsertFunction(
2789 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
2790 CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
2793 CheckCall->setDoesNotThrow();
2798 // Emit a stub for __cfi_check function so that the linker knows about this
2799 // symbol in LTO mode.
2800 void CodeGenFunction::EmitCfiCheckStub() {
2801 llvm::Module *M = &CGM.getModule();
2802 auto &Ctx = M->getContext();
2803 llvm::Function *F = llvm::Function::Create(
2804 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy}, false),
2805 llvm::GlobalValue::WeakAnyLinkage, "__cfi_check", M);
2806 llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx, "entry", F);
2807 // FIXME: consider emitting an intrinsic call like
2808 // call void @llvm.cfi_check(i64 %0, i8* %1, i8* %2)
2809 // which can be lowered in CrossDSOCFI pass to the actual contents of
2810 // __cfi_check. This would allow inlining of __cfi_check calls.
2811 llvm::CallInst::Create(
2812 llvm::Intrinsic::getDeclaration(M, llvm::Intrinsic::trap), "", BB);
2813 llvm::ReturnInst::Create(Ctx, nullptr, BB);
2816 // This function is basically a switch over the CFI failure kind, which is
2817 // extracted from CFICheckFailData (1st function argument). Each case is either
2818 // llvm.trap or a call to one of the two runtime handlers, based on
2819 // -fsanitize-trap and -fsanitize-recover settings. Default case (invalid
2820 // failure kind) traps, but this should really never happen. CFICheckFailData
2821 // can be nullptr if the calling module has -fsanitize-trap behavior for this
2822 // check kind; in this case __cfi_check_fail traps as well.
2823 void CodeGenFunction::EmitCfiCheckFail() {
2824 SanitizerScope SanScope(this);
2825 FunctionArgList Args;
2826 ImplicitParamDecl ArgData(getContext(), nullptr, SourceLocation(), nullptr,
2827 getContext().VoidPtrTy);
2828 ImplicitParamDecl ArgAddr(getContext(), nullptr, SourceLocation(), nullptr,
2829 getContext().VoidPtrTy);
2830 Args.push_back(&ArgData);
2831 Args.push_back(&ArgAddr);
2833 const CGFunctionInfo &FI =
2834 CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args);
2836 llvm::Function *F = llvm::Function::Create(
2837 llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false),
2838 llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule());
2839 F->setVisibility(llvm::GlobalValue::HiddenVisibility);
2841 StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args,
2845 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false,
2846 CGM.getContext().VoidPtrTy, ArgData.getLocation());
2848 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false,
2849 CGM.getContext().VoidPtrTy, ArgAddr.getLocation());
2851 // Data == nullptr means the calling module has trap behaviour for this check.
2852 llvm::Value *DataIsNotNullPtr =
2853 Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy));
2854 EmitTrapCheck(DataIsNotNullPtr);
2856 llvm::StructType *SourceLocationTy =
2857 llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty, nullptr);
2858 llvm::StructType *CfiCheckFailDataTy =
2859 llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy, nullptr);
2861 llvm::Value *V = Builder.CreateConstGEP2_32(
2863 Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0,
2865 Address CheckKindAddr(V, getIntAlign());
2866 llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr);
2868 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
2869 CGM.getLLVMContext(),
2870 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
2871 llvm::Value *ValidVtable = Builder.CreateZExt(
2872 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
2873 {Addr, AllVtables}),
2876 const std::pair<int, SanitizerMask> CheckKinds[] = {
2877 {CFITCK_VCall, SanitizerKind::CFIVCall},
2878 {CFITCK_NVCall, SanitizerKind::CFINVCall},
2879 {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast},
2880 {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast},
2881 {CFITCK_ICall, SanitizerKind::CFIICall}};
2883 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 5> Checks;
2884 for (auto CheckKindMaskPair : CheckKinds) {
2885 int Kind = CheckKindMaskPair.first;
2886 SanitizerMask Mask = CheckKindMaskPair.second;
2888 Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind));
2889 if (CGM.getLangOpts().Sanitize.has(Mask))
2890 EmitCheck(std::make_pair(Cond, Mask), SanitizerHandler::CFICheckFail, {},
2891 {Data, Addr, ValidVtable});
2893 EmitTrapCheck(Cond);
2897 // The only reference to this function will be created during LTO link.
2898 // Make sure it survives until then.
2899 CGM.addUsedGlobal(F);
2902 void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) {
2903 llvm::BasicBlock *Cont = createBasicBlock("cont");
2905 // If we're optimizing, collapse all calls to trap down to just one per
2906 // function to save on code size.
2907 if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
2908 TrapBB = createBasicBlock("trap");
2909 Builder.CreateCondBr(Checked, Cont, TrapBB);
2911 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
2912 TrapCall->setDoesNotReturn();
2913 TrapCall->setDoesNotThrow();
2914 Builder.CreateUnreachable();
2916 Builder.CreateCondBr(Checked, Cont, TrapBB);
2922 llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
2923 llvm::CallInst *TrapCall = Builder.CreateCall(CGM.getIntrinsic(IntrID));
2925 if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
2926 auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
2927 CGM.getCodeGenOpts().TrapFuncName);
2928 TrapCall->addAttribute(llvm::AttributeList::FunctionIndex, A);
2934 Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E,
2935 AlignmentSource *AlignSource) {
2936 assert(E->getType()->isArrayType() &&
2937 "Array to pointer decay must have array source type!");
2939 // Expressions of array type can't be bitfields or vector elements.
2940 LValue LV = EmitLValue(E);
2941 Address Addr = LV.getAddress();
2942 if (AlignSource) *AlignSource = LV.getAlignmentSource();
2944 // If the array type was an incomplete type, we need to make sure
2945 // the decay ends up being the right type.
2946 llvm::Type *NewTy = ConvertType(E->getType());
2947 Addr = Builder.CreateElementBitCast(Addr, NewTy);
2949 // Note that VLA pointers are always decayed, so we don't need to do
2951 if (!E->getType()->isVariableArrayType()) {
2952 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
2953 "Expected pointer to array");
2954 Addr = Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(), "arraydecay");
2957 QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
2958 return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType));
2961 /// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
2962 /// array to pointer, return the array subexpression.
2963 static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
2964 // If this isn't just an array->pointer decay, bail out.
2965 const auto *CE = dyn_cast<CastExpr>(E);
2966 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
2969 // If this is a decay from variable width array, bail out.
2970 const Expr *SubExpr = CE->getSubExpr();
2971 if (SubExpr->getType()->isVariableArrayType())
2977 static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF,
2979 ArrayRef<llvm::Value*> indices,
2981 const llvm::Twine &name = "arrayidx") {
2983 return CGF.Builder.CreateInBoundsGEP(ptr, indices, name);
2985 return CGF.Builder.CreateGEP(ptr, indices, name);
2989 static CharUnits getArrayElementAlign(CharUnits arrayAlign,
2991 CharUnits eltSize) {
2992 // If we have a constant index, we can use the exact offset of the
2993 // element we're accessing.
2994 if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
2995 CharUnits offset = constantIdx->getZExtValue() * eltSize;
2996 return arrayAlign.alignmentAtOffset(offset);
2998 // Otherwise, use the worst-case alignment for any element.
3000 return arrayAlign.alignmentOfArrayElement(eltSize);
3004 static QualType getFixedSizeElementType(const ASTContext &ctx,
3005 const VariableArrayType *vla) {
3008 eltType = vla->getElementType();
3009 } while ((vla = ctx.getAsVariableArrayType(eltType)));
3013 static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
3014 ArrayRef<llvm::Value*> indices,
3015 QualType eltType, bool inbounds,
3016 const llvm::Twine &name = "arrayidx") {
3017 // All the indices except that last must be zero.
3019 for (auto idx : indices.drop_back())
3020 assert(isa<llvm::ConstantInt>(idx) &&
3021 cast<llvm::ConstantInt>(idx)->isZero());
3024 // Determine the element size of the statically-sized base. This is
3025 // the thing that the indices are expressed in terms of.
3026 if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
3027 eltType = getFixedSizeElementType(CGF.getContext(), vla);
3030 // We can use that to compute the best alignment of the element.
3031 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
3032 CharUnits eltAlign =
3033 getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
3035 llvm::Value *eltPtr =
3036 emitArraySubscriptGEP(CGF, addr.getPointer(), indices, inbounds, name);
3037 return Address(eltPtr, eltAlign);
3040 LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
3042 // The index must always be an integer, which is not an aggregate. Emit it
3043 // in lexical order (this complexity is, sadly, required by C++17).
3044 llvm::Value *IdxPre =
3045 (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E->getIdx()) : nullptr;
3046 auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * {
3048 if (E->getLHS() != E->getIdx()) {
3049 assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS");
3050 Idx = EmitScalarExpr(E->getIdx());
3053 QualType IdxTy = E->getIdx()->getType();
3054 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
3056 if (SanOpts.has(SanitizerKind::ArrayBounds))
3057 EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
3059 // Extend or truncate the index type to 32 or 64-bits.
3060 if (Promote && Idx->getType() != IntPtrTy)
3061 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
3067 // If the base is a vector type, then we are forming a vector element lvalue
3068 // with this subscript.
3069 if (E->getBase()->getType()->isVectorType() &&
3070 !isa<ExtVectorElementExpr>(E->getBase())) {
3071 // Emit the vector as an lvalue to get its address.
3072 LValue LHS = EmitLValue(E->getBase());
3073 auto *Idx = EmitIdxAfterBase(/*Promote*/false);
3074 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
3075 return LValue::MakeVectorElt(LHS.getAddress(), Idx,
3076 E->getBase()->getType(),
3077 LHS.getAlignmentSource());
3080 // All the other cases basically behave like simple offsetting.
3082 // Handle the extvector case we ignored above.
3083 if (isa<ExtVectorElementExpr>(E->getBase())) {
3084 LValue LV = EmitLValue(E->getBase());
3085 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3086 Address Addr = EmitExtVectorElementLValue(LV);
3088 QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
3089 Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true);
3090 return MakeAddrLValue(Addr, EltType, LV.getAlignmentSource());
3093 AlignmentSource AlignSource;
3094 Address Addr = Address::invalid();
3095 if (const VariableArrayType *vla =
3096 getContext().getAsVariableArrayType(E->getType())) {
3097 // The base must be a pointer, which is not an aggregate. Emit
3098 // it. It needs to be emitted first in case it's what captures
3100 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
3101 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3103 // The element count here is the total number of non-VLA elements.
3104 llvm::Value *numElements = getVLASize(vla).first;
3106 // Effectively, the multiply by the VLA size is part of the GEP.
3107 // GEP indexes are signed, and scaling an index isn't permitted to
3108 // signed-overflow, so we use the same semantics for our explicit
3109 // multiply. We suppress this if overflow is not undefined behavior.
3110 if (getLangOpts().isSignedOverflowDefined()) {
3111 Idx = Builder.CreateMul(Idx, numElements);
3113 Idx = Builder.CreateNSWMul(Idx, numElements);
3116 Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
3117 !getLangOpts().isSignedOverflowDefined());
3119 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
3120 // Indexing over an interface, as in "NSString *P; P[4];"
3122 // Emit the base pointer.
3123 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
3124 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3126 CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
3127 llvm::Value *InterfaceSizeVal =
3128 llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());
3130 llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
3132 // We don't necessarily build correct LLVM struct types for ObjC
3133 // interfaces, so we can't rely on GEP to do this scaling
3134 // correctly, so we need to cast to i8*. FIXME: is this actually
3135 // true? A lot of other things in the fragile ABI would break...
3136 llvm::Type *OrigBaseTy = Addr.getType();
3137 Addr = Builder.CreateElementBitCast(Addr, Int8Ty);
3140 CharUnits EltAlign =
3141 getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
3142 llvm::Value *EltPtr =
3143 emitArraySubscriptGEP(*this, Addr.getPointer(), ScaledIdx, false);
3144 Addr = Address(EltPtr, EltAlign);
3147 Addr = Builder.CreateBitCast(Addr, OrigBaseTy);
3148 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3149 // If this is A[i] where A is an array, the frontend will have decayed the
3150 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3151 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3152 // "gep x, i" here. Emit one "gep A, 0, i".
3153 assert(Array->getType()->isArrayType() &&
3154 "Array to pointer decay must have array source type!");
3156 // For simple multidimensional array indexing, set the 'accessed' flag for
3157 // better bounds-checking of the base expression.
3158 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3159 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3161 ArrayLV = EmitLValue(Array);
3162 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3164 // Propagate the alignment from the array itself to the result.
3165 Addr = emitArraySubscriptGEP(*this, ArrayLV.getAddress(),
3166 {CGM.getSize(CharUnits::Zero()), Idx},
3168 !getLangOpts().isSignedOverflowDefined());
3169 AlignSource = ArrayLV.getAlignmentSource();
3171 // The base must be a pointer; emit it with an estimate of its alignment.
3172 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
3173 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3174 Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
3175 !getLangOpts().isSignedOverflowDefined());
3178 LValue LV = MakeAddrLValue(Addr, E->getType(), AlignSource);
3180 // TODO: Preserve/extend path TBAA metadata?
3182 if (getLangOpts().ObjC1 &&
3183 getLangOpts().getGC() != LangOptions::NonGC) {
3184 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
3185 setObjCGCLValueClass(getContext(), E, LV);
3190 static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base,
3191 AlignmentSource &AlignSource,
3192 QualType BaseTy, QualType ElTy,
3193 bool IsLowerBound) {
3195 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParenImpCasts())) {
3196 BaseLVal = CGF.EmitOMPArraySectionExpr(ASE, IsLowerBound);
3197 if (BaseTy->isArrayType()) {
3198 Address Addr = BaseLVal.getAddress();
3199 AlignSource = BaseLVal.getAlignmentSource();
3201 // If the array type was an incomplete type, we need to make sure
3202 // the decay ends up being the right type.
3203 llvm::Type *NewTy = CGF.ConvertType(BaseTy);
3204 Addr = CGF.Builder.CreateElementBitCast(Addr, NewTy);
3206 // Note that VLA pointers are always decayed, so we don't need to do
3208 if (!BaseTy->isVariableArrayType()) {
3209 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3210 "Expected pointer to array");
3211 Addr = CGF.Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(),
3215 return CGF.Builder.CreateElementBitCast(Addr,
3216 CGF.ConvertTypeForMem(ElTy));
3218 CharUnits Align = CGF.getNaturalTypeAlignment(ElTy, &AlignSource);
3219 return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress()), Align);
3221 return CGF.EmitPointerWithAlignment(Base, &AlignSource);
3224 LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
3225 bool IsLowerBound) {
3228 dyn_cast<OMPArraySectionExpr>(E->getBase()->IgnoreParenImpCasts()))
3229 BaseTy = OMPArraySectionExpr::getBaseOriginalType(ASE);
3231 BaseTy = E->getBase()->getType();
3232 QualType ResultExprTy;
3233 if (auto *AT = getContext().getAsArrayType(BaseTy))
3234 ResultExprTy = AT->getElementType();
3236 ResultExprTy = BaseTy->getPointeeType();
3237 llvm::Value *Idx = nullptr;
3238 if (IsLowerBound || E->getColonLoc().isInvalid()) {
3239 // Requesting lower bound or upper bound, but without provided length and
3240 // without ':' symbol for the default length -> length = 1.
3241 // Idx = LowerBound ?: 0;
3242 if (auto *LowerBound = E->getLowerBound()) {
3243 Idx = Builder.CreateIntCast(
3244 EmitScalarExpr(LowerBound), IntPtrTy,
3245 LowerBound->getType()->hasSignedIntegerRepresentation());
3247 Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
3249 // Try to emit length or lower bound as constant. If this is possible, 1
3250 // is subtracted from constant length or lower bound. Otherwise, emit LLVM
3251 // IR (LB + Len) - 1.
3252 auto &C = CGM.getContext();
3253 auto *Length = E->getLength();
3254 llvm::APSInt ConstLength;
3256 // Idx = LowerBound + Length - 1;
3257 if (Length->isIntegerConstantExpr(ConstLength, C)) {
3258 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3261 auto *LowerBound = E->getLowerBound();
3262 llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
3263 if (LowerBound && LowerBound->isIntegerConstantExpr(ConstLowerBound, C)) {
3264 ConstLowerBound = ConstLowerBound.zextOrTrunc(PointerWidthInBits);
3265 LowerBound = nullptr;
3269 else if (!LowerBound)
3272 if (Length || LowerBound) {
3273 auto *LowerBoundVal =
3275 ? Builder.CreateIntCast(
3276 EmitScalarExpr(LowerBound), IntPtrTy,
3277 LowerBound->getType()->hasSignedIntegerRepresentation())
3278 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
3281 ? Builder.CreateIntCast(
3282 EmitScalarExpr(Length), IntPtrTy,
3283 Length->getType()->hasSignedIntegerRepresentation())
3284 : llvm::ConstantInt::get(IntPtrTy, ConstLength);
3285 Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
3287 !getLangOpts().isSignedOverflowDefined());
3288 if (Length && LowerBound) {
3289 Idx = Builder.CreateSub(
3290 Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
3291 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3294 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
3296 // Idx = ArraySize - 1;
3297 QualType ArrayTy = BaseTy->isPointerType()
3298 ? E->getBase()->IgnoreParenImpCasts()->getType()
3300 if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) {
3301 Length = VAT->getSizeExpr();
3302 if (Length->isIntegerConstantExpr(ConstLength, C))
3305 auto *CAT = C.getAsConstantArrayType(ArrayTy);
3306 ConstLength = CAT->getSize();
3309 auto *LengthVal = Builder.CreateIntCast(
3310 EmitScalarExpr(Length), IntPtrTy,
3311 Length->getType()->hasSignedIntegerRepresentation());
3312 Idx = Builder.CreateSub(
3313 LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
3314 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3316 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3318 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
3324 Address EltPtr = Address::invalid();
3325 AlignmentSource AlignSource;
3326 if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
3327 // The base must be a pointer, which is not an aggregate. Emit
3328 // it. It needs to be emitted first in case it's what captures
3331 emitOMPArraySectionBase(*this, E->getBase(), AlignSource, BaseTy,
3332 VLA->getElementType(), IsLowerBound);
3333 // The element count here is the total number of non-VLA elements.
3334 llvm::Value *NumElements = getVLASize(VLA).first;
3336 // Effectively, the multiply by the VLA size is part of the GEP.
3337 // GEP indexes are signed, and scaling an index isn't permitted to
3338 // signed-overflow, so we use the same semantics for our explicit
3339 // multiply. We suppress this if overflow is not undefined behavior.
3340 if (getLangOpts().isSignedOverflowDefined())
3341 Idx = Builder.CreateMul(Idx, NumElements);
3343 Idx = Builder.CreateNSWMul(Idx, NumElements);
3344 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(),
3345 !getLangOpts().isSignedOverflowDefined());
3346 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3347 // If this is A[i] where A is an array, the frontend will have decayed the
3348 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3349 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3350 // "gep x, i" here. Emit one "gep A, 0, i".
3351 assert(Array->getType()->isArrayType() &&
3352 "Array to pointer decay must have array source type!");
3354 // For simple multidimensional array indexing, set the 'accessed' flag for
3355 // better bounds-checking of the base expression.
3356 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3357 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3359 ArrayLV = EmitLValue(Array);
3361 // Propagate the alignment from the array itself to the result.
3362 EltPtr = emitArraySubscriptGEP(
3363 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
3364 ResultExprTy, !getLangOpts().isSignedOverflowDefined());
3365 AlignSource = ArrayLV.getAlignmentSource();
3367 Address Base = emitOMPArraySectionBase(*this, E->getBase(), AlignSource,
3368 BaseTy, ResultExprTy, IsLowerBound);
3369 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy,
3370 !getLangOpts().isSignedOverflowDefined());
3373 return MakeAddrLValue(EltPtr, ResultExprTy, AlignSource);
3376 LValue CodeGenFunction::
3377 EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
3378 // Emit the base vector as an l-value.
3381 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
3383 // If it is a pointer to a vector, emit the address and form an lvalue with
3385 AlignmentSource AlignSource;
3386 Address Ptr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
3387 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
3388 Base = MakeAddrLValue(Ptr, PT->getPointeeType(), AlignSource);
3389 Base.getQuals().removeObjCGCAttr();
3390 } else if (E->getBase()->isGLValue()) {
3391 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
3392 // emit the base as an lvalue.
3393 assert(E->getBase()->getType()->isVectorType());
3394 Base = EmitLValue(E->getBase());
3396 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
3397 assert(E->getBase()->getType()->isVectorType() &&
3398 "Result must be a vector");
3399 llvm::Value *Vec = EmitScalarExpr(E->getBase());
3401 // Store the vector to memory (because LValue wants an address).
3402 Address VecMem = CreateMemTemp(E->getBase()->getType());
3403 Builder.CreateStore(Vec, VecMem);
3404 Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
3405 AlignmentSource::Decl);
3409 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
3411 // Encode the element access list into a vector of unsigned indices.
3412 SmallVector<uint32_t, 4> Indices;
3413 E->getEncodedElementAccess(Indices);
3415 if (Base.isSimple()) {
3416 llvm::Constant *CV =
3417 llvm::ConstantDataVector::get(getLLVMContext(), Indices);
3418 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
3419 Base.getAlignmentSource());
3421 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
3423 llvm::Constant *BaseElts = Base.getExtVectorElts();
3424 SmallVector<llvm::Constant *, 4> CElts;
3426 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
3427 CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
3428 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
3429 return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
3430 Base.getAlignmentSource());
3433 LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
3434 Expr *BaseExpr = E->getBase();
3436 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
3439 AlignmentSource AlignSource;
3440 Address Addr = EmitPointerWithAlignment(BaseExpr, &AlignSource);
3441 QualType PtrTy = BaseExpr->getType()->getPointeeType();
3442 SanitizerSet SkippedChecks;
3443 bool IsBaseCXXThis = IsWrappedCXXThis(BaseExpr);
3445 SkippedChecks.set(SanitizerKind::Alignment, true);
3446 if (IsBaseCXXThis || isa<DeclRefExpr>(BaseExpr))
3447 SkippedChecks.set(SanitizerKind::Null, true);
3448 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy,
3449 /*Alignment=*/CharUnits::Zero(), SkippedChecks);
3450 BaseLV = MakeAddrLValue(Addr, PtrTy, AlignSource);
3452 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
3454 NamedDecl *ND = E->getMemberDecl();
3455 if (auto *Field = dyn_cast<FieldDecl>(ND)) {
3456 LValue LV = EmitLValueForField(BaseLV, Field);
3457 setObjCGCLValueClass(getContext(), E, LV);
3461 if (auto *VD = dyn_cast<VarDecl>(ND))
3462 return EmitGlobalVarDeclLValue(*this, E, VD);
3464 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
3465 return EmitFunctionDeclLValue(*this, E, FD);
3467 llvm_unreachable("Unhandled member declaration!");
3470 /// Given that we are currently emitting a lambda, emit an l-value for
3471 /// one of its members.
3472 LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
3473 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
3474 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
3475 QualType LambdaTagType =
3476 getContext().getTagDeclType(Field->getParent());
3477 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
3478 return EmitLValueForField(LambdaLV, Field);
3481 /// Drill down to the storage of a field without walking into
3482 /// reference types.
3484 /// The resulting address doesn't necessarily have the right type.
3485 static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
3486 const FieldDecl *field) {
3487 const RecordDecl *rec = field->getParent();
3490 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
3493 // Adjust the alignment down to the given offset.
3494 // As a special case, if the LLVM field index is 0, we know that this
3496 assert((idx != 0 || CGF.getContext().getASTRecordLayout(rec)
3497 .getFieldOffset(field->getFieldIndex()) == 0) &&
3498 "LLVM field at index zero had non-zero offset?");
3500 auto &recLayout = CGF.getContext().getASTRecordLayout(rec);
3501 auto offsetInBits = recLayout.getFieldOffset(field->getFieldIndex());
3502 offset = CGF.getContext().toCharUnitsFromBits(offsetInBits);
3505 return CGF.Builder.CreateStructGEP(base, idx, offset, field->getName());
3508 LValue CodeGenFunction::EmitLValueForField(LValue base,
3509 const FieldDecl *field) {
3510 AlignmentSource fieldAlignSource =
3511 getFieldAlignmentSource(base.getAlignmentSource());
3513 if (field->isBitField()) {
3514 const CGRecordLayout &RL =
3515 CGM.getTypes().getCGRecordLayout(field->getParent());
3516 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
3517 Address Addr = base.getAddress();
3518 unsigned Idx = RL.getLLVMFieldNo(field);
3520 // For structs, we GEP to the field that the record layout suggests.
3521 Addr = Builder.CreateStructGEP(Addr, Idx, Info.StorageOffset,
3523 // Get the access type.
3524 llvm::Type *FieldIntTy =
3525 llvm::Type::getIntNTy(getLLVMContext(), Info.StorageSize);
3526 if (Addr.getElementType() != FieldIntTy)
3527 Addr = Builder.CreateElementBitCast(Addr, FieldIntTy);
3529 QualType fieldType =
3530 field->getType().withCVRQualifiers(base.getVRQualifiers());
3531 return LValue::MakeBitfield(Addr, Info, fieldType, fieldAlignSource);
3534 const RecordDecl *rec = field->getParent();
3535 QualType type = field->getType();
3537 bool mayAlias = rec->hasAttr<MayAliasAttr>();
3539 Address addr = base.getAddress();
3540 unsigned cvr = base.getVRQualifiers();
3541 bool TBAAPath = CGM.getCodeGenOpts().StructPathTBAA;
3542 if (rec->isUnion()) {
3543 // For unions, there is no pointer adjustment.
3544 assert(!type->isReferenceType() && "union has reference member");
3545 // TODO: handle path-aware TBAA for union.
3548 // For structs, we GEP to the field that the record layout suggests.
3549 addr = emitAddrOfFieldStorage(*this, addr, field);
3551 // If this is a reference field, load the reference right now.
3552 if (const ReferenceType *refType = type->getAs<ReferenceType>()) {
3553 llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
3554 if (cvr & Qualifiers::Volatile) load->setVolatile(true);
3556 // Loading the reference will disable path-aware TBAA.
3558 if (CGM.shouldUseTBAA()) {
3561 tbaa = CGM.getTBAAInfo(getContext().CharTy);
3563 tbaa = CGM.getTBAAInfo(type);
3565 CGM.DecorateInstructionWithTBAA(load, tbaa);
3569 type = refType->getPointeeType();
3571 CharUnits alignment =
3572 getNaturalTypeAlignment(type, &fieldAlignSource, /*pointee*/ true);
3573 addr = Address(load, alignment);
3575 // Qualifiers on the struct don't apply to the referencee, and
3576 // we'll pick up CVR from the actual type later, so reset these
3577 // additional qualifiers now.
3582 // Make sure that the address is pointing to the right type. This is critical
3583 // for both unions and structs. A union needs a bitcast, a struct element
3584 // will need a bitcast if the LLVM type laid out doesn't match the desired
3586 addr = Builder.CreateElementBitCast(addr,
3587 CGM.getTypes().ConvertTypeForMem(type),
3590 if (field->hasAttr<AnnotateAttr>())
3591 addr = EmitFieldAnnotations(field, addr);
3593 LValue LV = MakeAddrLValue(addr, type, fieldAlignSource);
3594 LV.getQuals().addCVRQualifiers(cvr);
3596 const ASTRecordLayout &Layout =
3597 getContext().getASTRecordLayout(field->getParent());
3598 // Set the base type to be the base type of the base LValue and
3599 // update offset to be relative to the base type.
3600 LV.setTBAABaseType(mayAlias ? getContext().CharTy : base.getTBAABaseType());
3601 LV.setTBAAOffset(mayAlias ? 0 : base.getTBAAOffset() +
3602 Layout.getFieldOffset(field->getFieldIndex()) /
3603 getContext().getCharWidth());
3606 // __weak attribute on a field is ignored.
3607 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
3608 LV.getQuals().removeObjCGCAttr();
3610 // Fields of may_alias structs act like 'char' for TBAA purposes.
3611 // FIXME: this should get propagated down through anonymous structs
3613 if (mayAlias && LV.getTBAAInfo())
3614 LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy));
3620 CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
3621 const FieldDecl *Field) {
3622 QualType FieldType = Field->getType();
3624 if (!FieldType->isReferenceType())
3625 return EmitLValueForField(Base, Field);
3627 Address V = emitAddrOfFieldStorage(*this, Base.getAddress(), Field);
3629 // Make sure that the address is pointing to the right type.
3630 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
3631 V = Builder.CreateElementBitCast(V, llvmType, Field->getName());
3633 // TODO: access-path TBAA?
3634 auto FieldAlignSource = getFieldAlignmentSource(Base.getAlignmentSource());
3635 return MakeAddrLValue(V, FieldType, FieldAlignSource);
3638 LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
3639 if (E->isFileScope()) {
3640 ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
3641 return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl);
3643 if (E->getType()->isVariablyModifiedType())
3644 // make sure to emit the VLA size.
3645 EmitVariablyModifiedType(E->getType());
3647 Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
3648 const Expr *InitExpr = E->getInitializer();
3649 LValue Result = MakeAddrLValue(DeclPtr, E->getType(), AlignmentSource::Decl);
3651 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
3657 LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
3658 if (!E->isGLValue())
3659 // Initializing an aggregate temporary in C++11: T{...}.
3660 return EmitAggExprToLValue(E);
3662 // An lvalue initializer list must be initializing a reference.
3663 assert(E->isTransparent() && "non-transparent glvalue init list");
3664 return EmitLValue(E->getInit(0));
3667 /// Emit the operand of a glvalue conditional operator. This is either a glvalue
3668 /// or a (possibly-parenthesized) throw-expression. If this is a throw, no
3669 /// LValue is returned and the current block has been terminated.
3670 static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
3671 const Expr *Operand) {
3672 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
3673 CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
3677 return CGF.EmitLValue(Operand);
3680 LValue CodeGenFunction::
3681 EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
3682 if (!expr->isGLValue()) {
3683 // ?: here should be an aggregate.
3684 assert(hasAggregateEvaluationKind(expr->getType()) &&
3685 "Unexpected conditional operator!");
3686 return EmitAggExprToLValue(expr);
3689 OpaqueValueMapping binding(*this, expr);
3691 const Expr *condExpr = expr->getCond();
3693 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
3694 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
3695 if (!CondExprBool) std::swap(live, dead);
3697 if (!ContainsLabel(dead)) {
3698 // If the true case is live, we need to track its region.
3700 incrementProfileCounter(expr);
3701 return EmitLValue(live);
3705 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
3706 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
3707 llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
3709 ConditionalEvaluation eval(*this);
3710 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr));
3712 // Any temporaries created here are conditional.
3713 EmitBlock(lhsBlock);
3714 incrementProfileCounter(expr);
3716 Optional<LValue> lhs =
3717 EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
3720 if (lhs && !lhs->isSimple())
3721 return EmitUnsupportedLValue(expr, "conditional operator");
3723 lhsBlock = Builder.GetInsertBlock();
3725 Builder.CreateBr(contBlock);
3727 // Any temporaries created here are conditional.
3728 EmitBlock(rhsBlock);
3730 Optional<LValue> rhs =
3731 EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
3733 if (rhs && !rhs->isSimple())
3734 return EmitUnsupportedLValue(expr, "conditional operator");
3735 rhsBlock = Builder.GetInsertBlock();
3737 EmitBlock(contBlock);
3740 llvm::PHINode *phi = Builder.CreatePHI(lhs->getPointer()->getType(),
3742 phi->addIncoming(lhs->getPointer(), lhsBlock);
3743 phi->addIncoming(rhs->getPointer(), rhsBlock);
3744 Address result(phi, std::min(lhs->getAlignment(), rhs->getAlignment()));
3745 AlignmentSource alignSource =
3746 std::max(lhs->getAlignmentSource(), rhs->getAlignmentSource());
3747 return MakeAddrLValue(result, expr->getType(), alignSource);
3749 assert((lhs || rhs) &&
3750 "both operands of glvalue conditional are throw-expressions?");
3751 return lhs ? *lhs : *rhs;
3755 /// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
3756 /// type. If the cast is to a reference, we can have the usual lvalue result,
3757 /// otherwise if a cast is needed by the code generator in an lvalue context,
3758 /// then it must mean that we need the address of an aggregate in order to
3759 /// access one of its members. This can happen for all the reasons that casts
3760 /// are permitted with aggregate result, including noop aggregate casts, and
3761 /// cast from scalar to union.
3762 LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
3763 switch (E->getCastKind()) {
3766 case CK_ArrayToPointerDecay:
3767 case CK_FunctionToPointerDecay:
3768 case CK_NullToMemberPointer:
3769 case CK_NullToPointer:
3770 case CK_IntegralToPointer:
3771 case CK_PointerToIntegral:
3772 case CK_PointerToBoolean:
3773 case CK_VectorSplat:
3774 case CK_IntegralCast:
3775 case CK_BooleanToSignedIntegral:
3776 case CK_IntegralToBoolean:
3777 case CK_IntegralToFloating:
3778 case CK_FloatingToIntegral:
3779 case CK_FloatingToBoolean:
3780 case CK_FloatingCast:
3781 case CK_FloatingRealToComplex:
3782 case CK_FloatingComplexToReal:
3783 case CK_FloatingComplexToBoolean:
3784 case CK_FloatingComplexCast:
3785 case CK_FloatingComplexToIntegralComplex:
3786 case CK_IntegralRealToComplex:
3787 case CK_IntegralComplexToReal:
3788 case CK_IntegralComplexToBoolean:
3789 case CK_IntegralComplexCast:
3790 case CK_IntegralComplexToFloatingComplex:
3791 case CK_DerivedToBaseMemberPointer:
3792 case CK_BaseToDerivedMemberPointer:
3793 case CK_MemberPointerToBoolean:
3794 case CK_ReinterpretMemberPointer:
3795 case CK_AnyPointerToBlockPointerCast:
3796 case CK_ARCProduceObject:
3797 case CK_ARCConsumeObject:
3798 case CK_ARCReclaimReturnedObject:
3799 case CK_ARCExtendBlockObject:
3800 case CK_CopyAndAutoreleaseBlockObject:
3801 case CK_AddressSpaceConversion:
3802 case CK_IntToOCLSampler:
3803 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
3806 llvm_unreachable("dependent cast kind in IR gen!");
3808 case CK_BuiltinFnToFnPtr:
3809 llvm_unreachable("builtin functions are handled elsewhere");
3811 // These are never l-values; just use the aggregate emission code.
3812 case CK_NonAtomicToAtomic:
3813 case CK_AtomicToNonAtomic:
3814 return EmitAggExprToLValue(E);
3817 LValue LV = EmitLValue(E->getSubExpr());
3818 Address V = LV.getAddress();
3819 const auto *DCE = cast<CXXDynamicCastExpr>(E);
3820 return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
3823 case CK_ConstructorConversion:
3824 case CK_UserDefinedConversion:
3825 case CK_CPointerToObjCPointerCast:
3826 case CK_BlockPointerToObjCPointerCast:
3828 case CK_LValueToRValue:
3829 return EmitLValue(E->getSubExpr());
3831 case CK_UncheckedDerivedToBase:
3832 case CK_DerivedToBase: {
3833 const RecordType *DerivedClassTy =
3834 E->getSubExpr()->getType()->getAs<RecordType>();
3835 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
3837 LValue LV = EmitLValue(E->getSubExpr());
3838 Address This = LV.getAddress();
3840 // Perform the derived-to-base conversion
3841 Address Base = GetAddressOfBaseClass(
3842 This, DerivedClassDecl, E->path_begin(), E->path_end(),
3843 /*NullCheckValue=*/false, E->getExprLoc());
3845 return MakeAddrLValue(Base, E->getType(), LV.getAlignmentSource());
3848 return EmitAggExprToLValue(E);
3849 case CK_BaseToDerived: {
3850 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
3851 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
3853 LValue LV = EmitLValue(E->getSubExpr());
3855 // Perform the base-to-derived conversion
3857 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
3858 E->path_begin(), E->path_end(),
3859 /*NullCheckValue=*/false);
3861 // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
3862 // performed and the object is not of the derived type.
3863 if (sanitizePerformTypeCheck())
3864 EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
3865 Derived.getPointer(), E->getType());
3867 if (SanOpts.has(SanitizerKind::CFIDerivedCast))
3868 EmitVTablePtrCheckForCast(E->getType(), Derived.getPointer(),
3869 /*MayBeNull=*/false,
3870 CFITCK_DerivedCast, E->getLocStart());
3872 return MakeAddrLValue(Derived, E->getType(), LV.getAlignmentSource());
3874 case CK_LValueBitCast: {
3875 // This must be a reinterpret_cast (or c-style equivalent).
3876 const auto *CE = cast<ExplicitCastExpr>(E);
3878 CGM.EmitExplicitCastExprType(CE, this);
3879 LValue LV = EmitLValue(E->getSubExpr());
3880 Address V = Builder.CreateBitCast(LV.getAddress(),
3881 ConvertType(CE->getTypeAsWritten()));
3883 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
3884 EmitVTablePtrCheckForCast(E->getType(), V.getPointer(),
3885 /*MayBeNull=*/false,
3886 CFITCK_UnrelatedCast, E->getLocStart());
3888 return MakeAddrLValue(V, E->getType(), LV.getAlignmentSource());
3890 case CK_ObjCObjectLValueCast: {
3891 LValue LV = EmitLValue(E->getSubExpr());
3892 Address V = Builder.CreateElementBitCast(LV.getAddress(),
3893 ConvertType(E->getType()));
3894 return MakeAddrLValue(V, E->getType(), LV.getAlignmentSource());
3896 case CK_ZeroToOCLQueue:
3897 llvm_unreachable("NULL to OpenCL queue lvalue cast is not valid");
3898 case CK_ZeroToOCLEvent:
3899 llvm_unreachable("NULL to OpenCL event lvalue cast is not valid");
3902 llvm_unreachable("Unhandled lvalue cast kind?");
3905 LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
3906 assert(OpaqueValueMappingData::shouldBindAsLValue(e));
3907 return getOpaqueLValueMapping(e);
3910 RValue CodeGenFunction::EmitRValueForField(LValue LV,
3911 const FieldDecl *FD,
3912 SourceLocation Loc) {
3913 QualType FT = FD->getType();
3914 LValue FieldLV = EmitLValueForField(LV, FD);
3915 switch (getEvaluationKind(FT)) {
3917 return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
3919 return FieldLV.asAggregateRValue();
3921 // This routine is used to load fields one-by-one to perform a copy, so
3922 // don't load reference fields.
3923 if (FD->getType()->isReferenceType())
3924 return RValue::get(FieldLV.getPointer());
3925 return EmitLoadOfLValue(FieldLV, Loc);
3927 llvm_unreachable("bad evaluation kind");
3930 //===--------------------------------------------------------------------===//
3931 // Expression Emission
3932 //===--------------------------------------------------------------------===//
3934 RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
3935 ReturnValueSlot ReturnValue) {
3936 // Builtins never have block type.
3937 if (E->getCallee()->getType()->isBlockPointerType())
3938 return EmitBlockCallExpr(E, ReturnValue);
3940 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
3941 return EmitCXXMemberCallExpr(CE, ReturnValue);
3943 if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
3944 return EmitCUDAKernelCallExpr(CE, ReturnValue);
3946 if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
3947 if (const CXXMethodDecl *MD =
3948 dyn_cast_or_null<CXXMethodDecl>(CE->getCalleeDecl()))
3949 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
3951 CGCallee callee = EmitCallee(E->getCallee());
3953 if (callee.isBuiltin()) {
3954 return EmitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(),
3958 if (callee.isPseudoDestructor()) {
3959 return EmitCXXPseudoDestructorExpr(callee.getPseudoDestructorExpr());
3962 return EmitCall(E->getCallee()->getType(), callee, E, ReturnValue);
3965 /// Emit a CallExpr without considering whether it might be a subclass.
3966 RValue CodeGenFunction::EmitSimpleCallExpr(const CallExpr *E,
3967 ReturnValueSlot ReturnValue) {
3968 CGCallee Callee = EmitCallee(E->getCallee());
3969 return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue);
3972 static CGCallee EmitDirectCallee(CodeGenFunction &CGF, const FunctionDecl *FD) {
3973 if (auto builtinID = FD->getBuiltinID()) {
3974 return CGCallee::forBuiltin(builtinID, FD);
3977 llvm::Constant *calleePtr = EmitFunctionDeclPointer(CGF.CGM, FD);
3978 return CGCallee::forDirect(calleePtr, FD);
3981 CGCallee CodeGenFunction::EmitCallee(const Expr *E) {
3982 E = E->IgnoreParens();
3984 // Look through function-to-pointer decay.
3985 if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) {
3986 if (ICE->getCastKind() == CK_FunctionToPointerDecay ||
3987 ICE->getCastKind() == CK_BuiltinFnToFnPtr) {
3988 return EmitCallee(ICE->getSubExpr());
3991 // Resolve direct calls.
3992 } else if (auto DRE = dyn_cast<DeclRefExpr>(E)) {
3993 if (auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
3994 return EmitDirectCallee(*this, FD);
3996 } else if (auto ME = dyn_cast<MemberExpr>(E)) {
3997 if (auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) {
3998 EmitIgnoredExpr(ME->getBase());
3999 return EmitDirectCallee(*this, FD);
4002 // Look through template substitutions.
4003 } else if (auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
4004 return EmitCallee(NTTP->getReplacement());
4006 // Treat pseudo-destructor calls differently.
4007 } else if (auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) {
4008 return CGCallee::forPseudoDestructor(PDE);
4011 // Otherwise, we have an indirect reference.
4012 llvm::Value *calleePtr;
4013 QualType functionType;
4014 if (auto ptrType = E->getType()->getAs<PointerType>()) {
4015 calleePtr = EmitScalarExpr(E);
4016 functionType = ptrType->getPointeeType();
4018 functionType = E->getType();
4019 calleePtr = EmitLValue(E).getPointer();
4021 assert(functionType->isFunctionType());
4022 CGCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(),
4023 E->getReferencedDeclOfCallee());
4024 CGCallee callee(calleeInfo, calleePtr);
4028 LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
4029 // Comma expressions just emit their LHS then their RHS as an l-value.
4030 if (E->getOpcode() == BO_Comma) {
4031 EmitIgnoredExpr(E->getLHS());
4032 EnsureInsertPoint();
4033 return EmitLValue(E->getRHS());
4036 if (E->getOpcode() == BO_PtrMemD ||
4037 E->getOpcode() == BO_PtrMemI)
4038 return EmitPointerToDataMemberBinaryExpr(E);
4040 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
4042 // Note that in all of these cases, __block variables need the RHS
4043 // evaluated first just in case the variable gets moved by the RHS.
4045 switch (getEvaluationKind(E->getType())) {
4047 switch (E->getLHS()->getType().getObjCLifetime()) {
4048 case Qualifiers::OCL_Strong:
4049 return EmitARCStoreStrong(E, /*ignored*/ false).first;
4051 case Qualifiers::OCL_Autoreleasing:
4052 return EmitARCStoreAutoreleasing(E).first;
4054 // No reason to do any of these differently.
4055 case Qualifiers::OCL_None:
4056 case Qualifiers::OCL_ExplicitNone:
4057 case Qualifiers::OCL_Weak:
4061 RValue RV = EmitAnyExpr(E->getRHS());
4062 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
4063 EmitStoreThroughLValue(RV, LV);
4068 return EmitComplexAssignmentLValue(E);
4071 return EmitAggExprToLValue(E);
4073 llvm_unreachable("bad evaluation kind");
4076 LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
4077 RValue RV = EmitCallExpr(E);
4080 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
4081 AlignmentSource::Decl);
4083 assert(E->getCallReturnType(getContext())->isReferenceType() &&
4084 "Can't have a scalar return unless the return type is a "
4087 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
4090 LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
4091 // FIXME: This shouldn't require another copy.
4092 return EmitAggExprToLValue(E);
4095 LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
4096 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
4097 && "binding l-value to type which needs a temporary");
4098 AggValueSlot Slot = CreateAggTemp(E->getType());
4099 EmitCXXConstructExpr(E, Slot);
4100 return MakeAddrLValue(Slot.getAddress(), E->getType(),
4101 AlignmentSource::Decl);
4105 CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
4106 return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType());
4109 Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
4110 return Builder.CreateElementBitCast(CGM.GetAddrOfUuidDescriptor(E),
4111 ConvertType(E->getType()));
4114 LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
4115 return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(),
4116 AlignmentSource::Decl);
4120 CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
4121 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
4122 Slot.setExternallyDestructed();
4123 EmitAggExpr(E->getSubExpr(), Slot);
4124 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
4125 return MakeAddrLValue(Slot.getAddress(), E->getType(),
4126 AlignmentSource::Decl);
4130 CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
4131 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
4132 EmitLambdaExpr(E, Slot);
4133 return MakeAddrLValue(Slot.getAddress(), E->getType(),
4134 AlignmentSource::Decl);
4137 LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
4138 RValue RV = EmitObjCMessageExpr(E);
4141 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
4142 AlignmentSource::Decl);
4144 assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
4145 "Can't have a scalar return unless the return type is a "
4148 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
4151 LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
4153 CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
4154 return MakeAddrLValue(V, E->getType(), AlignmentSource::Decl);
4157 llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
4158 const ObjCIvarDecl *Ivar) {
4159 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
4162 LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
4163 llvm::Value *BaseValue,
4164 const ObjCIvarDecl *Ivar,
4165 unsigned CVRQualifiers) {
4166 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
4167 Ivar, CVRQualifiers);
4170 LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
4171 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
4172 llvm::Value *BaseValue = nullptr;
4173 const Expr *BaseExpr = E->getBase();
4174 Qualifiers BaseQuals;
4177 BaseValue = EmitScalarExpr(BaseExpr);
4178 ObjectTy = BaseExpr->getType()->getPointeeType();
4179 BaseQuals = ObjectTy.getQualifiers();
4181 LValue BaseLV = EmitLValue(BaseExpr);
4182 BaseValue = BaseLV.getPointer();
4183 ObjectTy = BaseExpr->getType();
4184 BaseQuals = ObjectTy.getQualifiers();
4188 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
4189 BaseQuals.getCVRQualifiers());
4190 setObjCGCLValueClass(getContext(), E, LV);
4194 LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
4195 // Can only get l-value for message expression returning aggregate type
4196 RValue RV = EmitAnyExprToTemp(E);
4197 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
4198 AlignmentSource::Decl);
4201 RValue CodeGenFunction::EmitCall(QualType CalleeType, const CGCallee &OrigCallee,
4202 const CallExpr *E, ReturnValueSlot ReturnValue,
4203 llvm::Value *Chain) {
4204 // Get the actual function type. The callee type will always be a pointer to
4205 // function type or a block pointer type.
4206 assert(CalleeType->isFunctionPointerType() &&
4207 "Call must have function pointer type!");
4209 const Decl *TargetDecl = OrigCallee.getAbstractInfo().getCalleeDecl();
4211 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
4212 // We can only guarantee that a function is called from the correct
4213 // context/function based on the appropriate target attributes,
4214 // so only check in the case where we have both always_inline and target
4215 // since otherwise we could be making a conditional call after a check for
4216 // the proper cpu features (and it won't cause code generation issues due to
4217 // function based code generation).
4218 if (TargetDecl->hasAttr<AlwaysInlineAttr>() &&
4219 TargetDecl->hasAttr<TargetAttr>())
4220 checkTargetFeatures(E, FD);
4222 CalleeType = getContext().getCanonicalType(CalleeType);
4224 const auto *FnType =
4225 cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
4227 CGCallee Callee = OrigCallee;
4229 if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
4230 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4231 if (llvm::Constant *PrefixSig =
4232 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
4233 SanitizerScope SanScope(this);
4234 llvm::Constant *FTRTTIConst =
4235 CGM.GetAddrOfRTTIDescriptor(QualType(FnType, 0), /*ForEH=*/true);
4236 llvm::Type *PrefixStructTyElems[] = {
4237 PrefixSig->getType(),
4238 FTRTTIConst->getType()
4240 llvm::StructType *PrefixStructTy = llvm::StructType::get(
4241 CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true);
4243 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4245 llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
4246 CalleePtr, llvm::PointerType::getUnqual(PrefixStructTy));
4247 llvm::Value *CalleeSigPtr =
4248 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0);
4249 llvm::Value *CalleeSig =
4250 Builder.CreateAlignedLoad(CalleeSigPtr, getIntAlign());
4251 llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
4253 llvm::BasicBlock *Cont = createBasicBlock("cont");
4254 llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
4255 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
4257 EmitBlock(TypeCheck);
4258 llvm::Value *CalleeRTTIPtr =
4259 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1);
4260 llvm::Value *CalleeRTTI =
4261 Builder.CreateAlignedLoad(CalleeRTTIPtr, getPointerAlign());
4262 llvm::Value *CalleeRTTIMatch =
4263 Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
4264 llvm::Constant *StaticData[] = {
4265 EmitCheckSourceLocation(E->getLocStart()),
4266 EmitCheckTypeDescriptor(CalleeType)
4268 EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
4269 SanitizerHandler::FunctionTypeMismatch, StaticData, CalleePtr);
4271 Builder.CreateBr(Cont);
4276 // If we are checking indirect calls and this call is indirect, check that the
4277 // function pointer is a member of the bit set for the function type.
4278 if (SanOpts.has(SanitizerKind::CFIICall) &&
4279 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4280 SanitizerScope SanScope(this);
4281 EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
4283 llvm::Metadata *MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0));
4284 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
4286 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4287 llvm::Value *CastedCallee = Builder.CreateBitCast(CalleePtr, Int8PtrTy);
4288 llvm::Value *TypeTest = Builder.CreateCall(
4289 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedCallee, TypeId});
4291 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
4292 llvm::Constant *StaticData[] = {
4293 llvm::ConstantInt::get(Int8Ty, CFITCK_ICall),
4294 EmitCheckSourceLocation(E->getLocStart()),
4295 EmitCheckTypeDescriptor(QualType(FnType, 0)),
4297 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
4298 EmitCfiSlowPathCheck(SanitizerKind::CFIICall, TypeTest, CrossDsoTypeId,
4299 CastedCallee, StaticData);
4301 EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIICall),
4302 SanitizerHandler::CFICheckFail, StaticData,
4303 {CastedCallee, llvm::UndefValue::get(IntPtrTy)});
4309 Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
4310 CGM.getContext().VoidPtrTy);
4312 // C++17 requires that we evaluate arguments to a call using assignment syntax
4313 // right-to-left, and that we evaluate arguments to certain other operators
4314 // left-to-right. Note that we allow this to override the order dictated by
4315 // the calling convention on the MS ABI, which means that parameter
4316 // destruction order is not necessarily reverse construction order.
4317 // FIXME: Revisit this based on C++ committee response to unimplementability.
4318 EvaluationOrder Order = EvaluationOrder::Default;
4319 if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
4320 if (OCE->isAssignmentOp())
4321 Order = EvaluationOrder::ForceRightToLeft;
4323 switch (OCE->getOperator()) {
4325 case OO_GreaterGreater:
4330 Order = EvaluationOrder::ForceLeftToRight;
4338 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(),
4339 E->getDirectCallee(), /*ParamsToSkip*/ 0, Order);
4341 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
4342 Args, FnType, /*isChainCall=*/Chain);
4345 // If the expression that denotes the called function has a type
4346 // that does not include a prototype, [the default argument
4347 // promotions are performed]. If the number of arguments does not
4348 // equal the number of parameters, the behavior is undefined. If
4349 // the function is defined with a type that includes a prototype,
4350 // and either the prototype ends with an ellipsis (, ...) or the
4351 // types of the arguments after promotion are not compatible with
4352 // the types of the parameters, the behavior is undefined. If the
4353 // function is defined with a type that does not include a
4354 // prototype, and the types of the arguments after promotion are
4355 // not compatible with those of the parameters after promotion,
4356 // the behavior is undefined [except in some trivial cases].
4357 // That is, in the general case, we should assume that a call
4358 // through an unprototyped function type works like a *non-variadic*
4359 // call. The way we make this work is to cast to the exact type
4360 // of the promoted arguments.
4362 // Chain calls use this same code path to add the invisible chain parameter
4363 // to the function type.
4364 if (isa<FunctionNoProtoType>(FnType) || Chain) {
4365 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
4366 CalleeTy = CalleeTy->getPointerTo();
4368 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4369 CalleePtr = Builder.CreateBitCast(CalleePtr, CalleeTy, "callee.knr.cast");
4370 Callee.setFunctionPointer(CalleePtr);
4373 return EmitCall(FnInfo, Callee, ReturnValue, Args);
4376 LValue CodeGenFunction::
4377 EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
4378 Address BaseAddr = Address::invalid();
4379 if (E->getOpcode() == BO_PtrMemI) {
4380 BaseAddr = EmitPointerWithAlignment(E->getLHS());
4382 BaseAddr = EmitLValue(E->getLHS()).getAddress();
4385 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
4387 const MemberPointerType *MPT
4388 = E->getRHS()->getType()->getAs<MemberPointerType>();
4390 AlignmentSource AlignSource;
4391 Address MemberAddr =
4392 EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT,
4395 return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), AlignSource);
4398 /// Given the address of a temporary variable, produce an r-value of
4400 RValue CodeGenFunction::convertTempToRValue(Address addr,
4402 SourceLocation loc) {
4403 LValue lvalue = MakeAddrLValue(addr, type, AlignmentSource::Decl);
4404 switch (getEvaluationKind(type)) {
4406 return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
4408 return lvalue.asAggregateRValue();
4410 return RValue::get(EmitLoadOfScalar(lvalue, loc));
4412 llvm_unreachable("bad evaluation kind");
4415 void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
4416 assert(Val->getType()->isFPOrFPVectorTy());
4417 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
4420 llvm::MDBuilder MDHelper(getLLVMContext());
4421 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
4423 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
4427 struct LValueOrRValue {
4433 static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
4434 const PseudoObjectExpr *E,
4436 AggValueSlot slot) {
4437 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
4439 // Find the result expression, if any.
4440 const Expr *resultExpr = E->getResultExpr();
4441 LValueOrRValue result;
4443 for (PseudoObjectExpr::const_semantics_iterator
4444 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
4445 const Expr *semantic = *i;
4447 // If this semantic expression is an opaque value, bind it
4448 // to the result of its source expression.
4449 if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
4451 // If this is the result expression, we may need to evaluate
4452 // directly into the slot.
4453 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
4455 if (ov == resultExpr && ov->isRValue() && !forLValue &&
4456 CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
4457 CGF.EmitAggExpr(ov->getSourceExpr(), slot);
4459 LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
4460 AlignmentSource::Decl);
4461 opaqueData = OVMA::bind(CGF, ov, LV);
4462 result.RV = slot.asRValue();
4464 // Otherwise, emit as normal.
4466 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
4468 // If this is the result, also evaluate the result now.
4469 if (ov == resultExpr) {
4471 result.LV = CGF.EmitLValue(ov);
4473 result.RV = CGF.EmitAnyExpr(ov, slot);
4477 opaques.push_back(opaqueData);
4479 // Otherwise, if the expression is the result, evaluate it
4480 // and remember the result.
4481 } else if (semantic == resultExpr) {
4483 result.LV = CGF.EmitLValue(semantic);
4485 result.RV = CGF.EmitAnyExpr(semantic, slot);
4487 // Otherwise, evaluate the expression in an ignored context.
4489 CGF.EmitIgnoredExpr(semantic);
4493 // Unbind all the opaques now.
4494 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
4495 opaques[i].unbind(CGF);
4500 RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
4501 AggValueSlot slot) {
4502 return emitPseudoObjectExpr(*this, E, false, slot).RV;
4505 LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
4506 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;