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 llvm::Value *ArraySize,
66 bool CastToDefaultAddrSpace) {
67 auto Alloca = CreateTempAlloca(Ty, Name, ArraySize);
68 Alloca->setAlignment(Align.getQuantity());
69 llvm::Value *V = Alloca;
70 // Alloca always returns a pointer in alloca address space, which may
71 // be different from the type defined by the language. For example,
72 // in C++ the auto variables are in the default address space. Therefore
73 // cast alloca to the default address space when necessary.
74 if (CastToDefaultAddrSpace && getASTAllocaAddressSpace() != LangAS::Default) {
75 auto DestAddrSpace = getContext().getTargetAddressSpace(LangAS::Default);
76 V = getTargetHooks().performAddrSpaceCast(
77 *this, V, getASTAllocaAddressSpace(), LangAS::Default,
78 Ty->getPointerTo(DestAddrSpace), /*non-null*/ true);
81 return Address(V, Align);
84 /// CreateTempAlloca - This creates an alloca and inserts it into the entry
85 /// block if \p ArraySize is nullptr, otherwise inserts it at the current
86 /// insertion point of the builder.
87 llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
89 llvm::Value *ArraySize) {
91 return Builder.CreateAlloca(Ty, ArraySize, Name);
92 return new llvm::AllocaInst(Ty, CGM.getDataLayout().getAllocaAddrSpace(),
93 ArraySize, Name, AllocaInsertPt);
96 /// CreateDefaultAlignTempAlloca - This creates an alloca with the
97 /// default alignment of the corresponding LLVM type, which is *not*
98 /// guaranteed to be related in any way to the expected alignment of
99 /// an AST type that might have been lowered to Ty.
100 Address CodeGenFunction::CreateDefaultAlignTempAlloca(llvm::Type *Ty,
103 CharUnits::fromQuantity(CGM.getDataLayout().getABITypeAlignment(Ty));
104 return CreateTempAlloca(Ty, Align, Name);
107 void CodeGenFunction::InitTempAlloca(Address Var, llvm::Value *Init) {
108 assert(isa<llvm::AllocaInst>(Var.getPointer()));
109 auto *Store = new llvm::StoreInst(Init, Var.getPointer());
110 Store->setAlignment(Var.getAlignment().getQuantity());
111 llvm::BasicBlock *Block = AllocaInsertPt->getParent();
112 Block->getInstList().insertAfter(AllocaInsertPt->getIterator(), Store);
115 Address CodeGenFunction::CreateIRTemp(QualType Ty, const Twine &Name) {
116 CharUnits Align = getContext().getTypeAlignInChars(Ty);
117 return CreateTempAlloca(ConvertType(Ty), Align, Name);
120 Address CodeGenFunction::CreateMemTemp(QualType Ty, const Twine &Name,
121 bool CastToDefaultAddrSpace) {
122 // FIXME: Should we prefer the preferred type alignment here?
123 return CreateMemTemp(Ty, getContext().getTypeAlignInChars(Ty), Name,
124 CastToDefaultAddrSpace);
127 Address CodeGenFunction::CreateMemTemp(QualType Ty, CharUnits Align,
129 bool CastToDefaultAddrSpace) {
130 return CreateTempAlloca(ConvertTypeForMem(Ty), Align, Name, nullptr,
131 CastToDefaultAddrSpace);
134 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
135 /// expression and compare the result against zero, returning an Int1Ty value.
136 llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
137 PGO.setCurrentStmt(E);
138 if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
139 llvm::Value *MemPtr = EmitScalarExpr(E);
140 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
143 QualType BoolTy = getContext().BoolTy;
144 SourceLocation Loc = E->getExprLoc();
145 if (!E->getType()->isAnyComplexType())
146 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy, Loc);
148 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(), BoolTy,
152 /// EmitIgnoredExpr - Emit code to compute the specified expression,
153 /// ignoring the result.
154 void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
156 return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
158 // Just emit it as an l-value and drop the result.
162 /// EmitAnyExpr - Emit code to compute the specified expression which
163 /// can have any type. The result is returned as an RValue struct.
164 /// If this is an aggregate expression, AggSlot indicates where the
165 /// result should be returned.
166 RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
167 AggValueSlot aggSlot,
169 switch (getEvaluationKind(E->getType())) {
171 return RValue::get(EmitScalarExpr(E, ignoreResult));
173 return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
175 if (!ignoreResult && aggSlot.isIgnored())
176 aggSlot = CreateAggTemp(E->getType(), "agg-temp");
177 EmitAggExpr(E, aggSlot);
178 return aggSlot.asRValue();
180 llvm_unreachable("bad evaluation kind");
183 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
184 /// always be accessible even if no aggregate location is provided.
185 RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
186 AggValueSlot AggSlot = AggValueSlot::ignored();
188 if (hasAggregateEvaluationKind(E->getType()))
189 AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
190 return EmitAnyExpr(E, AggSlot);
193 /// EmitAnyExprToMem - Evaluate an expression into a given memory
195 void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
199 // FIXME: This function should take an LValue as an argument.
200 switch (getEvaluationKind(E->getType())) {
202 EmitComplexExprIntoLValue(E, MakeAddrLValue(Location, E->getType()),
206 case TEK_Aggregate: {
207 EmitAggExpr(E, AggValueSlot::forAddr(Location, Quals,
208 AggValueSlot::IsDestructed_t(IsInit),
209 AggValueSlot::DoesNotNeedGCBarriers,
210 AggValueSlot::IsAliased_t(!IsInit)));
215 RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
216 LValue LV = MakeAddrLValue(Location, E->getType());
217 EmitStoreThroughLValue(RV, LV);
221 llvm_unreachable("bad evaluation kind");
225 pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M,
226 const Expr *E, Address ReferenceTemporary) {
227 // Objective-C++ ARC:
228 // If we are binding a reference to a temporary that has ownership, we
229 // need to perform retain/release operations on the temporary.
231 // FIXME: This should be looking at E, not M.
232 if (auto Lifetime = M->getType().getObjCLifetime()) {
234 case Qualifiers::OCL_None:
235 case Qualifiers::OCL_ExplicitNone:
236 // Carry on to normal cleanup handling.
239 case Qualifiers::OCL_Autoreleasing:
240 // Nothing to do; cleaned up by an autorelease pool.
243 case Qualifiers::OCL_Strong:
244 case Qualifiers::OCL_Weak:
245 switch (StorageDuration Duration = M->getStorageDuration()) {
247 // Note: we intentionally do not register a cleanup to release
248 // the object on program termination.
252 // FIXME: We should probably register a cleanup in this case.
256 case SD_FullExpression:
257 CodeGenFunction::Destroyer *Destroy;
258 CleanupKind CleanupKind;
259 if (Lifetime == Qualifiers::OCL_Strong) {
260 const ValueDecl *VD = M->getExtendingDecl();
262 VD && isa<VarDecl>(VD) && VD->hasAttr<ObjCPreciseLifetimeAttr>();
263 CleanupKind = CGF.getARCCleanupKind();
264 Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise
265 : &CodeGenFunction::destroyARCStrongImprecise;
267 // __weak objects always get EH cleanups; otherwise, exceptions
268 // could cause really nasty crashes instead of mere leaks.
269 CleanupKind = NormalAndEHCleanup;
270 Destroy = &CodeGenFunction::destroyARCWeak;
272 if (Duration == SD_FullExpression)
273 CGF.pushDestroy(CleanupKind, ReferenceTemporary,
274 M->getType(), *Destroy,
275 CleanupKind & EHCleanup);
277 CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
279 *Destroy, CleanupKind & EHCleanup);
283 llvm_unreachable("temporary cannot have dynamic storage duration");
285 llvm_unreachable("unknown storage duration");
289 CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
290 if (const RecordType *RT =
291 E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
292 // Get the destructor for the reference temporary.
293 auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
294 if (!ClassDecl->hasTrivialDestructor())
295 ReferenceTemporaryDtor = ClassDecl->getDestructor();
298 if (!ReferenceTemporaryDtor)
301 // Call the destructor for the temporary.
302 switch (M->getStorageDuration()) {
305 llvm::Constant *CleanupFn;
306 llvm::Constant *CleanupArg;
307 if (E->getType()->isArrayType()) {
308 CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper(
309 ReferenceTemporary, E->getType(),
310 CodeGenFunction::destroyCXXObject, CGF.getLangOpts().Exceptions,
311 dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
312 CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
314 CleanupFn = CGF.CGM.getAddrOfCXXStructor(ReferenceTemporaryDtor,
315 StructorType::Complete);
316 CleanupArg = cast<llvm::Constant>(ReferenceTemporary.getPointer());
318 CGF.CGM.getCXXABI().registerGlobalDtor(
319 CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
323 case SD_FullExpression:
324 CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(),
325 CodeGenFunction::destroyCXXObject,
326 CGF.getLangOpts().Exceptions);
330 CGF.pushLifetimeExtendedDestroy(NormalAndEHCleanup,
331 ReferenceTemporary, E->getType(),
332 CodeGenFunction::destroyCXXObject,
333 CGF.getLangOpts().Exceptions);
337 llvm_unreachable("temporary cannot have dynamic storage duration");
341 static Address createReferenceTemporary(CodeGenFunction &CGF,
342 const MaterializeTemporaryExpr *M,
344 auto &TCG = CGF.getTargetHooks();
345 switch (M->getStorageDuration()) {
346 case SD_FullExpression:
348 // If we have a constant temporary array or record try to promote it into a
349 // constant global under the same rules a normal constant would've been
350 // promoted. This is easier on the optimizer and generally emits fewer
352 QualType Ty = Inner->getType();
353 if (CGF.CGM.getCodeGenOpts().MergeAllConstants &&
354 (Ty->isArrayType() || Ty->isRecordType()) &&
355 CGF.CGM.isTypeConstant(Ty, true))
356 if (llvm::Constant *Init = CGF.CGM.EmitConstantExpr(Inner, Ty, &CGF)) {
357 if (auto AddrSpace = CGF.getTarget().getConstantAddressSpace()) {
358 auto AS = AddrSpace.getValue();
359 auto *GV = new llvm::GlobalVariable(
360 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
361 llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp", nullptr,
362 llvm::GlobalValue::NotThreadLocal,
363 CGF.getContext().getTargetAddressSpace(AS));
364 CharUnits alignment = CGF.getContext().getTypeAlignInChars(Ty);
365 GV->setAlignment(alignment.getQuantity());
366 llvm::Constant *C = GV;
367 if (AS != LangAS::Default)
368 C = TCG.performAddrSpaceCast(
369 CGF.CGM, GV, AS, LangAS::Default,
370 GV->getValueType()->getPointerTo(
371 CGF.getContext().getTargetAddressSpace(LangAS::Default)));
372 // FIXME: Should we put the new global into a COMDAT?
373 return Address(C, alignment);
376 return CGF.CreateMemTemp(Ty, "ref.tmp");
380 return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
383 llvm_unreachable("temporary can't have dynamic storage duration");
385 llvm_unreachable("unknown storage duration");
388 LValue CodeGenFunction::
389 EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *M) {
390 const Expr *E = M->GetTemporaryExpr();
392 // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
393 // as that will cause the lifetime adjustment to be lost for ARC
394 auto ownership = M->getType().getObjCLifetime();
395 if (ownership != Qualifiers::OCL_None &&
396 ownership != Qualifiers::OCL_ExplicitNone) {
397 Address Object = createReferenceTemporary(*this, M, E);
398 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
399 Object = Address(llvm::ConstantExpr::getBitCast(Var,
400 ConvertTypeForMem(E->getType())
401 ->getPointerTo(Object.getAddressSpace())),
402 Object.getAlignment());
404 // createReferenceTemporary will promote the temporary to a global with a
405 // constant initializer if it can. It can only do this to a value of
406 // ARC-manageable type if the value is global and therefore "immune" to
407 // ref-counting operations. Therefore we have no need to emit either a
408 // dynamic initialization or a cleanup and we can just return the address
410 if (Var->hasInitializer())
411 return MakeAddrLValue(Object, M->getType(),
412 LValueBaseInfo(AlignmentSource::Decl, false));
414 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
416 LValue RefTempDst = MakeAddrLValue(Object, M->getType(),
417 LValueBaseInfo(AlignmentSource::Decl,
420 switch (getEvaluationKind(E->getType())) {
421 default: llvm_unreachable("expected scalar or aggregate expression");
423 EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
425 case TEK_Aggregate: {
426 EmitAggExpr(E, AggValueSlot::forAddr(Object,
427 E->getType().getQualifiers(),
428 AggValueSlot::IsDestructed,
429 AggValueSlot::DoesNotNeedGCBarriers,
430 AggValueSlot::IsNotAliased));
435 pushTemporaryCleanup(*this, M, E, Object);
439 SmallVector<const Expr *, 2> CommaLHSs;
440 SmallVector<SubobjectAdjustment, 2> Adjustments;
441 E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
443 for (const auto &Ignored : CommaLHSs)
444 EmitIgnoredExpr(Ignored);
446 if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
447 if (opaque->getType()->isRecordType()) {
448 assert(Adjustments.empty());
449 return EmitOpaqueValueLValue(opaque);
453 // Create and initialize the reference temporary.
454 Address Object = createReferenceTemporary(*this, M, E);
455 if (auto *Var = dyn_cast<llvm::GlobalVariable>(
456 Object.getPointer()->stripPointerCasts())) {
457 Object = Address(llvm::ConstantExpr::getBitCast(
458 cast<llvm::Constant>(Object.getPointer()),
459 ConvertTypeForMem(E->getType())->getPointerTo()),
460 Object.getAlignment());
461 // If the temporary is a global and has a constant initializer or is a
462 // constant temporary that we promoted to a global, we may have already
464 if (!Var->hasInitializer()) {
465 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
466 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
469 switch (M->getStorageDuration()) {
471 case SD_FullExpression:
472 if (auto *Size = EmitLifetimeStart(
473 CGM.getDataLayout().getTypeAllocSize(Object.getElementType()),
474 Object.getPointer())) {
475 if (M->getStorageDuration() == SD_Automatic)
476 pushCleanupAfterFullExpr<CallLifetimeEnd>(NormalEHLifetimeMarker,
479 pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, Object,
486 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
488 pushTemporaryCleanup(*this, M, E, Object);
490 // Perform derived-to-base casts and/or field accesses, to get from the
491 // temporary object we created (and, potentially, for which we extended
492 // the lifetime) to the subobject we're binding the reference to.
493 for (unsigned I = Adjustments.size(); I != 0; --I) {
494 SubobjectAdjustment &Adjustment = Adjustments[I-1];
495 switch (Adjustment.Kind) {
496 case SubobjectAdjustment::DerivedToBaseAdjustment:
498 GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
499 Adjustment.DerivedToBase.BasePath->path_begin(),
500 Adjustment.DerivedToBase.BasePath->path_end(),
501 /*NullCheckValue=*/ false, E->getExprLoc());
504 case SubobjectAdjustment::FieldAdjustment: {
505 LValue LV = MakeAddrLValue(Object, E->getType(),
506 LValueBaseInfo(AlignmentSource::Decl, false));
507 LV = EmitLValueForField(LV, Adjustment.Field);
508 assert(LV.isSimple() &&
509 "materialized temporary field is not a simple lvalue");
510 Object = LV.getAddress();
514 case SubobjectAdjustment::MemberPointerAdjustment: {
515 llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
516 Object = EmitCXXMemberDataPointerAddress(E, Object, Ptr,
523 return MakeAddrLValue(Object, M->getType(),
524 LValueBaseInfo(AlignmentSource::Decl, false));
528 CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) {
529 // Emit the expression as an lvalue.
530 LValue LV = EmitLValue(E);
531 assert(LV.isSimple());
532 llvm::Value *Value = LV.getPointer();
534 if (sanitizePerformTypeCheck() && !E->getType()->isFunctionType()) {
535 // C++11 [dcl.ref]p5 (as amended by core issue 453):
536 // If a glvalue to which a reference is directly bound designates neither
537 // an existing object or function of an appropriate type nor a region of
538 // storage of suitable size and alignment to contain an object of the
539 // reference's type, the behavior is undefined.
540 QualType Ty = E->getType();
541 EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
544 return RValue::get(Value);
548 /// getAccessedFieldNo - Given an encoded value and a result number, return the
549 /// input field number being accessed.
550 unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
551 const llvm::Constant *Elts) {
552 return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
556 /// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
557 static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
559 llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
560 llvm::Value *K47 = Builder.getInt64(47);
561 llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
562 llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
563 llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
564 llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
565 return Builder.CreateMul(B1, KMul);
568 bool CodeGenFunction::sanitizePerformTypeCheck() const {
569 return SanOpts.has(SanitizerKind::Null) |
570 SanOpts.has(SanitizerKind::Alignment) |
571 SanOpts.has(SanitizerKind::ObjectSize) |
572 SanOpts.has(SanitizerKind::Vptr);
575 void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
576 llvm::Value *Ptr, QualType Ty,
578 SanitizerSet SkippedChecks) {
579 if (!sanitizePerformTypeCheck())
582 // Don't check pointers outside the default address space. The null check
583 // isn't correct, the object-size check isn't supported by LLVM, and we can't
584 // communicate the addresses to the runtime handler for the vptr check.
585 if (Ptr->getType()->getPointerAddressSpace())
588 // Don't check pointers to volatile data. The behavior here is implementation-
590 if (Ty.isVolatileQualified())
593 SanitizerScope SanScope(this);
595 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 3> Checks;
596 llvm::BasicBlock *Done = nullptr;
598 // Quickly determine whether we have a pointer to an alloca. It's possible
599 // to skip null checks, and some alignment checks, for these pointers. This
600 // can reduce compile-time significantly.
602 dyn_cast<llvm::AllocaInst>(Ptr->stripPointerCastsNoFollowAliases());
604 bool AllowNullPointers = TCK == TCK_DowncastPointer || TCK == TCK_Upcast ||
605 TCK == TCK_UpcastToVirtualBase;
606 if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
607 !SkippedChecks.has(SanitizerKind::Null) && !PtrToAlloca) {
608 // The glvalue must not be an empty glvalue.
609 llvm::Value *IsNonNull = Builder.CreateIsNotNull(Ptr);
611 // The IR builder can constant-fold the null check if the pointer points to
614 IsNonNull == llvm::ConstantInt::getTrue(getLLVMContext());
616 // Skip the null check if the pointer is known to be non-null.
618 if (AllowNullPointers) {
619 // When performing pointer casts, it's OK if the value is null.
620 // Skip the remaining checks in that case.
621 Done = createBasicBlock("null");
622 llvm::BasicBlock *Rest = createBasicBlock("not.null");
623 Builder.CreateCondBr(IsNonNull, Rest, Done);
626 Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null));
631 if (SanOpts.has(SanitizerKind::ObjectSize) &&
632 !SkippedChecks.has(SanitizerKind::ObjectSize) &&
633 !Ty->isIncompleteType()) {
634 uint64_t Size = getContext().getTypeSizeInChars(Ty).getQuantity();
636 // The glvalue must refer to a large enough storage region.
637 // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
639 // FIXME: Get object address space
640 llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
641 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
642 llvm::Value *Min = Builder.getFalse();
643 llvm::Value *NullIsUnknown = Builder.getFalse();
644 llvm::Value *CastAddr = Builder.CreateBitCast(Ptr, Int8PtrTy);
645 llvm::Value *LargeEnough = Builder.CreateICmpUGE(
646 Builder.CreateCall(F, {CastAddr, Min, NullIsUnknown}),
647 llvm::ConstantInt::get(IntPtrTy, Size));
648 Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
651 uint64_t AlignVal = 0;
653 if (SanOpts.has(SanitizerKind::Alignment) &&
654 !SkippedChecks.has(SanitizerKind::Alignment)) {
655 AlignVal = Alignment.getQuantity();
656 if (!Ty->isIncompleteType() && !AlignVal)
657 AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity();
659 // The glvalue must be suitably aligned.
661 (!PtrToAlloca || PtrToAlloca->getAlignment() < AlignVal)) {
663 Builder.CreateAnd(Builder.CreatePtrToInt(Ptr, IntPtrTy),
664 llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
665 llvm::Value *Aligned =
666 Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
667 Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
671 if (Checks.size() > 0) {
672 // Make sure we're not losing information. Alignment needs to be a power of
674 assert(!AlignVal || (uint64_t)1 << llvm::Log2_64(AlignVal) == AlignVal);
675 llvm::Constant *StaticData[] = {
676 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(Ty),
677 llvm::ConstantInt::get(Int8Ty, AlignVal ? llvm::Log2_64(AlignVal) : 1),
678 llvm::ConstantInt::get(Int8Ty, TCK)};
679 EmitCheck(Checks, SanitizerHandler::TypeMismatch, StaticData, Ptr);
682 // If possible, check that the vptr indicates that there is a subobject of
683 // type Ty at offset zero within this object.
685 // C++11 [basic.life]p5,6:
686 // [For storage which does not refer to an object within its lifetime]
687 // The program has undefined behavior if:
688 // -- the [pointer or glvalue] is used to access a non-static data member
689 // or call a non-static member function
690 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
691 if (SanOpts.has(SanitizerKind::Vptr) &&
692 !SkippedChecks.has(SanitizerKind::Vptr) &&
693 (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
694 TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
695 TCK == TCK_UpcastToVirtualBase) &&
696 RD && RD->hasDefinition() && RD->isDynamicClass()) {
697 // Compute a hash of the mangled name of the type.
699 // FIXME: This is not guaranteed to be deterministic! Move to a
700 // fingerprinting mechanism once LLVM provides one. For the time
701 // being the implementation happens to be deterministic.
702 SmallString<64> MangledName;
703 llvm::raw_svector_ostream Out(MangledName);
704 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
707 // Blacklist based on the mangled type.
708 if (!CGM.getContext().getSanitizerBlacklist().isBlacklistedType(
710 llvm::hash_code TypeHash = hash_value(Out.str());
712 // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
713 llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
714 llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
715 Address VPtrAddr(Builder.CreateBitCast(Ptr, VPtrTy), getPointerAlign());
716 llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
717 llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
719 llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
720 Hash = Builder.CreateTrunc(Hash, IntPtrTy);
722 // Look the hash up in our cache.
723 const int CacheSize = 128;
724 llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
725 llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
726 "__ubsan_vptr_type_cache");
727 llvm::Value *Slot = Builder.CreateAnd(Hash,
728 llvm::ConstantInt::get(IntPtrTy,
730 llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
731 llvm::Value *CacheVal =
732 Builder.CreateAlignedLoad(Builder.CreateInBoundsGEP(Cache, Indices),
735 // If the hash isn't in the cache, call a runtime handler to perform the
736 // hard work of checking whether the vptr is for an object of the right
737 // type. This will either fill in the cache and return, or produce a
739 llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
740 llvm::Constant *StaticData[] = {
741 EmitCheckSourceLocation(Loc),
742 EmitCheckTypeDescriptor(Ty),
743 CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
744 llvm::ConstantInt::get(Int8Ty, TCK)
746 llvm::Value *DynamicData[] = { Ptr, Hash };
747 EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
748 SanitizerHandler::DynamicTypeCacheMiss, StaticData,
754 Builder.CreateBr(Done);
759 /// Determine whether this expression refers to a flexible array member in a
760 /// struct. We disable array bounds checks for such members.
761 static bool isFlexibleArrayMemberExpr(const Expr *E) {
762 // For compatibility with existing code, we treat arrays of length 0 or
763 // 1 as flexible array members.
764 const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe();
765 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
766 if (CAT->getSize().ugt(1))
768 } else if (!isa<IncompleteArrayType>(AT))
771 E = E->IgnoreParens();
773 // A flexible array member must be the last member in the class.
774 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
775 // FIXME: If the base type of the member expr is not FD->getParent(),
776 // this should not be treated as a flexible array member access.
777 if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
778 RecordDecl::field_iterator FI(
779 DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
780 return ++FI == FD->getParent()->field_end();
782 } else if (const auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) {
783 return IRE->getDecl()->getNextIvar() == nullptr;
789 /// If Base is known to point to the start of an array, return the length of
790 /// that array. Return 0 if the length cannot be determined.
791 static llvm::Value *getArrayIndexingBound(
792 CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType) {
793 // For the vector indexing extension, the bound is the number of elements.
794 if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
795 IndexedType = Base->getType();
796 return CGF.Builder.getInt32(VT->getNumElements());
799 Base = Base->IgnoreParens();
801 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
802 if (CE->getCastKind() == CK_ArrayToPointerDecay &&
803 !isFlexibleArrayMemberExpr(CE->getSubExpr())) {
804 IndexedType = CE->getSubExpr()->getType();
805 const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
806 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
807 return CGF.Builder.getInt(CAT->getSize());
808 else if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
809 return CGF.getVLASize(VAT).first;
816 void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
817 llvm::Value *Index, QualType IndexType,
819 assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
820 "should not be called unless adding bounds checks");
821 SanitizerScope SanScope(this);
823 QualType IndexedType;
824 llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType);
828 bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
829 llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
830 llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
832 llvm::Constant *StaticData[] = {
833 EmitCheckSourceLocation(E->getExprLoc()),
834 EmitCheckTypeDescriptor(IndexedType),
835 EmitCheckTypeDescriptor(IndexType)
837 llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
838 : Builder.CreateICmpULE(IndexVal, BoundVal);
839 EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds),
840 SanitizerHandler::OutOfBounds, StaticData, Index);
844 CodeGenFunction::ComplexPairTy CodeGenFunction::
845 EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
846 bool isInc, bool isPre) {
847 ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
849 llvm::Value *NextVal;
850 if (isa<llvm::IntegerType>(InVal.first->getType())) {
851 uint64_t AmountVal = isInc ? 1 : -1;
852 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
854 // Add the inc/dec to the real part.
855 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
857 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
858 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
861 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
863 // Add the inc/dec to the real part.
864 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
867 ComplexPairTy IncVal(NextVal, InVal.second);
869 // Store the updated result through the lvalue.
870 EmitStoreOfComplex(IncVal, LV, /*init*/ false);
872 // If this is a postinc, return the value read from memory, otherwise use the
874 return isPre ? IncVal : InVal;
877 void CodeGenModule::EmitExplicitCastExprType(const ExplicitCastExpr *E,
878 CodeGenFunction *CGF) {
879 // Bind VLAs in the cast type.
880 if (CGF && E->getType()->isVariablyModifiedType())
881 CGF->EmitVariablyModifiedType(E->getType());
883 if (CGDebugInfo *DI = getModuleDebugInfo())
884 DI->EmitExplicitCastType(E->getType());
887 //===----------------------------------------------------------------------===//
888 // LValue Expression Emission
889 //===----------------------------------------------------------------------===//
891 /// EmitPointerWithAlignment - Given an expression of pointer type, try to
892 /// derive a more accurate bound on the alignment of the pointer.
893 Address CodeGenFunction::EmitPointerWithAlignment(const Expr *E,
894 LValueBaseInfo *BaseInfo) {
895 // We allow this with ObjC object pointers because of fragile ABIs.
896 assert(E->getType()->isPointerType() ||
897 E->getType()->isObjCObjectPointerType());
898 E = E->IgnoreParens();
901 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
902 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
903 CGM.EmitExplicitCastExprType(ECE, this);
905 switch (CE->getCastKind()) {
906 // Non-converting casts (but not C's implicit conversion from void*).
909 if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) {
910 if (PtrTy->getPointeeType()->isVoidType())
913 LValueBaseInfo InnerInfo;
914 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), &InnerInfo);
915 if (BaseInfo) *BaseInfo = InnerInfo;
917 // If this is an explicit bitcast, and the source l-value is
918 // opaque, honor the alignment of the casted-to type.
919 if (isa<ExplicitCastExpr>(CE) &&
920 InnerInfo.getAlignmentSource() != AlignmentSource::Decl) {
921 LValueBaseInfo ExpInfo;
922 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(),
925 BaseInfo->mergeForCast(ExpInfo);
926 Addr = Address(Addr.getPointer(), Align);
929 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast) &&
930 CE->getCastKind() == CK_BitCast) {
931 if (auto PT = E->getType()->getAs<PointerType>())
932 EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr.getPointer(),
934 CodeGenFunction::CFITCK_UnrelatedCast,
938 return Builder.CreateBitCast(Addr, ConvertType(E->getType()));
942 // Array-to-pointer decay.
943 case CK_ArrayToPointerDecay:
944 return EmitArrayToPointerDecay(CE->getSubExpr(), BaseInfo);
946 // Derived-to-base conversions.
947 case CK_UncheckedDerivedToBase:
948 case CK_DerivedToBase: {
949 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), BaseInfo);
950 auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
951 return GetAddressOfBaseClass(Addr, Derived,
952 CE->path_begin(), CE->path_end(),
953 ShouldNullCheckClassCastValue(CE),
957 // TODO: Is there any reason to treat base-to-derived conversions
965 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
966 if (UO->getOpcode() == UO_AddrOf) {
967 LValue LV = EmitLValue(UO->getSubExpr());
968 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
969 return LV.getAddress();
973 // TODO: conditional operators, comma.
975 // Otherwise, use the alignment of the type.
976 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(), BaseInfo);
977 return Address(EmitScalarExpr(E), Align);
980 RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
981 if (Ty->isVoidType())
982 return RValue::get(nullptr);
984 switch (getEvaluationKind(Ty)) {
987 ConvertType(Ty->castAs<ComplexType>()->getElementType());
988 llvm::Value *U = llvm::UndefValue::get(EltTy);
989 return RValue::getComplex(std::make_pair(U, U));
992 // If this is a use of an undefined aggregate type, the aggregate must have an
993 // identifiable address. Just because the contents of the value are undefined
994 // doesn't mean that the address can't be taken and compared.
995 case TEK_Aggregate: {
996 Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
997 return RValue::getAggregate(DestPtr);
1001 return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
1003 llvm_unreachable("bad evaluation kind");
1006 RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
1008 ErrorUnsupported(E, Name);
1009 return GetUndefRValue(E->getType());
1012 LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
1014 ErrorUnsupported(E, Name);
1015 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
1016 return MakeAddrLValue(Address(llvm::UndefValue::get(Ty), CharUnits::One()),
1020 bool CodeGenFunction::IsWrappedCXXThis(const Expr *Obj) {
1021 const Expr *Base = Obj;
1022 while (!isa<CXXThisExpr>(Base)) {
1023 // The result of a dynamic_cast can be null.
1024 if (isa<CXXDynamicCastExpr>(Base))
1027 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
1028 Base = CE->getSubExpr();
1029 } else if (const auto *PE = dyn_cast<ParenExpr>(Base)) {
1030 Base = PE->getSubExpr();
1031 } else if (const auto *UO = dyn_cast<UnaryOperator>(Base)) {
1032 if (UO->getOpcode() == UO_Extension)
1033 Base = UO->getSubExpr();
1043 LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
1045 if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
1046 LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
1049 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple()) {
1050 SanitizerSet SkippedChecks;
1051 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
1052 bool IsBaseCXXThis = IsWrappedCXXThis(ME->getBase());
1054 SkippedChecks.set(SanitizerKind::Alignment, true);
1055 if (IsBaseCXXThis || isa<DeclRefExpr>(ME->getBase()))
1056 SkippedChecks.set(SanitizerKind::Null, true);
1058 EmitTypeCheck(TCK, E->getExprLoc(), LV.getPointer(),
1059 E->getType(), LV.getAlignment(), SkippedChecks);
1064 /// EmitLValue - Emit code to compute a designator that specifies the location
1065 /// of the expression.
1067 /// This can return one of two things: a simple address or a bitfield reference.
1068 /// In either case, the LLVM Value* in the LValue structure is guaranteed to be
1069 /// an LLVM pointer type.
1071 /// If this returns a bitfield reference, nothing about the pointee type of the
1072 /// LLVM value is known: For example, it may not be a pointer to an integer.
1074 /// If this returns a normal address, and if the lvalue's C type is fixed size,
1075 /// this method guarantees that the returned pointer type will point to an LLVM
1076 /// type of the same size of the lvalue's type. If the lvalue has a variable
1077 /// length type, this is not possible.
1079 LValue CodeGenFunction::EmitLValue(const Expr *E) {
1080 ApplyDebugLocation DL(*this, E);
1081 switch (E->getStmtClass()) {
1082 default: return EmitUnsupportedLValue(E, "l-value expression");
1084 case Expr::ObjCPropertyRefExprClass:
1085 llvm_unreachable("cannot emit a property reference directly");
1087 case Expr::ObjCSelectorExprClass:
1088 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
1089 case Expr::ObjCIsaExprClass:
1090 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
1091 case Expr::BinaryOperatorClass:
1092 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
1093 case Expr::CompoundAssignOperatorClass: {
1094 QualType Ty = E->getType();
1095 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1096 Ty = AT->getValueType();
1097 if (!Ty->isAnyComplexType())
1098 return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
1099 return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
1101 case Expr::CallExprClass:
1102 case Expr::CXXMemberCallExprClass:
1103 case Expr::CXXOperatorCallExprClass:
1104 case Expr::UserDefinedLiteralClass:
1105 return EmitCallExprLValue(cast<CallExpr>(E));
1106 case Expr::VAArgExprClass:
1107 return EmitVAArgExprLValue(cast<VAArgExpr>(E));
1108 case Expr::DeclRefExprClass:
1109 return EmitDeclRefLValue(cast<DeclRefExpr>(E));
1110 case Expr::ParenExprClass:
1111 return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
1112 case Expr::GenericSelectionExprClass:
1113 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
1114 case Expr::PredefinedExprClass:
1115 return EmitPredefinedLValue(cast<PredefinedExpr>(E));
1116 case Expr::StringLiteralClass:
1117 return EmitStringLiteralLValue(cast<StringLiteral>(E));
1118 case Expr::ObjCEncodeExprClass:
1119 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
1120 case Expr::PseudoObjectExprClass:
1121 return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
1122 case Expr::InitListExprClass:
1123 return EmitInitListLValue(cast<InitListExpr>(E));
1124 case Expr::CXXTemporaryObjectExprClass:
1125 case Expr::CXXConstructExprClass:
1126 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
1127 case Expr::CXXBindTemporaryExprClass:
1128 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
1129 case Expr::CXXUuidofExprClass:
1130 return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
1131 case Expr::LambdaExprClass:
1132 return EmitLambdaLValue(cast<LambdaExpr>(E));
1134 case Expr::ExprWithCleanupsClass: {
1135 const auto *cleanups = cast<ExprWithCleanups>(E);
1136 enterFullExpression(cleanups);
1137 RunCleanupsScope Scope(*this);
1138 LValue LV = EmitLValue(cleanups->getSubExpr());
1139 if (LV.isSimple()) {
1140 // Defend against branches out of gnu statement expressions surrounded by
1142 llvm::Value *V = LV.getPointer();
1143 Scope.ForceCleanup({&V});
1144 return LValue::MakeAddr(Address(V, LV.getAlignment()), LV.getType(),
1145 getContext(), LV.getBaseInfo(),
1148 // FIXME: Is it possible to create an ExprWithCleanups that produces a
1149 // bitfield lvalue or some other non-simple lvalue?
1153 case Expr::CXXDefaultArgExprClass:
1154 return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
1155 case Expr::CXXDefaultInitExprClass: {
1156 CXXDefaultInitExprScope Scope(*this);
1157 return EmitLValue(cast<CXXDefaultInitExpr>(E)->getExpr());
1159 case Expr::CXXTypeidExprClass:
1160 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
1162 case Expr::ObjCMessageExprClass:
1163 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
1164 case Expr::ObjCIvarRefExprClass:
1165 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
1166 case Expr::StmtExprClass:
1167 return EmitStmtExprLValue(cast<StmtExpr>(E));
1168 case Expr::UnaryOperatorClass:
1169 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
1170 case Expr::ArraySubscriptExprClass:
1171 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
1172 case Expr::OMPArraySectionExprClass:
1173 return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E));
1174 case Expr::ExtVectorElementExprClass:
1175 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
1176 case Expr::MemberExprClass:
1177 return EmitMemberExpr(cast<MemberExpr>(E));
1178 case Expr::CompoundLiteralExprClass:
1179 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
1180 case Expr::ConditionalOperatorClass:
1181 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
1182 case Expr::BinaryConditionalOperatorClass:
1183 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
1184 case Expr::ChooseExprClass:
1185 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr());
1186 case Expr::OpaqueValueExprClass:
1187 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
1188 case Expr::SubstNonTypeTemplateParmExprClass:
1189 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
1190 case Expr::ImplicitCastExprClass:
1191 case Expr::CStyleCastExprClass:
1192 case Expr::CXXFunctionalCastExprClass:
1193 case Expr::CXXStaticCastExprClass:
1194 case Expr::CXXDynamicCastExprClass:
1195 case Expr::CXXReinterpretCastExprClass:
1196 case Expr::CXXConstCastExprClass:
1197 case Expr::ObjCBridgedCastExprClass:
1198 return EmitCastLValue(cast<CastExpr>(E));
1200 case Expr::MaterializeTemporaryExprClass:
1201 return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
1203 case Expr::CoawaitExprClass:
1204 return EmitCoawaitLValue(cast<CoawaitExpr>(E));
1205 case Expr::CoyieldExprClass:
1206 return EmitCoyieldLValue(cast<CoyieldExpr>(E));
1210 /// Given an object of the given canonical type, can we safely copy a
1211 /// value out of it based on its initializer?
1212 static bool isConstantEmittableObjectType(QualType type) {
1213 assert(type.isCanonical());
1214 assert(!type->isReferenceType());
1216 // Must be const-qualified but non-volatile.
1217 Qualifiers qs = type.getLocalQualifiers();
1218 if (!qs.hasConst() || qs.hasVolatile()) return false;
1220 // Otherwise, all object types satisfy this except C++ classes with
1221 // mutable subobjects or non-trivial copy/destroy behavior.
1222 if (const auto *RT = dyn_cast<RecordType>(type))
1223 if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
1224 if (RD->hasMutableFields() || !RD->isTrivial())
1230 /// Can we constant-emit a load of a reference to a variable of the
1231 /// given type? This is different from predicates like
1232 /// Decl::isUsableInConstantExpressions because we do want it to apply
1233 /// in situations that don't necessarily satisfy the language's rules
1234 /// for this (e.g. C++'s ODR-use rules). For example, we want to able
1235 /// to do this with const float variables even if those variables
1236 /// aren't marked 'constexpr'.
1237 enum ConstantEmissionKind {
1239 CEK_AsReferenceOnly,
1240 CEK_AsValueOrReference,
1243 static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
1244 type = type.getCanonicalType();
1245 if (const auto *ref = dyn_cast<ReferenceType>(type)) {
1246 if (isConstantEmittableObjectType(ref->getPointeeType()))
1247 return CEK_AsValueOrReference;
1248 return CEK_AsReferenceOnly;
1250 if (isConstantEmittableObjectType(type))
1251 return CEK_AsValueOnly;
1255 /// Try to emit a reference to the given value without producing it as
1256 /// an l-value. This is actually more than an optimization: we can't
1257 /// produce an l-value for variables that we never actually captured
1258 /// in a block or lambda, which means const int variables or constexpr
1259 /// literals or similar.
1260 CodeGenFunction::ConstantEmission
1261 CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
1262 ValueDecl *value = refExpr->getDecl();
1264 // The value needs to be an enum constant or a constant variable.
1265 ConstantEmissionKind CEK;
1266 if (isa<ParmVarDecl>(value)) {
1268 } else if (auto *var = dyn_cast<VarDecl>(value)) {
1269 CEK = checkVarTypeForConstantEmission(var->getType());
1270 } else if (isa<EnumConstantDecl>(value)) {
1271 CEK = CEK_AsValueOnly;
1275 if (CEK == CEK_None) return ConstantEmission();
1277 Expr::EvalResult result;
1278 bool resultIsReference;
1279 QualType resultType;
1281 // It's best to evaluate all the way as an r-value if that's permitted.
1282 if (CEK != CEK_AsReferenceOnly &&
1283 refExpr->EvaluateAsRValue(result, getContext())) {
1284 resultIsReference = false;
1285 resultType = refExpr->getType();
1287 // Otherwise, try to evaluate as an l-value.
1288 } else if (CEK != CEK_AsValueOnly &&
1289 refExpr->EvaluateAsLValue(result, getContext())) {
1290 resultIsReference = true;
1291 resultType = value->getType();
1295 return ConstantEmission();
1298 // In any case, if the initializer has side-effects, abandon ship.
1299 if (result.HasSideEffects)
1300 return ConstantEmission();
1302 // Emit as a constant.
1303 llvm::Constant *C = CGM.EmitConstantValue(result.Val, resultType, this);
1305 // Make sure we emit a debug reference to the global variable.
1306 // This should probably fire even for
1307 if (isa<VarDecl>(value)) {
1308 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
1309 EmitDeclRefExprDbgValue(refExpr, result.Val);
1311 assert(isa<EnumConstantDecl>(value));
1312 EmitDeclRefExprDbgValue(refExpr, result.Val);
1315 // If we emitted a reference constant, we need to dereference that.
1316 if (resultIsReference)
1317 return ConstantEmission::forReference(C);
1319 return ConstantEmission::forValue(C);
1322 llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
1323 SourceLocation Loc) {
1324 return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
1325 lvalue.getType(), Loc, lvalue.getBaseInfo(),
1326 lvalue.getTBAAInfo(),
1327 lvalue.getTBAABaseType(), lvalue.getTBAAOffset(),
1328 lvalue.isNontemporal());
1331 static bool hasBooleanRepresentation(QualType Ty) {
1332 if (Ty->isBooleanType())
1335 if (const EnumType *ET = Ty->getAs<EnumType>())
1336 return ET->getDecl()->getIntegerType()->isBooleanType();
1338 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1339 return hasBooleanRepresentation(AT->getValueType());
1344 static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
1345 llvm::APInt &Min, llvm::APInt &End,
1346 bool StrictEnums, bool IsBool) {
1347 const EnumType *ET = Ty->getAs<EnumType>();
1348 bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
1349 ET && !ET->getDecl()->isFixed();
1350 if (!IsBool && !IsRegularCPlusPlusEnum)
1354 Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
1355 End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
1357 const EnumDecl *ED = ET->getDecl();
1358 llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
1359 unsigned Bitwidth = LTy->getScalarSizeInBits();
1360 unsigned NumNegativeBits = ED->getNumNegativeBits();
1361 unsigned NumPositiveBits = ED->getNumPositiveBits();
1363 if (NumNegativeBits) {
1364 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
1365 assert(NumBits <= Bitwidth);
1366 End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
1369 assert(NumPositiveBits <= Bitwidth);
1370 End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
1371 Min = llvm::APInt(Bitwidth, 0);
1377 llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
1378 llvm::APInt Min, End;
1379 if (!getRangeForType(*this, Ty, Min, End, CGM.getCodeGenOpts().StrictEnums,
1380 hasBooleanRepresentation(Ty)))
1383 llvm::MDBuilder MDHelper(getLLVMContext());
1384 return MDHelper.createRange(Min, End);
1387 bool CodeGenFunction::EmitScalarRangeCheck(llvm::Value *Value, QualType Ty,
1388 SourceLocation Loc) {
1389 bool HasBoolCheck = SanOpts.has(SanitizerKind::Bool);
1390 bool HasEnumCheck = SanOpts.has(SanitizerKind::Enum);
1391 if (!HasBoolCheck && !HasEnumCheck)
1394 bool IsBool = hasBooleanRepresentation(Ty) ||
1395 NSAPI(CGM.getContext()).isObjCBOOLType(Ty);
1396 bool NeedsBoolCheck = HasBoolCheck && IsBool;
1397 bool NeedsEnumCheck = HasEnumCheck && Ty->getAs<EnumType>();
1398 if (!NeedsBoolCheck && !NeedsEnumCheck)
1401 // Single-bit booleans don't need to be checked. Special-case this to avoid
1402 // a bit width mismatch when handling bitfield values. This is handled by
1403 // EmitFromMemory for the non-bitfield case.
1405 cast<llvm::IntegerType>(Value->getType())->getBitWidth() == 1)
1408 llvm::APInt Min, End;
1409 if (!getRangeForType(*this, Ty, Min, End, /*StrictEnums=*/true, IsBool))
1412 SanitizerScope SanScope(this);
1416 Check = Builder.CreateICmpULE(
1417 Value, llvm::ConstantInt::get(getLLVMContext(), End));
1419 llvm::Value *Upper = Builder.CreateICmpSLE(
1420 Value, llvm::ConstantInt::get(getLLVMContext(), End));
1421 llvm::Value *Lower = Builder.CreateICmpSGE(
1422 Value, llvm::ConstantInt::get(getLLVMContext(), Min));
1423 Check = Builder.CreateAnd(Upper, Lower);
1425 llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc),
1426 EmitCheckTypeDescriptor(Ty)};
1427 SanitizerMask Kind =
1428 NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
1429 EmitCheck(std::make_pair(Check, Kind), SanitizerHandler::LoadInvalidValue,
1430 StaticArgs, EmitCheckValue(Value));
1434 llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile,
1437 LValueBaseInfo BaseInfo,
1438 llvm::MDNode *TBAAInfo,
1439 QualType TBAABaseType,
1440 uint64_t TBAAOffset,
1441 bool isNontemporal) {
1442 if (!CGM.getCodeGenOpts().PreserveVec3Type) {
1443 // For better performance, handle vector loads differently.
1444 if (Ty->isVectorType()) {
1445 const llvm::Type *EltTy = Addr.getElementType();
1447 const auto *VTy = cast<llvm::VectorType>(EltTy);
1449 // Handle vectors of size 3 like size 4 for better performance.
1450 if (VTy->getNumElements() == 3) {
1452 // Bitcast to vec4 type.
1453 llvm::VectorType *vec4Ty =
1454 llvm::VectorType::get(VTy->getElementType(), 4);
1455 Address Cast = Builder.CreateElementBitCast(Addr, vec4Ty, "castToVec4");
1457 llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4");
1459 // Shuffle vector to get vec3.
1460 V = Builder.CreateShuffleVector(V, llvm::UndefValue::get(vec4Ty),
1461 {0, 1, 2}, "extractVec");
1462 return EmitFromMemory(V, Ty);
1467 // Atomic operations have to be done on integral types.
1468 LValue AtomicLValue =
1469 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
1470 if (Ty->isAtomicType() || LValueIsSuitableForInlineAtomic(AtomicLValue)) {
1471 return EmitAtomicLoad(AtomicLValue, Loc).getScalarVal();
1474 llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
1475 if (isNontemporal) {
1476 llvm::MDNode *Node = llvm::MDNode::get(
1477 Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1478 Load->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1481 bool MayAlias = BaseInfo.getMayAlias();
1482 llvm::MDNode *TBAA = MayAlias
1483 ? CGM.getTBAAInfo(getContext().CharTy)
1484 : CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo, TBAAOffset);
1486 CGM.DecorateInstructionWithTBAA(Load, TBAA, MayAlias);
1489 if (EmitScalarRangeCheck(Load, Ty, Loc)) {
1490 // In order to prevent the optimizer from throwing away the check, don't
1491 // attach range metadata to the load.
1492 } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
1493 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
1494 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
1496 return EmitFromMemory(Load, Ty);
1499 llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
1500 // Bool has a different representation in memory than in registers.
1501 if (hasBooleanRepresentation(Ty)) {
1502 // This should really always be an i1, but sometimes it's already
1503 // an i8, and it's awkward to track those cases down.
1504 if (Value->getType()->isIntegerTy(1))
1505 return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
1506 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1507 "wrong value rep of bool");
1513 llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
1514 // Bool has a different representation in memory than in registers.
1515 if (hasBooleanRepresentation(Ty)) {
1516 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1517 "wrong value rep of bool");
1518 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
1524 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr,
1525 bool Volatile, QualType Ty,
1526 LValueBaseInfo BaseInfo,
1527 llvm::MDNode *TBAAInfo,
1528 bool isInit, QualType TBAABaseType,
1529 uint64_t TBAAOffset,
1530 bool isNontemporal) {
1532 if (!CGM.getCodeGenOpts().PreserveVec3Type) {
1533 // Handle vectors differently to get better performance.
1534 if (Ty->isVectorType()) {
1535 llvm::Type *SrcTy = Value->getType();
1536 auto *VecTy = dyn_cast<llvm::VectorType>(SrcTy);
1537 // Handle vec3 special.
1538 if (VecTy && VecTy->getNumElements() == 3) {
1539 // Our source is a vec3, do a shuffle vector to make it a vec4.
1540 llvm::Constant *Mask[] = {Builder.getInt32(0), Builder.getInt32(1),
1541 Builder.getInt32(2),
1542 llvm::UndefValue::get(Builder.getInt32Ty())};
1543 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1544 Value = Builder.CreateShuffleVector(Value, llvm::UndefValue::get(VecTy),
1545 MaskV, "extractVec");
1546 SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
1548 if (Addr.getElementType() != SrcTy) {
1549 Addr = Builder.CreateElementBitCast(Addr, SrcTy, "storetmp");
1554 Value = EmitToMemory(Value, Ty);
1556 LValue AtomicLValue =
1557 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
1558 if (Ty->isAtomicType() ||
1559 (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) {
1560 EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit);
1564 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
1565 if (isNontemporal) {
1566 llvm::MDNode *Node =
1567 llvm::MDNode::get(Store->getContext(),
1568 llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1569 Store->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1572 bool MayAlias = BaseInfo.getMayAlias();
1573 llvm::MDNode *TBAA = MayAlias
1574 ? CGM.getTBAAInfo(getContext().CharTy)
1575 : CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo, TBAAOffset);
1577 CGM.DecorateInstructionWithTBAA(Store, TBAA, MayAlias);
1581 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
1583 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
1584 lvalue.getType(), lvalue.getBaseInfo(),
1585 lvalue.getTBAAInfo(), isInit, lvalue.getTBAABaseType(),
1586 lvalue.getTBAAOffset(), lvalue.isNontemporal());
1589 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1590 /// method emits the address of the lvalue, then loads the result as an rvalue,
1591 /// returning the rvalue.
1592 RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
1593 if (LV.isObjCWeak()) {
1594 // load of a __weak object.
1595 Address AddrWeakObj = LV.getAddress();
1596 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1599 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
1600 // In MRC mode, we do a load+autorelease.
1601 if (!getLangOpts().ObjCAutoRefCount) {
1602 return RValue::get(EmitARCLoadWeak(LV.getAddress()));
1605 // In ARC mode, we load retained and then consume the value.
1606 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
1607 Object = EmitObjCConsumeObject(LV.getType(), Object);
1608 return RValue::get(Object);
1611 if (LV.isSimple()) {
1612 assert(!LV.getType()->isFunctionType());
1614 // Everything needs a load.
1615 return RValue::get(EmitLoadOfScalar(LV, Loc));
1618 if (LV.isVectorElt()) {
1619 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
1620 LV.isVolatileQualified());
1621 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
1625 // If this is a reference to a subset of the elements of a vector, either
1626 // shuffle the input or extract/insert them as appropriate.
1627 if (LV.isExtVectorElt())
1628 return EmitLoadOfExtVectorElementLValue(LV);
1630 // Global Register variables always invoke intrinsics
1631 if (LV.isGlobalReg())
1632 return EmitLoadOfGlobalRegLValue(LV);
1634 assert(LV.isBitField() && "Unknown LValue type!");
1635 return EmitLoadOfBitfieldLValue(LV, Loc);
1638 RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
1639 SourceLocation Loc) {
1640 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
1642 // Get the output type.
1643 llvm::Type *ResLTy = ConvertType(LV.getType());
1645 Address Ptr = LV.getBitFieldAddress();
1646 llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
1648 if (Info.IsSigned) {
1649 assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
1650 unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
1652 Val = Builder.CreateShl(Val, HighBits, "bf.shl");
1653 if (Info.Offset + HighBits)
1654 Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
1657 Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
1658 if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
1659 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
1663 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
1664 EmitScalarRangeCheck(Val, LV.getType(), Loc);
1665 return RValue::get(Val);
1668 // If this is a reference to a subset of the elements of a vector, create an
1669 // appropriate shufflevector.
1670 RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
1671 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
1672 LV.isVolatileQualified());
1674 const llvm::Constant *Elts = LV.getExtVectorElts();
1676 // If the result of the expression is a non-vector type, we must be extracting
1677 // a single element. Just codegen as an extractelement.
1678 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1680 unsigned InIdx = getAccessedFieldNo(0, Elts);
1681 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
1682 return RValue::get(Builder.CreateExtractElement(Vec, Elt));
1685 // Always use shuffle vector to try to retain the original program structure
1686 unsigned NumResultElts = ExprVT->getNumElements();
1688 SmallVector<llvm::Constant*, 4> Mask;
1689 for (unsigned i = 0; i != NumResultElts; ++i)
1690 Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
1692 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1693 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
1695 return RValue::get(Vec);
1698 /// @brief Generates lvalue for partial ext_vector access.
1699 Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
1700 Address VectorAddress = LV.getExtVectorAddress();
1701 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1702 QualType EQT = ExprVT->getElementType();
1703 llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
1705 Address CastToPointerElement =
1706 Builder.CreateElementBitCast(VectorAddress, VectorElementTy,
1707 "conv.ptr.element");
1709 const llvm::Constant *Elts = LV.getExtVectorElts();
1710 unsigned ix = getAccessedFieldNo(0, Elts);
1712 Address VectorBasePtrPlusIx =
1713 Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
1714 getContext().getTypeSizeInChars(EQT),
1717 return VectorBasePtrPlusIx;
1720 /// @brief Load of global gamed gegisters are always calls to intrinsics.
1721 RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
1722 assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
1723 "Bad type for register variable");
1724 llvm::MDNode *RegName = cast<llvm::MDNode>(
1725 cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
1727 // We accept integer and pointer types only
1728 llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
1729 llvm::Type *Ty = OrigTy;
1730 if (OrigTy->isPointerTy())
1731 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1732 llvm::Type *Types[] = { Ty };
1734 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
1735 llvm::Value *Call = Builder.CreateCall(
1736 F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
1737 if (OrigTy->isPointerTy())
1738 Call = Builder.CreateIntToPtr(Call, OrigTy);
1739 return RValue::get(Call);
1743 /// EmitStoreThroughLValue - Store the specified rvalue into the specified
1744 /// lvalue, where both are guaranteed to the have the same type, and that type
1746 void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
1748 if (!Dst.isSimple()) {
1749 if (Dst.isVectorElt()) {
1750 // Read/modify/write the vector, inserting the new element.
1751 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
1752 Dst.isVolatileQualified());
1753 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
1754 Dst.getVectorIdx(), "vecins");
1755 Builder.CreateStore(Vec, Dst.getVectorAddress(),
1756 Dst.isVolatileQualified());
1760 // If this is an update of extended vector elements, insert them as
1762 if (Dst.isExtVectorElt())
1763 return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
1765 if (Dst.isGlobalReg())
1766 return EmitStoreThroughGlobalRegLValue(Src, Dst);
1768 assert(Dst.isBitField() && "Unknown LValue type");
1769 return EmitStoreThroughBitfieldLValue(Src, Dst);
1772 // There's special magic for assigning into an ARC-qualified l-value.
1773 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
1775 case Qualifiers::OCL_None:
1776 llvm_unreachable("present but none");
1778 case Qualifiers::OCL_ExplicitNone:
1782 case Qualifiers::OCL_Strong:
1784 Src = RValue::get(EmitARCRetain(Dst.getType(), Src.getScalarVal()));
1787 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
1790 case Qualifiers::OCL_Weak:
1792 // Initialize and then skip the primitive store.
1793 EmitARCInitWeak(Dst.getAddress(), Src.getScalarVal());
1795 EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
1798 case Qualifiers::OCL_Autoreleasing:
1799 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
1800 Src.getScalarVal()));
1801 // fall into the normal path
1806 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
1807 // load of a __weak object.
1808 Address LvalueDst = Dst.getAddress();
1809 llvm::Value *src = Src.getScalarVal();
1810 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
1814 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
1815 // load of a __strong object.
1816 Address LvalueDst = Dst.getAddress();
1817 llvm::Value *src = Src.getScalarVal();
1818 if (Dst.isObjCIvar()) {
1819 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
1820 llvm::Type *ResultType = IntPtrTy;
1821 Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp());
1822 llvm::Value *RHS = dst.getPointer();
1823 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1825 Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType,
1826 "sub.ptr.lhs.cast");
1827 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
1828 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
1830 } else if (Dst.isGlobalObjCRef()) {
1831 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
1832 Dst.isThreadLocalRef());
1835 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
1839 assert(Src.isScalar() && "Can't emit an agg store with this method");
1840 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
1843 void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
1844 llvm::Value **Result) {
1845 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
1846 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
1847 Address Ptr = Dst.getBitFieldAddress();
1849 // Get the source value, truncated to the width of the bit-field.
1850 llvm::Value *SrcVal = Src.getScalarVal();
1852 // Cast the source to the storage type and shift it into place.
1853 SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
1854 /*IsSigned=*/false);
1855 llvm::Value *MaskedVal = SrcVal;
1857 // See if there are other bits in the bitfield's storage we'll need to load
1858 // and mask together with source before storing.
1859 if (Info.StorageSize != Info.Size) {
1860 assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
1862 Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
1864 // Mask the source value as needed.
1865 if (!hasBooleanRepresentation(Dst.getType()))
1866 SrcVal = Builder.CreateAnd(SrcVal,
1867 llvm::APInt::getLowBitsSet(Info.StorageSize,
1872 SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
1874 // Mask out the original value.
1875 Val = Builder.CreateAnd(Val,
1876 ~llvm::APInt::getBitsSet(Info.StorageSize,
1878 Info.Offset + Info.Size),
1881 // Or together the unchanged values and the source value.
1882 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
1884 assert(Info.Offset == 0);
1887 // Write the new value back out.
1888 Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
1890 // Return the new value of the bit-field, if requested.
1892 llvm::Value *ResultVal = MaskedVal;
1894 // Sign extend the value if needed.
1895 if (Info.IsSigned) {
1896 assert(Info.Size <= Info.StorageSize);
1897 unsigned HighBits = Info.StorageSize - Info.Size;
1899 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
1900 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
1904 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
1906 *Result = EmitFromMemory(ResultVal, Dst.getType());
1910 void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
1912 // This access turns into a read/modify/write of the vector. Load the input
1914 llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(),
1915 Dst.isVolatileQualified());
1916 const llvm::Constant *Elts = Dst.getExtVectorElts();
1918 llvm::Value *SrcVal = Src.getScalarVal();
1920 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
1921 unsigned NumSrcElts = VTy->getNumElements();
1922 unsigned NumDstElts = Vec->getType()->getVectorNumElements();
1923 if (NumDstElts == NumSrcElts) {
1924 // Use shuffle vector is the src and destination are the same number of
1925 // elements and restore the vector mask since it is on the side it will be
1927 SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
1928 for (unsigned i = 0; i != NumSrcElts; ++i)
1929 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
1931 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1932 Vec = Builder.CreateShuffleVector(SrcVal,
1933 llvm::UndefValue::get(Vec->getType()),
1935 } else if (NumDstElts > NumSrcElts) {
1936 // Extended the source vector to the same length and then shuffle it
1937 // into the destination.
1938 // FIXME: since we're shuffling with undef, can we just use the indices
1939 // into that? This could be simpler.
1940 SmallVector<llvm::Constant*, 4> ExtMask;
1941 for (unsigned i = 0; i != NumSrcElts; ++i)
1942 ExtMask.push_back(Builder.getInt32(i));
1943 ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
1944 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
1945 llvm::Value *ExtSrcVal =
1946 Builder.CreateShuffleVector(SrcVal,
1947 llvm::UndefValue::get(SrcVal->getType()),
1950 SmallVector<llvm::Constant*, 4> Mask;
1951 for (unsigned i = 0; i != NumDstElts; ++i)
1952 Mask.push_back(Builder.getInt32(i));
1954 // When the vector size is odd and .odd or .hi is used, the last element
1955 // of the Elts constant array will be one past the size of the vector.
1956 // Ignore the last element here, if it is greater than the mask size.
1957 if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
1960 // modify when what gets shuffled in
1961 for (unsigned i = 0; i != NumSrcElts; ++i)
1962 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
1963 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1964 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
1966 // We should never shorten the vector
1967 llvm_unreachable("unexpected shorten vector length");
1970 // If the Src is a scalar (not a vector) it must be updating one element.
1971 unsigned InIdx = getAccessedFieldNo(0, Elts);
1972 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
1973 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
1976 Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
1977 Dst.isVolatileQualified());
1980 /// @brief Store of global named registers are always calls to intrinsics.
1981 void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
1982 assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
1983 "Bad type for register variable");
1984 llvm::MDNode *RegName = cast<llvm::MDNode>(
1985 cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
1986 assert(RegName && "Register LValue is not metadata");
1988 // We accept integer and pointer types only
1989 llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
1990 llvm::Type *Ty = OrigTy;
1991 if (OrigTy->isPointerTy())
1992 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1993 llvm::Type *Types[] = { Ty };
1995 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
1996 llvm::Value *Value = Src.getScalarVal();
1997 if (OrigTy->isPointerTy())
1998 Value = Builder.CreatePtrToInt(Value, Ty);
2000 F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
2003 // setObjCGCLValueClass - sets class of the lvalue for the purpose of
2004 // generating write-barries API. It is currently a global, ivar,
2006 static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
2008 bool IsMemberAccess=false) {
2009 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
2012 if (isa<ObjCIvarRefExpr>(E)) {
2013 QualType ExpTy = E->getType();
2014 if (IsMemberAccess && ExpTy->isPointerType()) {
2015 // If ivar is a structure pointer, assigning to field of
2016 // this struct follows gcc's behavior and makes it a non-ivar
2017 // writer-barrier conservatively.
2018 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
2019 if (ExpTy->isRecordType()) {
2020 LV.setObjCIvar(false);
2024 LV.setObjCIvar(true);
2025 auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
2026 LV.setBaseIvarExp(Exp->getBase());
2027 LV.setObjCArray(E->getType()->isArrayType());
2031 if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
2032 if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
2033 if (VD->hasGlobalStorage()) {
2034 LV.setGlobalObjCRef(true);
2035 LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
2038 LV.setObjCArray(E->getType()->isArrayType());
2042 if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
2043 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2047 if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
2048 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2049 if (LV.isObjCIvar()) {
2050 // If cast is to a structure pointer, follow gcc's behavior and make it
2051 // a non-ivar write-barrier.
2052 QualType ExpTy = E->getType();
2053 if (ExpTy->isPointerType())
2054 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
2055 if (ExpTy->isRecordType())
2056 LV.setObjCIvar(false);
2061 if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
2062 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
2066 if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
2067 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2071 if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
2072 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2076 if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
2077 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2081 if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
2082 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
2083 if (LV.isObjCIvar() && !LV.isObjCArray())
2084 // Using array syntax to assigning to what an ivar points to is not
2085 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
2086 LV.setObjCIvar(false);
2087 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
2088 // Using array syntax to assigning to what global points to is not
2089 // same as assigning to the global itself. {id *G;} G[i] = 0;
2090 LV.setGlobalObjCRef(false);
2094 if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
2095 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
2096 // We don't know if member is an 'ivar', but this flag is looked at
2097 // only in the context of LV.isObjCIvar().
2098 LV.setObjCArray(E->getType()->isArrayType());
2103 static llvm::Value *
2104 EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
2105 llvm::Value *V, llvm::Type *IRType,
2106 StringRef Name = StringRef()) {
2107 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
2108 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
2111 static LValue EmitThreadPrivateVarDeclLValue(
2112 CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
2113 llvm::Type *RealVarTy, SourceLocation Loc) {
2114 Addr = CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
2115 Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy);
2116 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2117 return CGF.MakeAddrLValue(Addr, T, BaseInfo);
2120 Address CodeGenFunction::EmitLoadOfReference(Address Addr,
2121 const ReferenceType *RefTy,
2122 LValueBaseInfo *BaseInfo) {
2123 llvm::Value *Ptr = Builder.CreateLoad(Addr);
2124 return Address(Ptr, getNaturalTypeAlignment(RefTy->getPointeeType(),
2125 BaseInfo, /*forPointee*/ true));
2128 LValue CodeGenFunction::EmitLoadOfReferenceLValue(Address RefAddr,
2129 const ReferenceType *RefTy) {
2130 LValueBaseInfo BaseInfo;
2131 Address Addr = EmitLoadOfReference(RefAddr, RefTy, &BaseInfo);
2132 return MakeAddrLValue(Addr, RefTy->getPointeeType(), BaseInfo);
2135 Address CodeGenFunction::EmitLoadOfPointer(Address Ptr,
2136 const PointerType *PtrTy,
2137 LValueBaseInfo *BaseInfo) {
2138 llvm::Value *Addr = Builder.CreateLoad(Ptr);
2139 return Address(Addr, getNaturalTypeAlignment(PtrTy->getPointeeType(),
2141 /*forPointeeType=*/true));
2144 LValue CodeGenFunction::EmitLoadOfPointerLValue(Address PtrAddr,
2145 const PointerType *PtrTy) {
2146 LValueBaseInfo BaseInfo;
2147 Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &BaseInfo);
2148 return MakeAddrLValue(Addr, PtrTy->getPointeeType(), BaseInfo);
2151 static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
2152 const Expr *E, const VarDecl *VD) {
2153 QualType T = E->getType();
2155 // If it's thread_local, emit a call to its wrapper function instead.
2156 if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
2157 CGF.CGM.getCXXABI().usesThreadWrapperFunction())
2158 return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
2160 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
2161 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
2162 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
2163 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
2164 Address Addr(V, Alignment);
2166 // Emit reference to the private copy of the variable if it is an OpenMP
2167 // threadprivate variable.
2168 if (CGF.getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>())
2169 return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
2171 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2172 LV = CGF.EmitLoadOfReferenceLValue(Addr, RefTy);
2174 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2175 LV = CGF.MakeAddrLValue(Addr, T, BaseInfo);
2177 setObjCGCLValueClass(CGF.getContext(), E, LV);
2181 static llvm::Constant *EmitFunctionDeclPointer(CodeGenModule &CGM,
2182 const FunctionDecl *FD) {
2183 if (FD->hasAttr<WeakRefAttr>()) {
2184 ConstantAddress aliasee = CGM.GetWeakRefReference(FD);
2185 return aliasee.getPointer();
2188 llvm::Constant *V = CGM.GetAddrOfFunction(FD);
2189 if (!FD->hasPrototype()) {
2190 if (const FunctionProtoType *Proto =
2191 FD->getType()->getAs<FunctionProtoType>()) {
2192 // Ugly case: for a K&R-style definition, the type of the definition
2193 // isn't the same as the type of a use. Correct for this with a
2195 QualType NoProtoType =
2196 CGM.getContext().getFunctionNoProtoType(Proto->getReturnType());
2197 NoProtoType = CGM.getContext().getPointerType(NoProtoType);
2198 V = llvm::ConstantExpr::getBitCast(V,
2199 CGM.getTypes().ConvertType(NoProtoType));
2205 static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
2206 const Expr *E, const FunctionDecl *FD) {
2207 llvm::Value *V = EmitFunctionDeclPointer(CGF.CGM, FD);
2208 CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
2209 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2210 return CGF.MakeAddrLValue(V, E->getType(), Alignment, BaseInfo);
2213 static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
2214 llvm::Value *ThisValue) {
2215 QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
2216 LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
2217 return CGF.EmitLValueForField(LV, FD);
2220 /// Named Registers are named metadata pointing to the register name
2221 /// which will be read from/written to as an argument to the intrinsic
2222 /// @llvm.read/write_register.
2223 /// So far, only the name is being passed down, but other options such as
2224 /// register type, allocation type or even optimization options could be
2225 /// passed down via the metadata node.
2226 static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
2227 SmallString<64> Name("llvm.named.register.");
2228 AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
2229 assert(Asm->getLabel().size() < 64-Name.size() &&
2230 "Register name too big");
2231 Name.append(Asm->getLabel());
2232 llvm::NamedMDNode *M =
2233 CGM.getModule().getOrInsertNamedMetadata(Name);
2234 if (M->getNumOperands() == 0) {
2235 llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
2237 llvm::Metadata *Ops[] = {Str};
2238 M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2241 CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
2244 llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
2245 return LValue::MakeGlobalReg(Address(Ptr, Alignment), VD->getType());
2248 LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
2249 const NamedDecl *ND = E->getDecl();
2250 QualType T = E->getType();
2252 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2253 // Global Named registers access via intrinsics only
2254 if (VD->getStorageClass() == SC_Register &&
2255 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
2256 return EmitGlobalNamedRegister(VD, CGM);
2258 // A DeclRefExpr for a reference initialized by a constant expression can
2259 // appear without being odr-used. Directly emit the constant initializer.
2260 const Expr *Init = VD->getAnyInitializer(VD);
2261 if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() &&
2262 VD->isUsableInConstantExpressions(getContext()) &&
2263 VD->checkInitIsICE() &&
2264 // Do not emit if it is private OpenMP variable.
2265 !(E->refersToEnclosingVariableOrCapture() && CapturedStmtInfo &&
2266 LocalDeclMap.count(VD))) {
2267 llvm::Constant *Val =
2268 CGM.EmitConstantValue(*VD->evaluateValue(), VD->getType(), this);
2269 assert(Val && "failed to emit reference constant expression");
2270 // FIXME: Eventually we will want to emit vector element references.
2272 // Should we be using the alignment of the constant pointer we emitted?
2273 CharUnits Alignment = getNaturalTypeAlignment(E->getType(), nullptr,
2275 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2276 return MakeAddrLValue(Address(Val, Alignment), T, BaseInfo);
2279 // Check for captured variables.
2280 if (E->refersToEnclosingVariableOrCapture()) {
2281 if (auto *FD = LambdaCaptureFields.lookup(VD))
2282 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
2283 else if (CapturedStmtInfo) {
2284 auto I = LocalDeclMap.find(VD);
2285 if (I != LocalDeclMap.end()) {
2286 if (auto RefTy = VD->getType()->getAs<ReferenceType>())
2287 return EmitLoadOfReferenceLValue(I->second, RefTy);
2288 return MakeAddrLValue(I->second, T);
2291 EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
2292 CapturedStmtInfo->getContextValue());
2293 bool MayAlias = CapLVal.getBaseInfo().getMayAlias();
2294 return MakeAddrLValue(
2295 Address(CapLVal.getPointer(), getContext().getDeclAlign(VD)),
2296 CapLVal.getType(), LValueBaseInfo(AlignmentSource::Decl, MayAlias));
2299 assert(isa<BlockDecl>(CurCodeDecl));
2300 Address addr = GetAddrOfBlockDecl(VD, VD->hasAttr<BlocksAttr>());
2301 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2302 return MakeAddrLValue(addr, T, BaseInfo);
2306 // FIXME: We should be able to assert this for FunctionDecls as well!
2307 // FIXME: We should be able to assert this for all DeclRefExprs, not just
2308 // those with a valid source location.
2309 assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
2310 !E->getLocation().isValid()) &&
2311 "Should not use decl without marking it used!");
2313 if (ND->hasAttr<WeakRefAttr>()) {
2314 const auto *VD = cast<ValueDecl>(ND);
2315 ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
2316 return MakeAddrLValue(Aliasee, T,
2317 LValueBaseInfo(AlignmentSource::Decl, false));
2320 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2321 // Check if this is a global variable.
2322 if (VD->hasLinkage() || VD->isStaticDataMember())
2323 return EmitGlobalVarDeclLValue(*this, E, VD);
2325 Address addr = Address::invalid();
2327 // The variable should generally be present in the local decl map.
2328 auto iter = LocalDeclMap.find(VD);
2329 if (iter != LocalDeclMap.end()) {
2330 addr = iter->second;
2332 // Otherwise, it might be static local we haven't emitted yet for
2333 // some reason; most likely, because it's in an outer function.
2334 } else if (VD->isStaticLocal()) {
2335 addr = Address(CGM.getOrCreateStaticVarDecl(
2336 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false)),
2337 getContext().getDeclAlign(VD));
2339 // No other cases for now.
2341 llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
2345 // Check for OpenMP threadprivate variables.
2346 if (getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
2347 return EmitThreadPrivateVarDeclLValue(
2348 *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
2352 // Drill into block byref variables.
2353 bool isBlockByref = VD->hasAttr<BlocksAttr>();
2355 addr = emitBlockByrefAddress(addr, VD);
2358 // Drill into reference types.
2360 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2361 LV = EmitLoadOfReferenceLValue(addr, RefTy);
2363 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2364 LV = MakeAddrLValue(addr, T, BaseInfo);
2367 bool isLocalStorage = VD->hasLocalStorage();
2369 bool NonGCable = isLocalStorage &&
2370 !VD->getType()->isReferenceType() &&
2373 LV.getQuals().removeObjCGCAttr();
2377 bool isImpreciseLifetime =
2378 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
2379 if (isImpreciseLifetime)
2380 LV.setARCPreciseLifetime(ARCImpreciseLifetime);
2381 setObjCGCLValueClass(getContext(), E, LV);
2385 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
2386 return EmitFunctionDeclLValue(*this, E, FD);
2388 // FIXME: While we're emitting a binding from an enclosing scope, all other
2389 // DeclRefExprs we see should be implicitly treated as if they also refer to
2390 // an enclosing scope.
2391 if (const auto *BD = dyn_cast<BindingDecl>(ND))
2392 return EmitLValue(BD->getBinding());
2394 llvm_unreachable("Unhandled DeclRefExpr");
2397 LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
2398 // __extension__ doesn't affect lvalue-ness.
2399 if (E->getOpcode() == UO_Extension)
2400 return EmitLValue(E->getSubExpr());
2402 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
2403 switch (E->getOpcode()) {
2404 default: llvm_unreachable("Unknown unary operator lvalue!");
2406 QualType T = E->getSubExpr()->getType()->getPointeeType();
2407 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
2409 LValueBaseInfo BaseInfo;
2410 Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &BaseInfo);
2411 LValue LV = MakeAddrLValue(Addr, T, BaseInfo);
2412 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
2414 // We should not generate __weak write barrier on indirect reference
2415 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
2416 // But, we continue to generate __strong write barrier on indirect write
2417 // into a pointer to object.
2418 if (getLangOpts().ObjC1 &&
2419 getLangOpts().getGC() != LangOptions::NonGC &&
2421 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
2426 LValue LV = EmitLValue(E->getSubExpr());
2427 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
2429 // __real is valid on scalars. This is a faster way of testing that.
2430 // __imag can only produce an rvalue on scalars.
2431 if (E->getOpcode() == UO_Real &&
2432 !LV.getAddress().getElementType()->isStructTy()) {
2433 assert(E->getSubExpr()->getType()->isArithmeticType());
2437 QualType T = ExprTy->castAs<ComplexType>()->getElementType();
2440 (E->getOpcode() == UO_Real
2441 ? emitAddrOfRealComponent(LV.getAddress(), LV.getType())
2442 : emitAddrOfImagComponent(LV.getAddress(), LV.getType()));
2443 LValue ElemLV = MakeAddrLValue(Component, T, LV.getBaseInfo());
2444 ElemLV.getQuals().addQualifiers(LV.getQuals());
2449 LValue LV = EmitLValue(E->getSubExpr());
2450 bool isInc = E->getOpcode() == UO_PreInc;
2452 if (E->getType()->isAnyComplexType())
2453 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
2455 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
2461 LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
2462 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
2464 LValueBaseInfo(AlignmentSource::Decl, false));
2467 LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
2468 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
2470 LValueBaseInfo(AlignmentSource::Decl, false));
2473 LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
2474 auto SL = E->getFunctionName();
2475 assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
2476 StringRef FnName = CurFn->getName();
2477 if (FnName.startswith("\01"))
2478 FnName = FnName.substr(1);
2479 StringRef NameItems[] = {
2480 PredefinedExpr::getIdentTypeName(E->getIdentType()), FnName};
2481 std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
2482 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2483 if (auto *BD = dyn_cast<BlockDecl>(CurCodeDecl)) {
2484 std::string Name = SL->getString();
2485 if (!Name.empty()) {
2486 unsigned Discriminator =
2487 CGM.getCXXABI().getMangleContext().getBlockId(BD, true);
2489 Name += "_" + Twine(Discriminator + 1).str();
2490 auto C = CGM.GetAddrOfConstantCString(Name, GVName.c_str());
2491 return MakeAddrLValue(C, E->getType(), BaseInfo);
2493 auto C = CGM.GetAddrOfConstantCString(FnName, GVName.c_str());
2494 return MakeAddrLValue(C, E->getType(), BaseInfo);
2497 auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
2498 return MakeAddrLValue(C, E->getType(), BaseInfo);
2501 /// Emit a type description suitable for use by a runtime sanitizer library. The
2502 /// format of a type descriptor is
2505 /// { i16 TypeKind, i16 TypeInfo }
2508 /// followed by an array of i8 containing the type name. TypeKind is 0 for an
2509 /// integer, 1 for a floating point value, and -1 for anything else.
2510 llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
2511 // Only emit each type's descriptor once.
2512 if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
2515 uint16_t TypeKind = -1;
2516 uint16_t TypeInfo = 0;
2518 if (T->isIntegerType()) {
2520 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
2521 (T->isSignedIntegerType() ? 1 : 0);
2522 } else if (T->isFloatingType()) {
2524 TypeInfo = getContext().getTypeSize(T);
2527 // Format the type name as if for a diagnostic, including quotes and
2528 // optionally an 'aka'.
2529 SmallString<32> Buffer;
2530 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
2531 (intptr_t)T.getAsOpaquePtr(),
2532 StringRef(), StringRef(), None, Buffer,
2535 llvm::Constant *Components[] = {
2536 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
2537 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
2539 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
2541 auto *GV = new llvm::GlobalVariable(
2542 CGM.getModule(), Descriptor->getType(),
2543 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
2544 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2545 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
2547 // Remember the descriptor for this type.
2548 CGM.setTypeDescriptorInMap(T, GV);
2553 llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
2554 llvm::Type *TargetTy = IntPtrTy;
2556 // Floating-point types which fit into intptr_t are bitcast to integers
2557 // and then passed directly (after zero-extension, if necessary).
2558 if (V->getType()->isFloatingPointTy()) {
2559 unsigned Bits = V->getType()->getPrimitiveSizeInBits();
2560 if (Bits <= TargetTy->getIntegerBitWidth())
2561 V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
2565 // Integers which fit in intptr_t are zero-extended and passed directly.
2566 if (V->getType()->isIntegerTy() &&
2567 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
2568 return Builder.CreateZExt(V, TargetTy);
2570 // Pointers are passed directly, everything else is passed by address.
2571 if (!V->getType()->isPointerTy()) {
2572 Address Ptr = CreateDefaultAlignTempAlloca(V->getType());
2573 Builder.CreateStore(V, Ptr);
2574 V = Ptr.getPointer();
2576 return Builder.CreatePtrToInt(V, TargetTy);
2579 /// \brief Emit a representation of a SourceLocation for passing to a handler
2580 /// in a sanitizer runtime library. The format for this data is:
2582 /// struct SourceLocation {
2583 /// const char *Filename;
2584 /// int32_t Line, Column;
2587 /// For an invalid SourceLocation, the Filename pointer is null.
2588 llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
2589 llvm::Constant *Filename;
2592 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
2593 if (PLoc.isValid()) {
2594 StringRef FilenameString = PLoc.getFilename();
2596 int PathComponentsToStrip =
2597 CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
2598 if (PathComponentsToStrip < 0) {
2599 assert(PathComponentsToStrip != INT_MIN);
2600 int PathComponentsToKeep = -PathComponentsToStrip;
2601 auto I = llvm::sys::path::rbegin(FilenameString);
2602 auto E = llvm::sys::path::rend(FilenameString);
2603 while (I != E && --PathComponentsToKeep)
2606 FilenameString = FilenameString.substr(I - E);
2607 } else if (PathComponentsToStrip > 0) {
2608 auto I = llvm::sys::path::begin(FilenameString);
2609 auto E = llvm::sys::path::end(FilenameString);
2610 while (I != E && PathComponentsToStrip--)
2615 FilenameString.substr(I - llvm::sys::path::begin(FilenameString));
2617 FilenameString = llvm::sys::path::filename(FilenameString);
2620 auto FilenameGV = CGM.GetAddrOfConstantCString(FilenameString, ".src");
2621 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
2622 cast<llvm::GlobalVariable>(FilenameGV.getPointer()));
2623 Filename = FilenameGV.getPointer();
2624 Line = PLoc.getLine();
2625 Column = PLoc.getColumn();
2627 Filename = llvm::Constant::getNullValue(Int8PtrTy);
2631 llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
2632 Builder.getInt32(Column)};
2634 return llvm::ConstantStruct::getAnon(Data);
2638 /// \brief Specify under what conditions this check can be recovered
2639 enum class CheckRecoverableKind {
2640 /// Always terminate program execution if this check fails.
2642 /// Check supports recovering, runtime has both fatal (noreturn) and
2643 /// non-fatal handlers for this check.
2645 /// Runtime conditionally aborts, always need to support recovery.
2650 static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
2651 assert(llvm::countPopulation(Kind) == 1);
2653 case SanitizerKind::Vptr:
2654 return CheckRecoverableKind::AlwaysRecoverable;
2655 case SanitizerKind::Return:
2656 case SanitizerKind::Unreachable:
2657 return CheckRecoverableKind::Unrecoverable;
2659 return CheckRecoverableKind::Recoverable;
2664 struct SanitizerHandlerInfo {
2665 char const *const Name;
2670 const SanitizerHandlerInfo SanitizerHandlers[] = {
2671 #define SANITIZER_CHECK(Enum, Name, Version) {#Name, Version},
2672 LIST_SANITIZER_CHECKS
2673 #undef SANITIZER_CHECK
2676 static void emitCheckHandlerCall(CodeGenFunction &CGF,
2677 llvm::FunctionType *FnType,
2678 ArrayRef<llvm::Value *> FnArgs,
2679 SanitizerHandler CheckHandler,
2680 CheckRecoverableKind RecoverKind, bool IsFatal,
2681 llvm::BasicBlock *ContBB) {
2682 assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
2683 bool NeedsAbortSuffix =
2684 IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
2685 const SanitizerHandlerInfo &CheckInfo = SanitizerHandlers[CheckHandler];
2686 const StringRef CheckName = CheckInfo.Name;
2687 std::string FnName =
2688 ("__ubsan_handle_" + CheckName +
2689 (CheckInfo.Version ? "_v" + llvm::utostr(CheckInfo.Version) : "") +
2690 (NeedsAbortSuffix ? "_abort" : ""))
2693 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
2695 llvm::AttrBuilder B;
2697 B.addAttribute(llvm::Attribute::NoReturn)
2698 .addAttribute(llvm::Attribute::NoUnwind);
2700 B.addAttribute(llvm::Attribute::UWTable);
2702 llvm::Value *Fn = CGF.CGM.CreateRuntimeFunction(
2704 llvm::AttributeList::get(CGF.getLLVMContext(),
2705 llvm::AttributeList::FunctionIndex, B),
2707 llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
2709 HandlerCall->setDoesNotReturn();
2710 CGF.Builder.CreateUnreachable();
2712 CGF.Builder.CreateBr(ContBB);
2716 void CodeGenFunction::EmitCheck(
2717 ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
2718 SanitizerHandler CheckHandler, ArrayRef<llvm::Constant *> StaticArgs,
2719 ArrayRef<llvm::Value *> DynamicArgs) {
2720 assert(IsSanitizerScope);
2721 assert(Checked.size() > 0);
2722 assert(CheckHandler >= 0 &&
2723 CheckHandler < sizeof(SanitizerHandlers) / sizeof(*SanitizerHandlers));
2724 const StringRef CheckName = SanitizerHandlers[CheckHandler].Name;
2726 llvm::Value *FatalCond = nullptr;
2727 llvm::Value *RecoverableCond = nullptr;
2728 llvm::Value *TrapCond = nullptr;
2729 for (int i = 0, n = Checked.size(); i < n; ++i) {
2730 llvm::Value *Check = Checked[i].first;
2731 // -fsanitize-trap= overrides -fsanitize-recover=.
2732 llvm::Value *&Cond =
2733 CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
2735 : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
2738 Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
2742 EmitTrapCheck(TrapCond);
2743 if (!FatalCond && !RecoverableCond)
2746 llvm::Value *JointCond;
2747 if (FatalCond && RecoverableCond)
2748 JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
2750 JointCond = FatalCond ? FatalCond : RecoverableCond;
2753 CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
2754 assert(SanOpts.has(Checked[0].second));
2756 for (int i = 1, n = Checked.size(); i < n; ++i) {
2757 assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
2758 "All recoverable kinds in a single check must be same!");
2759 assert(SanOpts.has(Checked[i].second));
2763 llvm::BasicBlock *Cont = createBasicBlock("cont");
2764 llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
2765 llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
2766 // Give hint that we very much don't expect to execute the handler
2767 // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
2768 llvm::MDBuilder MDHelper(getLLVMContext());
2769 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2770 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
2771 EmitBlock(Handlers);
2773 // Handler functions take an i8* pointing to the (handler-specific) static
2774 // information block, followed by a sequence of intptr_t arguments
2775 // representing operand values.
2776 SmallVector<llvm::Value *, 4> Args;
2777 SmallVector<llvm::Type *, 4> ArgTypes;
2778 Args.reserve(DynamicArgs.size() + 1);
2779 ArgTypes.reserve(DynamicArgs.size() + 1);
2781 // Emit handler arguments and create handler function type.
2782 if (!StaticArgs.empty()) {
2783 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2785 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2786 llvm::GlobalVariable::PrivateLinkage, Info);
2787 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2788 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2789 Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
2790 ArgTypes.push_back(Int8PtrTy);
2793 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
2794 Args.push_back(EmitCheckValue(DynamicArgs[i]));
2795 ArgTypes.push_back(IntPtrTy);
2798 llvm::FunctionType *FnType =
2799 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
2801 if (!FatalCond || !RecoverableCond) {
2802 // Simple case: we need to generate a single handler call, either
2803 // fatal, or non-fatal.
2804 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind,
2805 (FatalCond != nullptr), Cont);
2807 // Emit two handler calls: first one for set of unrecoverable checks,
2808 // another one for recoverable.
2809 llvm::BasicBlock *NonFatalHandlerBB =
2810 createBasicBlock("non_fatal." + CheckName);
2811 llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
2812 Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
2813 EmitBlock(FatalHandlerBB);
2814 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, true,
2816 EmitBlock(NonFatalHandlerBB);
2817 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, false,
2824 void CodeGenFunction::EmitCfiSlowPathCheck(
2825 SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId,
2826 llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) {
2827 llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
2829 llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
2830 llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
2832 llvm::MDBuilder MDHelper(getLLVMContext());
2833 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2834 BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
2838 bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind);
2840 llvm::CallInst *CheckCall;
2842 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2844 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2845 llvm::GlobalVariable::PrivateLinkage, Info);
2846 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2847 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2849 llvm::Constant *SlowPathDiagFn = CGM.getModule().getOrInsertFunction(
2850 "__cfi_slowpath_diag",
2851 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
2853 CheckCall = Builder.CreateCall(
2855 {TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)});
2857 llvm::Constant *SlowPathFn = CGM.getModule().getOrInsertFunction(
2859 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
2860 CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
2863 CheckCall->setDoesNotThrow();
2868 // Emit a stub for __cfi_check function so that the linker knows about this
2869 // symbol in LTO mode.
2870 void CodeGenFunction::EmitCfiCheckStub() {
2871 llvm::Module *M = &CGM.getModule();
2872 auto &Ctx = M->getContext();
2873 llvm::Function *F = llvm::Function::Create(
2874 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy}, false),
2875 llvm::GlobalValue::WeakAnyLinkage, "__cfi_check", M);
2876 llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx, "entry", F);
2877 // FIXME: consider emitting an intrinsic call like
2878 // call void @llvm.cfi_check(i64 %0, i8* %1, i8* %2)
2879 // which can be lowered in CrossDSOCFI pass to the actual contents of
2880 // __cfi_check. This would allow inlining of __cfi_check calls.
2881 llvm::CallInst::Create(
2882 llvm::Intrinsic::getDeclaration(M, llvm::Intrinsic::trap), "", BB);
2883 llvm::ReturnInst::Create(Ctx, nullptr, BB);
2886 // This function is basically a switch over the CFI failure kind, which is
2887 // extracted from CFICheckFailData (1st function argument). Each case is either
2888 // llvm.trap or a call to one of the two runtime handlers, based on
2889 // -fsanitize-trap and -fsanitize-recover settings. Default case (invalid
2890 // failure kind) traps, but this should really never happen. CFICheckFailData
2891 // can be nullptr if the calling module has -fsanitize-trap behavior for this
2892 // check kind; in this case __cfi_check_fail traps as well.
2893 void CodeGenFunction::EmitCfiCheckFail() {
2894 SanitizerScope SanScope(this);
2895 FunctionArgList Args;
2896 ImplicitParamDecl ArgData(getContext(), getContext().VoidPtrTy,
2897 ImplicitParamDecl::Other);
2898 ImplicitParamDecl ArgAddr(getContext(), getContext().VoidPtrTy,
2899 ImplicitParamDecl::Other);
2900 Args.push_back(&ArgData);
2901 Args.push_back(&ArgAddr);
2903 const CGFunctionInfo &FI =
2904 CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args);
2906 llvm::Function *F = llvm::Function::Create(
2907 llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false),
2908 llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule());
2909 F->setVisibility(llvm::GlobalValue::HiddenVisibility);
2911 StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args,
2915 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false,
2916 CGM.getContext().VoidPtrTy, ArgData.getLocation());
2918 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false,
2919 CGM.getContext().VoidPtrTy, ArgAddr.getLocation());
2921 // Data == nullptr means the calling module has trap behaviour for this check.
2922 llvm::Value *DataIsNotNullPtr =
2923 Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy));
2924 EmitTrapCheck(DataIsNotNullPtr);
2926 llvm::StructType *SourceLocationTy =
2927 llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty);
2928 llvm::StructType *CfiCheckFailDataTy =
2929 llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy);
2931 llvm::Value *V = Builder.CreateConstGEP2_32(
2933 Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0,
2935 Address CheckKindAddr(V, getIntAlign());
2936 llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr);
2938 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
2939 CGM.getLLVMContext(),
2940 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
2941 llvm::Value *ValidVtable = Builder.CreateZExt(
2942 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
2943 {Addr, AllVtables}),
2946 const std::pair<int, SanitizerMask> CheckKinds[] = {
2947 {CFITCK_VCall, SanitizerKind::CFIVCall},
2948 {CFITCK_NVCall, SanitizerKind::CFINVCall},
2949 {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast},
2950 {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast},
2951 {CFITCK_ICall, SanitizerKind::CFIICall}};
2953 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 5> Checks;
2954 for (auto CheckKindMaskPair : CheckKinds) {
2955 int Kind = CheckKindMaskPair.first;
2956 SanitizerMask Mask = CheckKindMaskPair.second;
2958 Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind));
2959 if (CGM.getLangOpts().Sanitize.has(Mask))
2960 EmitCheck(std::make_pair(Cond, Mask), SanitizerHandler::CFICheckFail, {},
2961 {Data, Addr, ValidVtable});
2963 EmitTrapCheck(Cond);
2967 // The only reference to this function will be created during LTO link.
2968 // Make sure it survives until then.
2969 CGM.addUsedGlobal(F);
2972 void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) {
2973 llvm::BasicBlock *Cont = createBasicBlock("cont");
2975 // If we're optimizing, collapse all calls to trap down to just one per
2976 // function to save on code size.
2977 if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
2978 TrapBB = createBasicBlock("trap");
2979 Builder.CreateCondBr(Checked, Cont, TrapBB);
2981 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
2982 TrapCall->setDoesNotReturn();
2983 TrapCall->setDoesNotThrow();
2984 Builder.CreateUnreachable();
2986 Builder.CreateCondBr(Checked, Cont, TrapBB);
2992 llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
2993 llvm::CallInst *TrapCall = Builder.CreateCall(CGM.getIntrinsic(IntrID));
2995 if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
2996 auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
2997 CGM.getCodeGenOpts().TrapFuncName);
2998 TrapCall->addAttribute(llvm::AttributeList::FunctionIndex, A);
3004 Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E,
3005 LValueBaseInfo *BaseInfo) {
3006 assert(E->getType()->isArrayType() &&
3007 "Array to pointer decay must have array source type!");
3009 // Expressions of array type can't be bitfields or vector elements.
3010 LValue LV = EmitLValue(E);
3011 Address Addr = LV.getAddress();
3012 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
3014 // If the array type was an incomplete type, we need to make sure
3015 // the decay ends up being the right type.
3016 llvm::Type *NewTy = ConvertType(E->getType());
3017 Addr = Builder.CreateElementBitCast(Addr, NewTy);
3019 // Note that VLA pointers are always decayed, so we don't need to do
3021 if (!E->getType()->isVariableArrayType()) {
3022 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3023 "Expected pointer to array");
3024 Addr = Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(), "arraydecay");
3027 QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
3028 return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType));
3031 /// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
3032 /// array to pointer, return the array subexpression.
3033 static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
3034 // If this isn't just an array->pointer decay, bail out.
3035 const auto *CE = dyn_cast<CastExpr>(E);
3036 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
3039 // If this is a decay from variable width array, bail out.
3040 const Expr *SubExpr = CE->getSubExpr();
3041 if (SubExpr->getType()->isVariableArrayType())
3047 static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF,
3049 ArrayRef<llvm::Value*> indices,
3053 const llvm::Twine &name = "arrayidx") {
3055 return CGF.EmitCheckedInBoundsGEP(ptr, indices, signedIndices, loc, name);
3057 return CGF.Builder.CreateGEP(ptr, indices, name);
3061 static CharUnits getArrayElementAlign(CharUnits arrayAlign,
3063 CharUnits eltSize) {
3064 // If we have a constant index, we can use the exact offset of the
3065 // element we're accessing.
3066 if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
3067 CharUnits offset = constantIdx->getZExtValue() * eltSize;
3068 return arrayAlign.alignmentAtOffset(offset);
3070 // Otherwise, use the worst-case alignment for any element.
3072 return arrayAlign.alignmentOfArrayElement(eltSize);
3076 static QualType getFixedSizeElementType(const ASTContext &ctx,
3077 const VariableArrayType *vla) {
3080 eltType = vla->getElementType();
3081 } while ((vla = ctx.getAsVariableArrayType(eltType)));
3085 static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
3086 ArrayRef<llvm::Value *> indices,
3087 QualType eltType, bool inbounds,
3088 bool signedIndices, SourceLocation loc,
3089 const llvm::Twine &name = "arrayidx") {
3090 // All the indices except that last must be zero.
3092 for (auto idx : indices.drop_back())
3093 assert(isa<llvm::ConstantInt>(idx) &&
3094 cast<llvm::ConstantInt>(idx)->isZero());
3097 // Determine the element size of the statically-sized base. This is
3098 // the thing that the indices are expressed in terms of.
3099 if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
3100 eltType = getFixedSizeElementType(CGF.getContext(), vla);
3103 // We can use that to compute the best alignment of the element.
3104 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
3105 CharUnits eltAlign =
3106 getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
3108 llvm::Value *eltPtr = emitArraySubscriptGEP(
3109 CGF, addr.getPointer(), indices, inbounds, signedIndices, loc, name);
3110 return Address(eltPtr, eltAlign);
3113 LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
3115 // The index must always be an integer, which is not an aggregate. Emit it
3116 // in lexical order (this complexity is, sadly, required by C++17).
3117 llvm::Value *IdxPre =
3118 (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E->getIdx()) : nullptr;
3119 bool SignedIndices = false;
3120 auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * {
3122 if (E->getLHS() != E->getIdx()) {
3123 assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS");
3124 Idx = EmitScalarExpr(E->getIdx());
3127 QualType IdxTy = E->getIdx()->getType();
3128 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
3129 SignedIndices |= IdxSigned;
3131 if (SanOpts.has(SanitizerKind::ArrayBounds))
3132 EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
3134 // Extend or truncate the index type to 32 or 64-bits.
3135 if (Promote && Idx->getType() != IntPtrTy)
3136 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
3142 // If the base is a vector type, then we are forming a vector element lvalue
3143 // with this subscript.
3144 if (E->getBase()->getType()->isVectorType() &&
3145 !isa<ExtVectorElementExpr>(E->getBase())) {
3146 // Emit the vector as an lvalue to get its address.
3147 LValue LHS = EmitLValue(E->getBase());
3148 auto *Idx = EmitIdxAfterBase(/*Promote*/false);
3149 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
3150 return LValue::MakeVectorElt(LHS.getAddress(), Idx,
3151 E->getBase()->getType(),
3155 // All the other cases basically behave like simple offsetting.
3157 // Handle the extvector case we ignored above.
3158 if (isa<ExtVectorElementExpr>(E->getBase())) {
3159 LValue LV = EmitLValue(E->getBase());
3160 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3161 Address Addr = EmitExtVectorElementLValue(LV);
3163 QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
3164 Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true,
3165 SignedIndices, E->getExprLoc());
3166 return MakeAddrLValue(Addr, EltType, LV.getBaseInfo());
3169 LValueBaseInfo BaseInfo;
3170 Address Addr = Address::invalid();
3171 if (const VariableArrayType *vla =
3172 getContext().getAsVariableArrayType(E->getType())) {
3173 // The base must be a pointer, which is not an aggregate. Emit
3174 // it. It needs to be emitted first in case it's what captures
3176 Addr = EmitPointerWithAlignment(E->getBase(), &BaseInfo);
3177 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3179 // The element count here is the total number of non-VLA elements.
3180 llvm::Value *numElements = getVLASize(vla).first;
3182 // Effectively, the multiply by the VLA size is part of the GEP.
3183 // GEP indexes are signed, and scaling an index isn't permitted to
3184 // signed-overflow, so we use the same semantics for our explicit
3185 // multiply. We suppress this if overflow is not undefined behavior.
3186 if (getLangOpts().isSignedOverflowDefined()) {
3187 Idx = Builder.CreateMul(Idx, numElements);
3189 Idx = Builder.CreateNSWMul(Idx, numElements);
3192 Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
3193 !getLangOpts().isSignedOverflowDefined(),
3194 SignedIndices, E->getExprLoc());
3196 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
3197 // Indexing over an interface, as in "NSString *P; P[4];"
3199 // Emit the base pointer.
3200 Addr = EmitPointerWithAlignment(E->getBase(), &BaseInfo);
3201 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3203 CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
3204 llvm::Value *InterfaceSizeVal =
3205 llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());
3207 llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
3209 // We don't necessarily build correct LLVM struct types for ObjC
3210 // interfaces, so we can't rely on GEP to do this scaling
3211 // correctly, so we need to cast to i8*. FIXME: is this actually
3212 // true? A lot of other things in the fragile ABI would break...
3213 llvm::Type *OrigBaseTy = Addr.getType();
3214 Addr = Builder.CreateElementBitCast(Addr, Int8Ty);
3217 CharUnits EltAlign =
3218 getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
3219 llvm::Value *EltPtr =
3220 emitArraySubscriptGEP(*this, Addr.getPointer(), ScaledIdx, false,
3221 SignedIndices, E->getExprLoc());
3222 Addr = Address(EltPtr, EltAlign);
3225 Addr = Builder.CreateBitCast(Addr, OrigBaseTy);
3226 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3227 // If this is A[i] where A is an array, the frontend will have decayed the
3228 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3229 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3230 // "gep x, i" here. Emit one "gep A, 0, i".
3231 assert(Array->getType()->isArrayType() &&
3232 "Array to pointer decay must have array source type!");
3234 // For simple multidimensional array indexing, set the 'accessed' flag for
3235 // better bounds-checking of the base expression.
3236 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3237 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3239 ArrayLV = EmitLValue(Array);
3240 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3242 // Propagate the alignment from the array itself to the result.
3243 Addr = emitArraySubscriptGEP(
3244 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
3245 E->getType(), !getLangOpts().isSignedOverflowDefined(), SignedIndices,
3247 BaseInfo = ArrayLV.getBaseInfo();
3249 // The base must be a pointer; emit it with an estimate of its alignment.
3250 Addr = EmitPointerWithAlignment(E->getBase(), &BaseInfo);
3251 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3252 Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
3253 !getLangOpts().isSignedOverflowDefined(),
3254 SignedIndices, E->getExprLoc());
3257 LValue LV = MakeAddrLValue(Addr, E->getType(), BaseInfo);
3259 // TODO: Preserve/extend path TBAA metadata?
3261 if (getLangOpts().ObjC1 &&
3262 getLangOpts().getGC() != LangOptions::NonGC) {
3263 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
3264 setObjCGCLValueClass(getContext(), E, LV);
3269 static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base,
3270 LValueBaseInfo &BaseInfo,
3271 QualType BaseTy, QualType ElTy,
3272 bool IsLowerBound) {
3274 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParenImpCasts())) {
3275 BaseLVal = CGF.EmitOMPArraySectionExpr(ASE, IsLowerBound);
3276 if (BaseTy->isArrayType()) {
3277 Address Addr = BaseLVal.getAddress();
3278 BaseInfo = BaseLVal.getBaseInfo();
3280 // If the array type was an incomplete type, we need to make sure
3281 // the decay ends up being the right type.
3282 llvm::Type *NewTy = CGF.ConvertType(BaseTy);
3283 Addr = CGF.Builder.CreateElementBitCast(Addr, NewTy);
3285 // Note that VLA pointers are always decayed, so we don't need to do
3287 if (!BaseTy->isVariableArrayType()) {
3288 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3289 "Expected pointer to array");
3290 Addr = CGF.Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(),
3294 return CGF.Builder.CreateElementBitCast(Addr,
3295 CGF.ConvertTypeForMem(ElTy));
3297 LValueBaseInfo TypeInfo;
3298 CharUnits Align = CGF.getNaturalTypeAlignment(ElTy, &TypeInfo);
3299 BaseInfo.mergeForCast(TypeInfo);
3300 return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress()), Align);
3302 return CGF.EmitPointerWithAlignment(Base, &BaseInfo);
3305 LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
3306 bool IsLowerBound) {
3309 dyn_cast<OMPArraySectionExpr>(E->getBase()->IgnoreParenImpCasts()))
3310 BaseTy = OMPArraySectionExpr::getBaseOriginalType(ASE);
3312 BaseTy = E->getBase()->getType();
3313 QualType ResultExprTy;
3314 if (auto *AT = getContext().getAsArrayType(BaseTy))
3315 ResultExprTy = AT->getElementType();
3317 ResultExprTy = BaseTy->getPointeeType();
3318 llvm::Value *Idx = nullptr;
3319 if (IsLowerBound || E->getColonLoc().isInvalid()) {
3320 // Requesting lower bound or upper bound, but without provided length and
3321 // without ':' symbol for the default length -> length = 1.
3322 // Idx = LowerBound ?: 0;
3323 if (auto *LowerBound = E->getLowerBound()) {
3324 Idx = Builder.CreateIntCast(
3325 EmitScalarExpr(LowerBound), IntPtrTy,
3326 LowerBound->getType()->hasSignedIntegerRepresentation());
3328 Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
3330 // Try to emit length or lower bound as constant. If this is possible, 1
3331 // is subtracted from constant length or lower bound. Otherwise, emit LLVM
3332 // IR (LB + Len) - 1.
3333 auto &C = CGM.getContext();
3334 auto *Length = E->getLength();
3335 llvm::APSInt ConstLength;
3337 // Idx = LowerBound + Length - 1;
3338 if (Length->isIntegerConstantExpr(ConstLength, C)) {
3339 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3342 auto *LowerBound = E->getLowerBound();
3343 llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
3344 if (LowerBound && LowerBound->isIntegerConstantExpr(ConstLowerBound, C)) {
3345 ConstLowerBound = ConstLowerBound.zextOrTrunc(PointerWidthInBits);
3346 LowerBound = nullptr;
3350 else if (!LowerBound)
3353 if (Length || LowerBound) {
3354 auto *LowerBoundVal =
3356 ? Builder.CreateIntCast(
3357 EmitScalarExpr(LowerBound), IntPtrTy,
3358 LowerBound->getType()->hasSignedIntegerRepresentation())
3359 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
3362 ? Builder.CreateIntCast(
3363 EmitScalarExpr(Length), IntPtrTy,
3364 Length->getType()->hasSignedIntegerRepresentation())
3365 : llvm::ConstantInt::get(IntPtrTy, ConstLength);
3366 Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
3368 !getLangOpts().isSignedOverflowDefined());
3369 if (Length && LowerBound) {
3370 Idx = Builder.CreateSub(
3371 Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
3372 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3375 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
3377 // Idx = ArraySize - 1;
3378 QualType ArrayTy = BaseTy->isPointerType()
3379 ? E->getBase()->IgnoreParenImpCasts()->getType()
3381 if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) {
3382 Length = VAT->getSizeExpr();
3383 if (Length->isIntegerConstantExpr(ConstLength, C))
3386 auto *CAT = C.getAsConstantArrayType(ArrayTy);
3387 ConstLength = CAT->getSize();
3390 auto *LengthVal = Builder.CreateIntCast(
3391 EmitScalarExpr(Length), IntPtrTy,
3392 Length->getType()->hasSignedIntegerRepresentation());
3393 Idx = Builder.CreateSub(
3394 LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
3395 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3397 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3399 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
3405 Address EltPtr = Address::invalid();
3406 LValueBaseInfo BaseInfo;
3407 if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
3408 // The base must be a pointer, which is not an aggregate. Emit
3409 // it. It needs to be emitted first in case it's what captures
3412 emitOMPArraySectionBase(*this, E->getBase(), BaseInfo, BaseTy,
3413 VLA->getElementType(), IsLowerBound);
3414 // The element count here is the total number of non-VLA elements.
3415 llvm::Value *NumElements = getVLASize(VLA).first;
3417 // Effectively, the multiply by the VLA size is part of the GEP.
3418 // GEP indexes are signed, and scaling an index isn't permitted to
3419 // signed-overflow, so we use the same semantics for our explicit
3420 // multiply. We suppress this if overflow is not undefined behavior.
3421 if (getLangOpts().isSignedOverflowDefined())
3422 Idx = Builder.CreateMul(Idx, NumElements);
3424 Idx = Builder.CreateNSWMul(Idx, NumElements);
3425 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(),
3426 !getLangOpts().isSignedOverflowDefined(),
3427 /*SignedIndices=*/false, E->getExprLoc());
3428 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3429 // If this is A[i] where A is an array, the frontend will have decayed the
3430 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3431 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3432 // "gep x, i" here. Emit one "gep A, 0, i".
3433 assert(Array->getType()->isArrayType() &&
3434 "Array to pointer decay must have array source type!");
3436 // For simple multidimensional array indexing, set the 'accessed' flag for
3437 // better bounds-checking of the base expression.
3438 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3439 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3441 ArrayLV = EmitLValue(Array);
3443 // Propagate the alignment from the array itself to the result.
3444 EltPtr = emitArraySubscriptGEP(
3445 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
3446 ResultExprTy, !getLangOpts().isSignedOverflowDefined(),
3447 /*SignedIndices=*/false, E->getExprLoc());
3448 BaseInfo = ArrayLV.getBaseInfo();
3450 Address Base = emitOMPArraySectionBase(*this, E->getBase(), BaseInfo,
3451 BaseTy, ResultExprTy, IsLowerBound);
3452 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy,
3453 !getLangOpts().isSignedOverflowDefined(),
3454 /*SignedIndices=*/false, E->getExprLoc());
3457 return MakeAddrLValue(EltPtr, ResultExprTy, BaseInfo);
3460 LValue CodeGenFunction::
3461 EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
3462 // Emit the base vector as an l-value.
3465 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
3467 // If it is a pointer to a vector, emit the address and form an lvalue with
3469 LValueBaseInfo BaseInfo;
3470 Address Ptr = EmitPointerWithAlignment(E->getBase(), &BaseInfo);
3471 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
3472 Base = MakeAddrLValue(Ptr, PT->getPointeeType(), BaseInfo);
3473 Base.getQuals().removeObjCGCAttr();
3474 } else if (E->getBase()->isGLValue()) {
3475 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
3476 // emit the base as an lvalue.
3477 assert(E->getBase()->getType()->isVectorType());
3478 Base = EmitLValue(E->getBase());
3480 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
3481 assert(E->getBase()->getType()->isVectorType() &&
3482 "Result must be a vector");
3483 llvm::Value *Vec = EmitScalarExpr(E->getBase());
3485 // Store the vector to memory (because LValue wants an address).
3486 Address VecMem = CreateMemTemp(E->getBase()->getType());
3487 Builder.CreateStore(Vec, VecMem);
3488 Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
3489 LValueBaseInfo(AlignmentSource::Decl, false));
3493 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
3495 // Encode the element access list into a vector of unsigned indices.
3496 SmallVector<uint32_t, 4> Indices;
3497 E->getEncodedElementAccess(Indices);
3499 if (Base.isSimple()) {
3500 llvm::Constant *CV =
3501 llvm::ConstantDataVector::get(getLLVMContext(), Indices);
3502 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
3503 Base.getBaseInfo());
3505 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
3507 llvm::Constant *BaseElts = Base.getExtVectorElts();
3508 SmallVector<llvm::Constant *, 4> CElts;
3510 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
3511 CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
3512 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
3513 return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
3514 Base.getBaseInfo());
3517 LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
3518 Expr *BaseExpr = E->getBase();
3519 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
3522 LValueBaseInfo BaseInfo;
3523 Address Addr = EmitPointerWithAlignment(BaseExpr, &BaseInfo);
3524 QualType PtrTy = BaseExpr->getType()->getPointeeType();
3525 SanitizerSet SkippedChecks;
3526 bool IsBaseCXXThis = IsWrappedCXXThis(BaseExpr);
3528 SkippedChecks.set(SanitizerKind::Alignment, true);
3529 if (IsBaseCXXThis || isa<DeclRefExpr>(BaseExpr))
3530 SkippedChecks.set(SanitizerKind::Null, true);
3531 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy,
3532 /*Alignment=*/CharUnits::Zero(), SkippedChecks);
3533 BaseLV = MakeAddrLValue(Addr, PtrTy, BaseInfo);
3535 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
3537 NamedDecl *ND = E->getMemberDecl();
3538 if (auto *Field = dyn_cast<FieldDecl>(ND)) {
3539 LValue LV = EmitLValueForField(BaseLV, Field);
3540 setObjCGCLValueClass(getContext(), E, LV);
3544 if (auto *VD = dyn_cast<VarDecl>(ND))
3545 return EmitGlobalVarDeclLValue(*this, E, VD);
3547 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
3548 return EmitFunctionDeclLValue(*this, E, FD);
3550 llvm_unreachable("Unhandled member declaration!");
3553 /// Given that we are currently emitting a lambda, emit an l-value for
3554 /// one of its members.
3555 LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
3556 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
3557 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
3558 QualType LambdaTagType =
3559 getContext().getTagDeclType(Field->getParent());
3560 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
3561 return EmitLValueForField(LambdaLV, Field);
3564 /// Drill down to the storage of a field without walking into
3565 /// reference types.
3567 /// The resulting address doesn't necessarily have the right type.
3568 static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
3569 const FieldDecl *field) {
3570 const RecordDecl *rec = field->getParent();
3573 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
3576 // Adjust the alignment down to the given offset.
3577 // As a special case, if the LLVM field index is 0, we know that this
3579 assert((idx != 0 || CGF.getContext().getASTRecordLayout(rec)
3580 .getFieldOffset(field->getFieldIndex()) == 0) &&
3581 "LLVM field at index zero had non-zero offset?");
3583 auto &recLayout = CGF.getContext().getASTRecordLayout(rec);
3584 auto offsetInBits = recLayout.getFieldOffset(field->getFieldIndex());
3585 offset = CGF.getContext().toCharUnitsFromBits(offsetInBits);
3588 return CGF.Builder.CreateStructGEP(base, idx, offset, field->getName());
3591 static bool hasAnyVptr(const QualType Type, const ASTContext &Context) {
3592 const auto *RD = Type.getTypePtr()->getAsCXXRecordDecl();
3596 if (RD->isDynamicClass())
3599 for (const auto &Base : RD->bases())
3600 if (hasAnyVptr(Base.getType(), Context))
3603 for (const FieldDecl *Field : RD->fields())
3604 if (hasAnyVptr(Field->getType(), Context))
3610 LValue CodeGenFunction::EmitLValueForField(LValue base,
3611 const FieldDecl *field) {
3612 LValueBaseInfo BaseInfo = base.getBaseInfo();
3613 AlignmentSource fieldAlignSource =
3614 getFieldAlignmentSource(BaseInfo.getAlignmentSource());
3615 LValueBaseInfo FieldBaseInfo(fieldAlignSource, BaseInfo.getMayAlias());
3617 const RecordDecl *rec = field->getParent();
3618 if (rec->isUnion() || rec->hasAttr<MayAliasAttr>())
3619 FieldBaseInfo.setMayAlias(true);
3620 bool mayAlias = FieldBaseInfo.getMayAlias();
3622 if (field->isBitField()) {
3623 const CGRecordLayout &RL =
3624 CGM.getTypes().getCGRecordLayout(field->getParent());
3625 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
3626 Address Addr = base.getAddress();
3627 unsigned Idx = RL.getLLVMFieldNo(field);
3629 // For structs, we GEP to the field that the record layout suggests.
3630 Addr = Builder.CreateStructGEP(Addr, Idx, Info.StorageOffset,
3632 // Get the access type.
3633 llvm::Type *FieldIntTy =
3634 llvm::Type::getIntNTy(getLLVMContext(), Info.StorageSize);
3635 if (Addr.getElementType() != FieldIntTy)
3636 Addr = Builder.CreateElementBitCast(Addr, FieldIntTy);
3638 QualType fieldType =
3639 field->getType().withCVRQualifiers(base.getVRQualifiers());
3640 return LValue::MakeBitfield(Addr, Info, fieldType, FieldBaseInfo);
3643 QualType type = field->getType();
3644 Address addr = base.getAddress();
3645 unsigned cvr = base.getVRQualifiers();
3646 bool TBAAPath = CGM.getCodeGenOpts().StructPathTBAA;
3647 if (rec->isUnion()) {
3648 // For unions, there is no pointer adjustment.
3649 assert(!type->isReferenceType() && "union has reference member");
3650 // TODO: handle path-aware TBAA for union.
3653 const auto FieldType = field->getType();
3654 if (CGM.getCodeGenOpts().StrictVTablePointers &&
3655 hasAnyVptr(FieldType, getContext()))
3656 // Because unions can easily skip invariant.barriers, we need to add
3657 // a barrier every time CXXRecord field with vptr is referenced.
3658 addr = Address(Builder.CreateInvariantGroupBarrier(addr.getPointer()),
3659 addr.getAlignment());
3661 // For structs, we GEP to the field that the record layout suggests.
3662 addr = emitAddrOfFieldStorage(*this, addr, field);
3664 // If this is a reference field, load the reference right now.
3665 if (const ReferenceType *refType = type->getAs<ReferenceType>()) {
3666 llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
3667 if (cvr & Qualifiers::Volatile) load->setVolatile(true);
3669 // Loading the reference will disable path-aware TBAA.
3671 if (CGM.shouldUseTBAA()) {
3674 tbaa = CGM.getTBAAInfo(getContext().CharTy);
3676 tbaa = CGM.getTBAAInfo(type);
3678 CGM.DecorateInstructionWithTBAA(load, tbaa);
3682 type = refType->getPointeeType();
3684 CharUnits alignment =
3685 getNaturalTypeAlignment(type, &FieldBaseInfo, /*pointee*/ true);
3686 FieldBaseInfo.setMayAlias(false);
3687 addr = Address(load, alignment);
3689 // Qualifiers on the struct don't apply to the referencee, and
3690 // we'll pick up CVR from the actual type later, so reset these
3691 // additional qualifiers now.
3696 // Make sure that the address is pointing to the right type. This is critical
3697 // for both unions and structs. A union needs a bitcast, a struct element
3698 // will need a bitcast if the LLVM type laid out doesn't match the desired
3700 addr = Builder.CreateElementBitCast(addr,
3701 CGM.getTypes().ConvertTypeForMem(type),
3704 if (field->hasAttr<AnnotateAttr>())
3705 addr = EmitFieldAnnotations(field, addr);
3707 LValue LV = MakeAddrLValue(addr, type, FieldBaseInfo);
3708 LV.getQuals().addCVRQualifiers(cvr);
3710 const ASTRecordLayout &Layout =
3711 getContext().getASTRecordLayout(field->getParent());
3712 // Set the base type to be the base type of the base LValue and
3713 // update offset to be relative to the base type.
3714 LV.setTBAABaseType(mayAlias ? getContext().CharTy : base.getTBAABaseType());
3715 LV.setTBAAOffset(mayAlias ? 0 : base.getTBAAOffset() +
3716 Layout.getFieldOffset(field->getFieldIndex()) /
3717 getContext().getCharWidth());
3720 // __weak attribute on a field is ignored.
3721 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
3722 LV.getQuals().removeObjCGCAttr();
3724 // Fields of may_alias structs act like 'char' for TBAA purposes.
3725 // FIXME: this should get propagated down through anonymous structs
3727 if (mayAlias && LV.getTBAAInfo())
3728 LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy));
3734 CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
3735 const FieldDecl *Field) {
3736 QualType FieldType = Field->getType();
3738 if (!FieldType->isReferenceType())
3739 return EmitLValueForField(Base, Field);
3741 Address V = emitAddrOfFieldStorage(*this, Base.getAddress(), Field);
3743 // Make sure that the address is pointing to the right type.
3744 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
3745 V = Builder.CreateElementBitCast(V, llvmType, Field->getName());
3747 // TODO: access-path TBAA?
3748 LValueBaseInfo BaseInfo = Base.getBaseInfo();
3749 LValueBaseInfo FieldBaseInfo(
3750 getFieldAlignmentSource(BaseInfo.getAlignmentSource()),
3751 BaseInfo.getMayAlias());
3752 return MakeAddrLValue(V, FieldType, FieldBaseInfo);
3755 LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
3756 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
3757 if (E->isFileScope()) {
3758 ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
3759 return MakeAddrLValue(GlobalPtr, E->getType(), BaseInfo);
3761 if (E->getType()->isVariablyModifiedType())
3762 // make sure to emit the VLA size.
3763 EmitVariablyModifiedType(E->getType());
3765 Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
3766 const Expr *InitExpr = E->getInitializer();
3767 LValue Result = MakeAddrLValue(DeclPtr, E->getType(), BaseInfo);
3769 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
3775 LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
3776 if (!E->isGLValue())
3777 // Initializing an aggregate temporary in C++11: T{...}.
3778 return EmitAggExprToLValue(E);
3780 // An lvalue initializer list must be initializing a reference.
3781 assert(E->isTransparent() && "non-transparent glvalue init list");
3782 return EmitLValue(E->getInit(0));
3785 /// Emit the operand of a glvalue conditional operator. This is either a glvalue
3786 /// or a (possibly-parenthesized) throw-expression. If this is a throw, no
3787 /// LValue is returned and the current block has been terminated.
3788 static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
3789 const Expr *Operand) {
3790 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
3791 CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
3795 return CGF.EmitLValue(Operand);
3798 LValue CodeGenFunction::
3799 EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
3800 if (!expr->isGLValue()) {
3801 // ?: here should be an aggregate.
3802 assert(hasAggregateEvaluationKind(expr->getType()) &&
3803 "Unexpected conditional operator!");
3804 return EmitAggExprToLValue(expr);
3807 OpaqueValueMapping binding(*this, expr);
3809 const Expr *condExpr = expr->getCond();
3811 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
3812 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
3813 if (!CondExprBool) std::swap(live, dead);
3815 if (!ContainsLabel(dead)) {
3816 // If the true case is live, we need to track its region.
3818 incrementProfileCounter(expr);
3819 return EmitLValue(live);
3823 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
3824 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
3825 llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
3827 ConditionalEvaluation eval(*this);
3828 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr));
3830 // Any temporaries created here are conditional.
3831 EmitBlock(lhsBlock);
3832 incrementProfileCounter(expr);
3834 Optional<LValue> lhs =
3835 EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
3838 if (lhs && !lhs->isSimple())
3839 return EmitUnsupportedLValue(expr, "conditional operator");
3841 lhsBlock = Builder.GetInsertBlock();
3843 Builder.CreateBr(contBlock);
3845 // Any temporaries created here are conditional.
3846 EmitBlock(rhsBlock);
3848 Optional<LValue> rhs =
3849 EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
3851 if (rhs && !rhs->isSimple())
3852 return EmitUnsupportedLValue(expr, "conditional operator");
3853 rhsBlock = Builder.GetInsertBlock();
3855 EmitBlock(contBlock);
3858 llvm::PHINode *phi = Builder.CreatePHI(lhs->getPointer()->getType(),
3860 phi->addIncoming(lhs->getPointer(), lhsBlock);
3861 phi->addIncoming(rhs->getPointer(), rhsBlock);
3862 Address result(phi, std::min(lhs->getAlignment(), rhs->getAlignment()));
3863 AlignmentSource alignSource =
3864 std::max(lhs->getBaseInfo().getAlignmentSource(),
3865 rhs->getBaseInfo().getAlignmentSource());
3866 bool MayAlias = lhs->getBaseInfo().getMayAlias() ||
3867 rhs->getBaseInfo().getMayAlias();
3868 return MakeAddrLValue(result, expr->getType(),
3869 LValueBaseInfo(alignSource, MayAlias));
3871 assert((lhs || rhs) &&
3872 "both operands of glvalue conditional are throw-expressions?");
3873 return lhs ? *lhs : *rhs;
3877 /// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
3878 /// type. If the cast is to a reference, we can have the usual lvalue result,
3879 /// otherwise if a cast is needed by the code generator in an lvalue context,
3880 /// then it must mean that we need the address of an aggregate in order to
3881 /// access one of its members. This can happen for all the reasons that casts
3882 /// are permitted with aggregate result, including noop aggregate casts, and
3883 /// cast from scalar to union.
3884 LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
3885 switch (E->getCastKind()) {
3888 case CK_ArrayToPointerDecay:
3889 case CK_FunctionToPointerDecay:
3890 case CK_NullToMemberPointer:
3891 case CK_NullToPointer:
3892 case CK_IntegralToPointer:
3893 case CK_PointerToIntegral:
3894 case CK_PointerToBoolean:
3895 case CK_VectorSplat:
3896 case CK_IntegralCast:
3897 case CK_BooleanToSignedIntegral:
3898 case CK_IntegralToBoolean:
3899 case CK_IntegralToFloating:
3900 case CK_FloatingToIntegral:
3901 case CK_FloatingToBoolean:
3902 case CK_FloatingCast:
3903 case CK_FloatingRealToComplex:
3904 case CK_FloatingComplexToReal:
3905 case CK_FloatingComplexToBoolean:
3906 case CK_FloatingComplexCast:
3907 case CK_FloatingComplexToIntegralComplex:
3908 case CK_IntegralRealToComplex:
3909 case CK_IntegralComplexToReal:
3910 case CK_IntegralComplexToBoolean:
3911 case CK_IntegralComplexCast:
3912 case CK_IntegralComplexToFloatingComplex:
3913 case CK_DerivedToBaseMemberPointer:
3914 case CK_BaseToDerivedMemberPointer:
3915 case CK_MemberPointerToBoolean:
3916 case CK_ReinterpretMemberPointer:
3917 case CK_AnyPointerToBlockPointerCast:
3918 case CK_ARCProduceObject:
3919 case CK_ARCConsumeObject:
3920 case CK_ARCReclaimReturnedObject:
3921 case CK_ARCExtendBlockObject:
3922 case CK_CopyAndAutoreleaseBlockObject:
3923 case CK_AddressSpaceConversion:
3924 case CK_IntToOCLSampler:
3925 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
3928 llvm_unreachable("dependent cast kind in IR gen!");
3930 case CK_BuiltinFnToFnPtr:
3931 llvm_unreachable("builtin functions are handled elsewhere");
3933 // These are never l-values; just use the aggregate emission code.
3934 case CK_NonAtomicToAtomic:
3935 case CK_AtomicToNonAtomic:
3936 return EmitAggExprToLValue(E);
3939 LValue LV = EmitLValue(E->getSubExpr());
3940 Address V = LV.getAddress();
3941 const auto *DCE = cast<CXXDynamicCastExpr>(E);
3942 return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
3945 case CK_ConstructorConversion:
3946 case CK_UserDefinedConversion:
3947 case CK_CPointerToObjCPointerCast:
3948 case CK_BlockPointerToObjCPointerCast:
3950 case CK_LValueToRValue:
3951 return EmitLValue(E->getSubExpr());
3953 case CK_UncheckedDerivedToBase:
3954 case CK_DerivedToBase: {
3955 const RecordType *DerivedClassTy =
3956 E->getSubExpr()->getType()->getAs<RecordType>();
3957 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
3959 LValue LV = EmitLValue(E->getSubExpr());
3960 Address This = LV.getAddress();
3962 // Perform the derived-to-base conversion
3963 Address Base = GetAddressOfBaseClass(
3964 This, DerivedClassDecl, E->path_begin(), E->path_end(),
3965 /*NullCheckValue=*/false, E->getExprLoc());
3967 return MakeAddrLValue(Base, E->getType(), LV.getBaseInfo());
3970 return EmitAggExprToLValue(E);
3971 case CK_BaseToDerived: {
3972 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
3973 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
3975 LValue LV = EmitLValue(E->getSubExpr());
3977 // Perform the base-to-derived conversion
3979 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
3980 E->path_begin(), E->path_end(),
3981 /*NullCheckValue=*/false);
3983 // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
3984 // performed and the object is not of the derived type.
3985 if (sanitizePerformTypeCheck())
3986 EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
3987 Derived.getPointer(), E->getType());
3989 if (SanOpts.has(SanitizerKind::CFIDerivedCast))
3990 EmitVTablePtrCheckForCast(E->getType(), Derived.getPointer(),
3991 /*MayBeNull=*/false,
3992 CFITCK_DerivedCast, E->getLocStart());
3994 return MakeAddrLValue(Derived, E->getType(), LV.getBaseInfo());
3996 case CK_LValueBitCast: {
3997 // This must be a reinterpret_cast (or c-style equivalent).
3998 const auto *CE = cast<ExplicitCastExpr>(E);
4000 CGM.EmitExplicitCastExprType(CE, this);
4001 LValue LV = EmitLValue(E->getSubExpr());
4002 Address V = Builder.CreateBitCast(LV.getAddress(),
4003 ConvertType(CE->getTypeAsWritten()));
4005 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
4006 EmitVTablePtrCheckForCast(E->getType(), V.getPointer(),
4007 /*MayBeNull=*/false,
4008 CFITCK_UnrelatedCast, E->getLocStart());
4010 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo());
4012 case CK_ObjCObjectLValueCast: {
4013 LValue LV = EmitLValue(E->getSubExpr());
4014 Address V = Builder.CreateElementBitCast(LV.getAddress(),
4015 ConvertType(E->getType()));
4016 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo());
4018 case CK_ZeroToOCLQueue:
4019 llvm_unreachable("NULL to OpenCL queue lvalue cast is not valid");
4020 case CK_ZeroToOCLEvent:
4021 llvm_unreachable("NULL to OpenCL event lvalue cast is not valid");
4024 llvm_unreachable("Unhandled lvalue cast kind?");
4027 LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
4028 assert(OpaqueValueMappingData::shouldBindAsLValue(e));
4029 return getOpaqueLValueMapping(e);
4032 RValue CodeGenFunction::EmitRValueForField(LValue LV,
4033 const FieldDecl *FD,
4034 SourceLocation Loc) {
4035 QualType FT = FD->getType();
4036 LValue FieldLV = EmitLValueForField(LV, FD);
4037 switch (getEvaluationKind(FT)) {
4039 return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
4041 return FieldLV.asAggregateRValue();
4043 // This routine is used to load fields one-by-one to perform a copy, so
4044 // don't load reference fields.
4045 if (FD->getType()->isReferenceType())
4046 return RValue::get(FieldLV.getPointer());
4047 return EmitLoadOfLValue(FieldLV, Loc);
4049 llvm_unreachable("bad evaluation kind");
4052 //===--------------------------------------------------------------------===//
4053 // Expression Emission
4054 //===--------------------------------------------------------------------===//
4056 RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
4057 ReturnValueSlot ReturnValue) {
4058 // Builtins never have block type.
4059 if (E->getCallee()->getType()->isBlockPointerType())
4060 return EmitBlockCallExpr(E, ReturnValue);
4062 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
4063 return EmitCXXMemberCallExpr(CE, ReturnValue);
4065 if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
4066 return EmitCUDAKernelCallExpr(CE, ReturnValue);
4068 if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
4069 if (const CXXMethodDecl *MD =
4070 dyn_cast_or_null<CXXMethodDecl>(CE->getCalleeDecl()))
4071 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
4073 CGCallee callee = EmitCallee(E->getCallee());
4075 if (callee.isBuiltin()) {
4076 return EmitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(),
4080 if (callee.isPseudoDestructor()) {
4081 return EmitCXXPseudoDestructorExpr(callee.getPseudoDestructorExpr());
4084 return EmitCall(E->getCallee()->getType(), callee, E, ReturnValue);
4087 /// Emit a CallExpr without considering whether it might be a subclass.
4088 RValue CodeGenFunction::EmitSimpleCallExpr(const CallExpr *E,
4089 ReturnValueSlot ReturnValue) {
4090 CGCallee Callee = EmitCallee(E->getCallee());
4091 return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue);
4094 static CGCallee EmitDirectCallee(CodeGenFunction &CGF, const FunctionDecl *FD) {
4095 if (auto builtinID = FD->getBuiltinID()) {
4096 return CGCallee::forBuiltin(builtinID, FD);
4099 llvm::Constant *calleePtr = EmitFunctionDeclPointer(CGF.CGM, FD);
4100 return CGCallee::forDirect(calleePtr, FD);
4103 CGCallee CodeGenFunction::EmitCallee(const Expr *E) {
4104 E = E->IgnoreParens();
4106 // Look through function-to-pointer decay.
4107 if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) {
4108 if (ICE->getCastKind() == CK_FunctionToPointerDecay ||
4109 ICE->getCastKind() == CK_BuiltinFnToFnPtr) {
4110 return EmitCallee(ICE->getSubExpr());
4113 // Resolve direct calls.
4114 } else if (auto DRE = dyn_cast<DeclRefExpr>(E)) {
4115 if (auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
4116 return EmitDirectCallee(*this, FD);
4118 } else if (auto ME = dyn_cast<MemberExpr>(E)) {
4119 if (auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) {
4120 EmitIgnoredExpr(ME->getBase());
4121 return EmitDirectCallee(*this, FD);
4124 // Look through template substitutions.
4125 } else if (auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
4126 return EmitCallee(NTTP->getReplacement());
4128 // Treat pseudo-destructor calls differently.
4129 } else if (auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) {
4130 return CGCallee::forPseudoDestructor(PDE);
4133 // Otherwise, we have an indirect reference.
4134 llvm::Value *calleePtr;
4135 QualType functionType;
4136 if (auto ptrType = E->getType()->getAs<PointerType>()) {
4137 calleePtr = EmitScalarExpr(E);
4138 functionType = ptrType->getPointeeType();
4140 functionType = E->getType();
4141 calleePtr = EmitLValue(E).getPointer();
4143 assert(functionType->isFunctionType());
4144 CGCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(),
4145 E->getReferencedDeclOfCallee());
4146 CGCallee callee(calleeInfo, calleePtr);
4150 LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
4151 // Comma expressions just emit their LHS then their RHS as an l-value.
4152 if (E->getOpcode() == BO_Comma) {
4153 EmitIgnoredExpr(E->getLHS());
4154 EnsureInsertPoint();
4155 return EmitLValue(E->getRHS());
4158 if (E->getOpcode() == BO_PtrMemD ||
4159 E->getOpcode() == BO_PtrMemI)
4160 return EmitPointerToDataMemberBinaryExpr(E);
4162 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
4164 // Note that in all of these cases, __block variables need the RHS
4165 // evaluated first just in case the variable gets moved by the RHS.
4167 switch (getEvaluationKind(E->getType())) {
4169 switch (E->getLHS()->getType().getObjCLifetime()) {
4170 case Qualifiers::OCL_Strong:
4171 return EmitARCStoreStrong(E, /*ignored*/ false).first;
4173 case Qualifiers::OCL_Autoreleasing:
4174 return EmitARCStoreAutoreleasing(E).first;
4176 // No reason to do any of these differently.
4177 case Qualifiers::OCL_None:
4178 case Qualifiers::OCL_ExplicitNone:
4179 case Qualifiers::OCL_Weak:
4183 RValue RV = EmitAnyExpr(E->getRHS());
4184 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
4186 EmitNullabilityCheck(LV, RV.getScalarVal(), E->getExprLoc());
4187 EmitStoreThroughLValue(RV, LV);
4192 return EmitComplexAssignmentLValue(E);
4195 return EmitAggExprToLValue(E);
4197 llvm_unreachable("bad evaluation kind");
4200 LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
4201 RValue RV = EmitCallExpr(E);
4204 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
4205 LValueBaseInfo(AlignmentSource::Decl, false));
4207 assert(E->getCallReturnType(getContext())->isReferenceType() &&
4208 "Can't have a scalar return unless the return type is a "
4211 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
4214 LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
4215 // FIXME: This shouldn't require another copy.
4216 return EmitAggExprToLValue(E);
4219 LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
4220 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
4221 && "binding l-value to type which needs a temporary");
4222 AggValueSlot Slot = CreateAggTemp(E->getType());
4223 EmitCXXConstructExpr(E, Slot);
4224 return MakeAddrLValue(Slot.getAddress(), E->getType(),
4225 LValueBaseInfo(AlignmentSource::Decl, false));
4229 CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
4230 return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType());
4233 Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
4234 return Builder.CreateElementBitCast(CGM.GetAddrOfUuidDescriptor(E),
4235 ConvertType(E->getType()));
4238 LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
4239 return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(),
4240 LValueBaseInfo(AlignmentSource::Decl, false));
4244 CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
4245 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
4246 Slot.setExternallyDestructed();
4247 EmitAggExpr(E->getSubExpr(), Slot);
4248 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
4249 return MakeAddrLValue(Slot.getAddress(), E->getType(),
4250 LValueBaseInfo(AlignmentSource::Decl, false));
4254 CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
4255 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
4256 EmitLambdaExpr(E, Slot);
4257 return MakeAddrLValue(Slot.getAddress(), E->getType(),
4258 LValueBaseInfo(AlignmentSource::Decl, false));
4261 LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
4262 RValue RV = EmitObjCMessageExpr(E);
4265 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
4266 LValueBaseInfo(AlignmentSource::Decl, false));
4268 assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
4269 "Can't have a scalar return unless the return type is a "
4272 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
4275 LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
4277 CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
4278 return MakeAddrLValue(V, E->getType(),
4279 LValueBaseInfo(AlignmentSource::Decl, false));
4282 llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
4283 const ObjCIvarDecl *Ivar) {
4284 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
4287 LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
4288 llvm::Value *BaseValue,
4289 const ObjCIvarDecl *Ivar,
4290 unsigned CVRQualifiers) {
4291 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
4292 Ivar, CVRQualifiers);
4295 LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
4296 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
4297 llvm::Value *BaseValue = nullptr;
4298 const Expr *BaseExpr = E->getBase();
4299 Qualifiers BaseQuals;
4302 BaseValue = EmitScalarExpr(BaseExpr);
4303 ObjectTy = BaseExpr->getType()->getPointeeType();
4304 BaseQuals = ObjectTy.getQualifiers();
4306 LValue BaseLV = EmitLValue(BaseExpr);
4307 BaseValue = BaseLV.getPointer();
4308 ObjectTy = BaseExpr->getType();
4309 BaseQuals = ObjectTy.getQualifiers();
4313 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
4314 BaseQuals.getCVRQualifiers());
4315 setObjCGCLValueClass(getContext(), E, LV);
4319 LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
4320 // Can only get l-value for message expression returning aggregate type
4321 RValue RV = EmitAnyExprToTemp(E);
4322 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
4323 LValueBaseInfo(AlignmentSource::Decl, false));
4326 RValue CodeGenFunction::EmitCall(QualType CalleeType, const CGCallee &OrigCallee,
4327 const CallExpr *E, ReturnValueSlot ReturnValue,
4328 llvm::Value *Chain) {
4329 // Get the actual function type. The callee type will always be a pointer to
4330 // function type or a block pointer type.
4331 assert(CalleeType->isFunctionPointerType() &&
4332 "Call must have function pointer type!");
4334 const Decl *TargetDecl = OrigCallee.getAbstractInfo().getCalleeDecl();
4336 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
4337 // We can only guarantee that a function is called from the correct
4338 // context/function based on the appropriate target attributes,
4339 // so only check in the case where we have both always_inline and target
4340 // since otherwise we could be making a conditional call after a check for
4341 // the proper cpu features (and it won't cause code generation issues due to
4342 // function based code generation).
4343 if (TargetDecl->hasAttr<AlwaysInlineAttr>() &&
4344 TargetDecl->hasAttr<TargetAttr>())
4345 checkTargetFeatures(E, FD);
4347 CalleeType = getContext().getCanonicalType(CalleeType);
4349 const auto *FnType =
4350 cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
4352 CGCallee Callee = OrigCallee;
4354 if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
4355 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4356 if (llvm::Constant *PrefixSig =
4357 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
4358 SanitizerScope SanScope(this);
4359 llvm::Constant *FTRTTIConst =
4360 CGM.GetAddrOfRTTIDescriptor(QualType(FnType, 0), /*ForEH=*/true);
4361 llvm::Type *PrefixStructTyElems[] = {
4362 PrefixSig->getType(),
4363 FTRTTIConst->getType()
4365 llvm::StructType *PrefixStructTy = llvm::StructType::get(
4366 CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true);
4368 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4370 llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
4371 CalleePtr, llvm::PointerType::getUnqual(PrefixStructTy));
4372 llvm::Value *CalleeSigPtr =
4373 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0);
4374 llvm::Value *CalleeSig =
4375 Builder.CreateAlignedLoad(CalleeSigPtr, getIntAlign());
4376 llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
4378 llvm::BasicBlock *Cont = createBasicBlock("cont");
4379 llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
4380 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
4382 EmitBlock(TypeCheck);
4383 llvm::Value *CalleeRTTIPtr =
4384 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1);
4385 llvm::Value *CalleeRTTI =
4386 Builder.CreateAlignedLoad(CalleeRTTIPtr, getPointerAlign());
4387 llvm::Value *CalleeRTTIMatch =
4388 Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
4389 llvm::Constant *StaticData[] = {
4390 EmitCheckSourceLocation(E->getLocStart()),
4391 EmitCheckTypeDescriptor(CalleeType)
4393 EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
4394 SanitizerHandler::FunctionTypeMismatch, StaticData, CalleePtr);
4396 Builder.CreateBr(Cont);
4401 // If we are checking indirect calls and this call is indirect, check that the
4402 // function pointer is a member of the bit set for the function type.
4403 if (SanOpts.has(SanitizerKind::CFIICall) &&
4404 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4405 SanitizerScope SanScope(this);
4406 EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
4408 llvm::Metadata *MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0));
4409 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
4411 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4412 llvm::Value *CastedCallee = Builder.CreateBitCast(CalleePtr, Int8PtrTy);
4413 llvm::Value *TypeTest = Builder.CreateCall(
4414 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedCallee, TypeId});
4416 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
4417 llvm::Constant *StaticData[] = {
4418 llvm::ConstantInt::get(Int8Ty, CFITCK_ICall),
4419 EmitCheckSourceLocation(E->getLocStart()),
4420 EmitCheckTypeDescriptor(QualType(FnType, 0)),
4422 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
4423 EmitCfiSlowPathCheck(SanitizerKind::CFIICall, TypeTest, CrossDsoTypeId,
4424 CastedCallee, StaticData);
4426 EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIICall),
4427 SanitizerHandler::CFICheckFail, StaticData,
4428 {CastedCallee, llvm::UndefValue::get(IntPtrTy)});
4434 Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
4435 CGM.getContext().VoidPtrTy);
4437 // C++17 requires that we evaluate arguments to a call using assignment syntax
4438 // right-to-left, and that we evaluate arguments to certain other operators
4439 // left-to-right. Note that we allow this to override the order dictated by
4440 // the calling convention on the MS ABI, which means that parameter
4441 // destruction order is not necessarily reverse construction order.
4442 // FIXME: Revisit this based on C++ committee response to unimplementability.
4443 EvaluationOrder Order = EvaluationOrder::Default;
4444 if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
4445 if (OCE->isAssignmentOp())
4446 Order = EvaluationOrder::ForceRightToLeft;
4448 switch (OCE->getOperator()) {
4450 case OO_GreaterGreater:
4455 Order = EvaluationOrder::ForceLeftToRight;
4463 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(),
4464 E->getDirectCallee(), /*ParamsToSkip*/ 0, Order);
4466 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
4467 Args, FnType, /*isChainCall=*/Chain);
4470 // If the expression that denotes the called function has a type
4471 // that does not include a prototype, [the default argument
4472 // promotions are performed]. If the number of arguments does not
4473 // equal the number of parameters, the behavior is undefined. If
4474 // the function is defined with a type that includes a prototype,
4475 // and either the prototype ends with an ellipsis (, ...) or the
4476 // types of the arguments after promotion are not compatible with
4477 // the types of the parameters, the behavior is undefined. If the
4478 // function is defined with a type that does not include a
4479 // prototype, and the types of the arguments after promotion are
4480 // not compatible with those of the parameters after promotion,
4481 // the behavior is undefined [except in some trivial cases].
4482 // That is, in the general case, we should assume that a call
4483 // through an unprototyped function type works like a *non-variadic*
4484 // call. The way we make this work is to cast to the exact type
4485 // of the promoted arguments.
4487 // Chain calls use this same code path to add the invisible chain parameter
4488 // to the function type.
4489 if (isa<FunctionNoProtoType>(FnType) || Chain) {
4490 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
4491 CalleeTy = CalleeTy->getPointerTo();
4493 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4494 CalleePtr = Builder.CreateBitCast(CalleePtr, CalleeTy, "callee.knr.cast");
4495 Callee.setFunctionPointer(CalleePtr);
4498 return EmitCall(FnInfo, Callee, ReturnValue, Args);
4501 LValue CodeGenFunction::
4502 EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
4503 Address BaseAddr = Address::invalid();
4504 if (E->getOpcode() == BO_PtrMemI) {
4505 BaseAddr = EmitPointerWithAlignment(E->getLHS());
4507 BaseAddr = EmitLValue(E->getLHS()).getAddress();
4510 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
4512 const MemberPointerType *MPT
4513 = E->getRHS()->getType()->getAs<MemberPointerType>();
4515 LValueBaseInfo BaseInfo;
4516 Address MemberAddr =
4517 EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT, &BaseInfo);
4519 return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), BaseInfo);
4522 /// Given the address of a temporary variable, produce an r-value of
4524 RValue CodeGenFunction::convertTempToRValue(Address addr,
4526 SourceLocation loc) {
4527 LValue lvalue = MakeAddrLValue(addr, type,
4528 LValueBaseInfo(AlignmentSource::Decl, false));
4529 switch (getEvaluationKind(type)) {
4531 return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
4533 return lvalue.asAggregateRValue();
4535 return RValue::get(EmitLoadOfScalar(lvalue, loc));
4537 llvm_unreachable("bad evaluation kind");
4540 void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
4541 assert(Val->getType()->isFPOrFPVectorTy());
4542 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
4545 llvm::MDBuilder MDHelper(getLLVMContext());
4546 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
4548 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
4552 struct LValueOrRValue {
4558 static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
4559 const PseudoObjectExpr *E,
4561 AggValueSlot slot) {
4562 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
4564 // Find the result expression, if any.
4565 const Expr *resultExpr = E->getResultExpr();
4566 LValueOrRValue result;
4568 for (PseudoObjectExpr::const_semantics_iterator
4569 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
4570 const Expr *semantic = *i;
4572 // If this semantic expression is an opaque value, bind it
4573 // to the result of its source expression.
4574 if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
4576 // If this is the result expression, we may need to evaluate
4577 // directly into the slot.
4578 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
4580 if (ov == resultExpr && ov->isRValue() && !forLValue &&
4581 CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
4582 CGF.EmitAggExpr(ov->getSourceExpr(), slot);
4583 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
4584 LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
4586 opaqueData = OVMA::bind(CGF, ov, LV);
4587 result.RV = slot.asRValue();
4589 // Otherwise, emit as normal.
4591 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
4593 // If this is the result, also evaluate the result now.
4594 if (ov == resultExpr) {
4596 result.LV = CGF.EmitLValue(ov);
4598 result.RV = CGF.EmitAnyExpr(ov, slot);
4602 opaques.push_back(opaqueData);
4604 // Otherwise, if the expression is the result, evaluate it
4605 // and remember the result.
4606 } else if (semantic == resultExpr) {
4608 result.LV = CGF.EmitLValue(semantic);
4610 result.RV = CGF.EmitAnyExpr(semantic, slot);
4612 // Otherwise, evaluate the expression in an ignored context.
4614 CGF.EmitIgnoredExpr(semantic);
4618 // Unbind all the opaques now.
4619 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
4620 opaques[i].unbind(CGF);
4625 RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
4626 AggValueSlot slot) {
4627 return emitPseudoObjectExpr(*this, E, false, slot).RV;
4630 LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
4631 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;