1 //===--- CGExprAgg.cpp - Emit LLVM Code from Aggregate 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 Aggregate Expr nodes as LLVM code.
12 //===----------------------------------------------------------------------===//
14 #include "CodeGenFunction.h"
15 #include "CGObjCRuntime.h"
16 #include "CodeGenModule.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclTemplate.h"
20 #include "clang/AST/StmtVisitor.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/Function.h"
23 #include "llvm/IR/GlobalVariable.h"
24 #include "llvm/IR/Intrinsics.h"
25 using namespace clang;
26 using namespace CodeGen;
28 //===----------------------------------------------------------------------===//
29 // Aggregate Expression Emitter
30 //===----------------------------------------------------------------------===//
33 class AggExprEmitter : public StmtVisitor<AggExprEmitter> {
39 /// We want to use 'dest' as the return slot except under two
41 /// - The destination slot requires garbage collection, so we
42 /// need to use the GC API.
43 /// - The destination slot is potentially aliased.
44 bool shouldUseDestForReturnSlot() const {
45 return !(Dest.requiresGCollection() || Dest.isPotentiallyAliased());
48 ReturnValueSlot getReturnValueSlot() const {
49 if (!shouldUseDestForReturnSlot())
50 return ReturnValueSlot();
52 return ReturnValueSlot(Dest.getAddr(), Dest.isVolatile(), IsResultUnused);
55 AggValueSlot EnsureSlot(QualType T) {
56 if (!Dest.isIgnored()) return Dest;
57 return CGF.CreateAggTemp(T, "agg.tmp.ensured");
59 void EnsureDest(QualType T) {
60 if (!Dest.isIgnored()) return;
61 Dest = CGF.CreateAggTemp(T, "agg.tmp.ensured");
65 AggExprEmitter(CodeGenFunction &cgf, AggValueSlot Dest, bool IsResultUnused)
66 : CGF(cgf), Builder(CGF.Builder), Dest(Dest),
67 IsResultUnused(IsResultUnused) { }
69 //===--------------------------------------------------------------------===//
71 //===--------------------------------------------------------------------===//
73 /// EmitAggLoadOfLValue - Given an expression with aggregate type that
74 /// represents a value lvalue, this method emits the address of the lvalue,
75 /// then loads the result into DestPtr.
76 void EmitAggLoadOfLValue(const Expr *E);
78 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
79 void EmitFinalDestCopy(QualType type, const LValue &src);
80 void EmitFinalDestCopy(QualType type, RValue src,
81 CharUnits srcAlignment = CharUnits::Zero());
82 void EmitCopy(QualType type, const AggValueSlot &dest,
83 const AggValueSlot &src);
85 void EmitMoveFromReturnSlot(const Expr *E, RValue Src);
87 void EmitArrayInit(llvm::Value *DestPtr, llvm::ArrayType *AType,
88 QualType elementType, InitListExpr *E);
90 AggValueSlot::NeedsGCBarriers_t needsGC(QualType T) {
91 if (CGF.getLangOpts().getGC() && TypeRequiresGCollection(T))
92 return AggValueSlot::NeedsGCBarriers;
93 return AggValueSlot::DoesNotNeedGCBarriers;
96 bool TypeRequiresGCollection(QualType T);
98 //===--------------------------------------------------------------------===//
100 //===--------------------------------------------------------------------===//
102 void Visit(Expr *E) {
103 ApplyDebugLocation DL(CGF, E);
104 StmtVisitor<AggExprEmitter>::Visit(E);
107 void VisitStmt(Stmt *S) {
108 CGF.ErrorUnsupported(S, "aggregate expression");
110 void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); }
111 void VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
112 Visit(GE->getResultExpr());
114 void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); }
115 void VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
116 return Visit(E->getReplacement());
120 void VisitDeclRefExpr(DeclRefExpr *E) {
121 // For aggregates, we should always be able to emit the variable
122 // as an l-value unless it's a reference. This is due to the fact
123 // that we can't actually ever see a normal l2r conversion on an
124 // aggregate in C++, and in C there's no language standard
125 // actively preventing us from listing variables in the captures
127 if (E->getDecl()->getType()->isReferenceType()) {
128 if (CodeGenFunction::ConstantEmission result
129 = CGF.tryEmitAsConstant(E)) {
130 EmitFinalDestCopy(E->getType(), result.getReferenceLValue(CGF, E));
135 EmitAggLoadOfLValue(E);
138 void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); }
139 void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); }
140 void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); }
141 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
142 void VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
143 EmitAggLoadOfLValue(E);
145 void VisitPredefinedExpr(const PredefinedExpr *E) {
146 EmitAggLoadOfLValue(E);
150 void VisitCastExpr(CastExpr *E);
151 void VisitCallExpr(const CallExpr *E);
152 void VisitStmtExpr(const StmtExpr *E);
153 void VisitBinaryOperator(const BinaryOperator *BO);
154 void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO);
155 void VisitBinAssign(const BinaryOperator *E);
156 void VisitBinComma(const BinaryOperator *E);
158 void VisitObjCMessageExpr(ObjCMessageExpr *E);
159 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
160 EmitAggLoadOfLValue(E);
163 void VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E);
164 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO);
165 void VisitChooseExpr(const ChooseExpr *CE);
166 void VisitInitListExpr(InitListExpr *E);
167 void VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
168 void VisitNoInitExpr(NoInitExpr *E) { } // Do nothing.
169 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
170 Visit(DAE->getExpr());
172 void VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
173 CodeGenFunction::CXXDefaultInitExprScope Scope(CGF);
174 Visit(DIE->getExpr());
176 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
177 void VisitCXXConstructExpr(const CXXConstructExpr *E);
178 void VisitLambdaExpr(LambdaExpr *E);
179 void VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E);
180 void VisitExprWithCleanups(ExprWithCleanups *E);
181 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
182 void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); }
183 void VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E);
184 void VisitOpaqueValueExpr(OpaqueValueExpr *E);
186 void VisitPseudoObjectExpr(PseudoObjectExpr *E) {
187 if (E->isGLValue()) {
188 LValue LV = CGF.EmitPseudoObjectLValue(E);
189 return EmitFinalDestCopy(E->getType(), LV);
192 CGF.EmitPseudoObjectRValue(E, EnsureSlot(E->getType()));
195 void VisitVAArgExpr(VAArgExpr *E);
197 void EmitInitializationToLValue(Expr *E, LValue Address);
198 void EmitNullInitializationToLValue(LValue Address);
199 // case Expr::ChooseExprClass:
200 void VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); }
201 void VisitAtomicExpr(AtomicExpr *E) {
202 CGF.EmitAtomicExpr(E, EnsureSlot(E->getType()).getAddr());
205 } // end anonymous namespace.
207 //===----------------------------------------------------------------------===//
209 //===----------------------------------------------------------------------===//
211 /// EmitAggLoadOfLValue - Given an expression with aggregate type that
212 /// represents a value lvalue, this method emits the address of the lvalue,
213 /// then loads the result into DestPtr.
214 void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) {
215 LValue LV = CGF.EmitLValue(E);
217 // If the type of the l-value is atomic, then do an atomic load.
218 if (LV.getType()->isAtomicType() || CGF.LValueIsSuitableForInlineAtomic(LV)) {
219 CGF.EmitAtomicLoad(LV, E->getExprLoc(), Dest);
223 EmitFinalDestCopy(E->getType(), LV);
226 /// \brief True if the given aggregate type requires special GC API calls.
227 bool AggExprEmitter::TypeRequiresGCollection(QualType T) {
228 // Only record types have members that might require garbage collection.
229 const RecordType *RecordTy = T->getAs<RecordType>();
230 if (!RecordTy) return false;
232 // Don't mess with non-trivial C++ types.
233 RecordDecl *Record = RecordTy->getDecl();
234 if (isa<CXXRecordDecl>(Record) &&
235 (cast<CXXRecordDecl>(Record)->hasNonTrivialCopyConstructor() ||
236 !cast<CXXRecordDecl>(Record)->hasTrivialDestructor()))
239 // Check whether the type has an object member.
240 return Record->hasObjectMember();
243 /// \brief Perform the final move to DestPtr if for some reason
244 /// getReturnValueSlot() didn't use it directly.
246 /// The idea is that you do something like this:
247 /// RValue Result = EmitSomething(..., getReturnValueSlot());
248 /// EmitMoveFromReturnSlot(E, Result);
250 /// If nothing interferes, this will cause the result to be emitted
251 /// directly into the return value slot. Otherwise, a final move
252 /// will be performed.
253 void AggExprEmitter::EmitMoveFromReturnSlot(const Expr *E, RValue src) {
254 if (shouldUseDestForReturnSlot()) {
255 // Logically, Dest.getAddr() should equal Src.getAggregateAddr().
256 // The possibility of undef rvalues complicates that a lot,
257 // though, so we can't really assert.
261 // Otherwise, copy from there to the destination.
262 assert(Dest.getAddr() != src.getAggregateAddr());
263 std::pair<CharUnits, CharUnits> typeInfo =
264 CGF.getContext().getTypeInfoInChars(E->getType());
265 EmitFinalDestCopy(E->getType(), src, typeInfo.second);
268 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
269 void AggExprEmitter::EmitFinalDestCopy(QualType type, RValue src,
270 CharUnits srcAlign) {
271 assert(src.isAggregate() && "value must be aggregate value!");
272 LValue srcLV = CGF.MakeAddrLValue(src.getAggregateAddr(), type, srcAlign);
273 EmitFinalDestCopy(type, srcLV);
276 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
277 void AggExprEmitter::EmitFinalDestCopy(QualType type, const LValue &src) {
278 // If Dest is ignored, then we're evaluating an aggregate expression
279 // in a context that doesn't care about the result. Note that loads
280 // from volatile l-values force the existence of a non-ignored
282 if (Dest.isIgnored())
285 AggValueSlot srcAgg =
286 AggValueSlot::forLValue(src, AggValueSlot::IsDestructed,
287 needsGC(type), AggValueSlot::IsAliased);
288 EmitCopy(type, Dest, srcAgg);
291 /// Perform a copy from the source into the destination.
293 /// \param type - the type of the aggregate being copied; qualifiers are
295 void AggExprEmitter::EmitCopy(QualType type, const AggValueSlot &dest,
296 const AggValueSlot &src) {
297 if (dest.requiresGCollection()) {
298 CharUnits sz = CGF.getContext().getTypeSizeInChars(type);
299 llvm::Value *size = llvm::ConstantInt::get(CGF.SizeTy, sz.getQuantity());
300 CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF,
307 // If the result of the assignment is used, copy the LHS there also.
308 // It's volatile if either side is. Use the minimum alignment of
310 CGF.EmitAggregateCopy(dest.getAddr(), src.getAddr(), type,
311 dest.isVolatile() || src.isVolatile(),
312 std::min(dest.getAlignment(), src.getAlignment()));
315 /// \brief Emit the initializer for a std::initializer_list initialized with a
316 /// real initializer list.
318 AggExprEmitter::VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E) {
319 // Emit an array containing the elements. The array is externally destructed
320 // if the std::initializer_list object is.
321 ASTContext &Ctx = CGF.getContext();
322 LValue Array = CGF.EmitLValue(E->getSubExpr());
323 assert(Array.isSimple() && "initializer_list array not a simple lvalue");
324 llvm::Value *ArrayPtr = Array.getAddress();
326 const ConstantArrayType *ArrayType =
327 Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
328 assert(ArrayType && "std::initializer_list constructed from non-array");
330 // FIXME: Perform the checks on the field types in SemaInit.
331 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
332 RecordDecl::field_iterator Field = Record->field_begin();
333 if (Field == Record->field_end()) {
334 CGF.ErrorUnsupported(E, "weird std::initializer_list");
339 if (!Field->getType()->isPointerType() ||
340 !Ctx.hasSameType(Field->getType()->getPointeeType(),
341 ArrayType->getElementType())) {
342 CGF.ErrorUnsupported(E, "weird std::initializer_list");
346 AggValueSlot Dest = EnsureSlot(E->getType());
347 LValue DestLV = CGF.MakeAddrLValue(Dest.getAddr(), E->getType(),
348 Dest.getAlignment());
349 LValue Start = CGF.EmitLValueForFieldInitialization(DestLV, *Field);
350 llvm::Value *Zero = llvm::ConstantInt::get(CGF.PtrDiffTy, 0);
351 llvm::Value *IdxStart[] = { Zero, Zero };
352 llvm::Value *ArrayStart =
353 Builder.CreateInBoundsGEP(ArrayPtr, IdxStart, "arraystart");
354 CGF.EmitStoreThroughLValue(RValue::get(ArrayStart), Start);
357 if (Field == Record->field_end()) {
358 CGF.ErrorUnsupported(E, "weird std::initializer_list");
362 llvm::Value *Size = Builder.getInt(ArrayType->getSize());
363 LValue EndOrLength = CGF.EmitLValueForFieldInitialization(DestLV, *Field);
364 if (Field->getType()->isPointerType() &&
365 Ctx.hasSameType(Field->getType()->getPointeeType(),
366 ArrayType->getElementType())) {
368 llvm::Value *IdxEnd[] = { Zero, Size };
369 llvm::Value *ArrayEnd =
370 Builder.CreateInBoundsGEP(ArrayPtr, IdxEnd, "arrayend");
371 CGF.EmitStoreThroughLValue(RValue::get(ArrayEnd), EndOrLength);
372 } else if (Ctx.hasSameType(Field->getType(), Ctx.getSizeType())) {
374 CGF.EmitStoreThroughLValue(RValue::get(Size), EndOrLength);
376 CGF.ErrorUnsupported(E, "weird std::initializer_list");
381 /// \brief Determine if E is a trivial array filler, that is, one that is
382 /// equivalent to zero-initialization.
383 static bool isTrivialFiller(Expr *E) {
387 if (isa<ImplicitValueInitExpr>(E))
390 if (auto *ILE = dyn_cast<InitListExpr>(E)) {
391 if (ILE->getNumInits())
393 return isTrivialFiller(ILE->getArrayFiller());
396 if (auto *Cons = dyn_cast_or_null<CXXConstructExpr>(E))
397 return Cons->getConstructor()->isDefaultConstructor() &&
398 Cons->getConstructor()->isTrivial();
400 // FIXME: Are there other cases where we can avoid emitting an initializer?
404 /// \brief Emit initialization of an array from an initializer list.
405 void AggExprEmitter::EmitArrayInit(llvm::Value *DestPtr, llvm::ArrayType *AType,
406 QualType elementType, InitListExpr *E) {
407 uint64_t NumInitElements = E->getNumInits();
409 uint64_t NumArrayElements = AType->getNumElements();
410 assert(NumInitElements <= NumArrayElements);
412 // DestPtr is an array*. Construct an elementType* by drilling
414 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
415 llvm::Value *indices[] = { zero, zero };
417 Builder.CreateInBoundsGEP(DestPtr, indices, "arrayinit.begin");
419 // Exception safety requires us to destroy all the
420 // already-constructed members if an initializer throws.
421 // For that, we'll need an EH cleanup.
422 QualType::DestructionKind dtorKind = elementType.isDestructedType();
423 llvm::AllocaInst *endOfInit = nullptr;
424 EHScopeStack::stable_iterator cleanup;
425 llvm::Instruction *cleanupDominator = nullptr;
426 if (CGF.needsEHCleanup(dtorKind)) {
427 // In principle we could tell the cleanup where we are more
428 // directly, but the control flow can get so varied here that it
429 // would actually be quite complex. Therefore we go through an
431 endOfInit = CGF.CreateTempAlloca(begin->getType(),
432 "arrayinit.endOfInit");
433 cleanupDominator = Builder.CreateStore(begin, endOfInit);
434 CGF.pushIrregularPartialArrayCleanup(begin, endOfInit, elementType,
435 CGF.getDestroyer(dtorKind));
436 cleanup = CGF.EHStack.stable_begin();
438 // Otherwise, remember that we didn't need a cleanup.
440 dtorKind = QualType::DK_none;
443 llvm::Value *one = llvm::ConstantInt::get(CGF.SizeTy, 1);
445 // The 'current element to initialize'. The invariants on this
446 // variable are complicated. Essentially, after each iteration of
447 // the loop, it points to the last initialized element, except
448 // that it points to the beginning of the array before any
449 // elements have been initialized.
450 llvm::Value *element = begin;
452 // Emit the explicit initializers.
453 for (uint64_t i = 0; i != NumInitElements; ++i) {
454 // Advance to the next element.
456 element = Builder.CreateInBoundsGEP(element, one, "arrayinit.element");
458 // Tell the cleanup that it needs to destroy up to this
459 // element. TODO: some of these stores can be trivially
460 // observed to be unnecessary.
461 if (endOfInit) Builder.CreateStore(element, endOfInit);
464 LValue elementLV = CGF.MakeAddrLValue(element, elementType);
465 EmitInitializationToLValue(E->getInit(i), elementLV);
468 // Check whether there's a non-trivial array-fill expression.
469 Expr *filler = E->getArrayFiller();
470 bool hasTrivialFiller = isTrivialFiller(filler);
472 // Any remaining elements need to be zero-initialized, possibly
473 // using the filler expression. We can skip this if the we're
474 // emitting to zeroed memory.
475 if (NumInitElements != NumArrayElements &&
476 !(Dest.isZeroed() && hasTrivialFiller &&
477 CGF.getTypes().isZeroInitializable(elementType))) {
479 // Use an actual loop. This is basically
480 // do { *array++ = filler; } while (array != end);
482 // Advance to the start of the rest of the array.
483 if (NumInitElements) {
484 element = Builder.CreateInBoundsGEP(element, one, "arrayinit.start");
485 if (endOfInit) Builder.CreateStore(element, endOfInit);
488 // Compute the end of the array.
489 llvm::Value *end = Builder.CreateInBoundsGEP(begin,
490 llvm::ConstantInt::get(CGF.SizeTy, NumArrayElements),
493 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
494 llvm::BasicBlock *bodyBB = CGF.createBasicBlock("arrayinit.body");
496 // Jump into the body.
497 CGF.EmitBlock(bodyBB);
498 llvm::PHINode *currentElement =
499 Builder.CreatePHI(element->getType(), 2, "arrayinit.cur");
500 currentElement->addIncoming(element, entryBB);
502 // Emit the actual filler expression.
503 LValue elementLV = CGF.MakeAddrLValue(currentElement, elementType);
505 EmitInitializationToLValue(filler, elementLV);
507 EmitNullInitializationToLValue(elementLV);
509 // Move on to the next element.
510 llvm::Value *nextElement =
511 Builder.CreateInBoundsGEP(currentElement, one, "arrayinit.next");
513 // Tell the EH cleanup that we finished with the last element.
514 if (endOfInit) Builder.CreateStore(nextElement, endOfInit);
516 // Leave the loop if we're done.
517 llvm::Value *done = Builder.CreateICmpEQ(nextElement, end,
519 llvm::BasicBlock *endBB = CGF.createBasicBlock("arrayinit.end");
520 Builder.CreateCondBr(done, endBB, bodyBB);
521 currentElement->addIncoming(nextElement, Builder.GetInsertBlock());
523 CGF.EmitBlock(endBB);
526 // Leave the partial-array cleanup if we entered one.
527 if (dtorKind) CGF.DeactivateCleanupBlock(cleanup, cleanupDominator);
530 //===----------------------------------------------------------------------===//
532 //===----------------------------------------------------------------------===//
534 void AggExprEmitter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E){
535 Visit(E->GetTemporaryExpr());
538 void AggExprEmitter::VisitOpaqueValueExpr(OpaqueValueExpr *e) {
539 EmitFinalDestCopy(e->getType(), CGF.getOpaqueLValueMapping(e));
543 AggExprEmitter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
544 if (Dest.isPotentiallyAliased() &&
545 E->getType().isPODType(CGF.getContext())) {
546 // For a POD type, just emit a load of the lvalue + a copy, because our
547 // compound literal might alias the destination.
548 EmitAggLoadOfLValue(E);
552 AggValueSlot Slot = EnsureSlot(E->getType());
553 CGF.EmitAggExpr(E->getInitializer(), Slot);
556 /// Attempt to look through various unimportant expressions to find a
557 /// cast of the given kind.
558 static Expr *findPeephole(Expr *op, CastKind kind) {
560 op = op->IgnoreParens();
561 if (CastExpr *castE = dyn_cast<CastExpr>(op)) {
562 if (castE->getCastKind() == kind)
563 return castE->getSubExpr();
564 if (castE->getCastKind() == CK_NoOp)
571 void AggExprEmitter::VisitCastExpr(CastExpr *E) {
572 switch (E->getCastKind()) {
574 // FIXME: Can this actually happen? We have no test coverage for it.
575 assert(isa<CXXDynamicCastExpr>(E) && "CK_Dynamic without a dynamic_cast?");
576 LValue LV = CGF.EmitCheckedLValue(E->getSubExpr(),
577 CodeGenFunction::TCK_Load);
578 // FIXME: Do we also need to handle property references here?
580 CGF.EmitDynamicCast(LV.getAddress(), cast<CXXDynamicCastExpr>(E));
582 CGF.CGM.ErrorUnsupported(E, "non-simple lvalue dynamic_cast");
584 if (!Dest.isIgnored())
585 CGF.CGM.ErrorUnsupported(E, "lvalue dynamic_cast with a destination");
590 // Evaluate even if the destination is ignored.
591 if (Dest.isIgnored()) {
592 CGF.EmitAnyExpr(E->getSubExpr(), AggValueSlot::ignored(),
593 /*ignoreResult=*/true);
597 // GCC union extension
598 QualType Ty = E->getSubExpr()->getType();
599 QualType PtrTy = CGF.getContext().getPointerType(Ty);
600 llvm::Value *CastPtr = Builder.CreateBitCast(Dest.getAddr(),
601 CGF.ConvertType(PtrTy));
602 EmitInitializationToLValue(E->getSubExpr(),
603 CGF.MakeAddrLValue(CastPtr, Ty));
607 case CK_DerivedToBase:
608 case CK_BaseToDerived:
609 case CK_UncheckedDerivedToBase: {
610 llvm_unreachable("cannot perform hierarchy conversion in EmitAggExpr: "
611 "should have been unpacked before we got here");
614 case CK_NonAtomicToAtomic:
615 case CK_AtomicToNonAtomic: {
616 bool isToAtomic = (E->getCastKind() == CK_NonAtomicToAtomic);
618 // Determine the atomic and value types.
619 QualType atomicType = E->getSubExpr()->getType();
620 QualType valueType = E->getType();
621 if (isToAtomic) std::swap(atomicType, valueType);
623 assert(atomicType->isAtomicType());
624 assert(CGF.getContext().hasSameUnqualifiedType(valueType,
625 atomicType->castAs<AtomicType>()->getValueType()));
627 // Just recurse normally if we're ignoring the result or the
628 // atomic type doesn't change representation.
629 if (Dest.isIgnored() || !CGF.CGM.isPaddedAtomicType(atomicType)) {
630 return Visit(E->getSubExpr());
633 CastKind peepholeTarget =
634 (isToAtomic ? CK_AtomicToNonAtomic : CK_NonAtomicToAtomic);
636 // These two cases are reverses of each other; try to peephole them.
637 if (Expr *op = findPeephole(E->getSubExpr(), peepholeTarget)) {
638 assert(CGF.getContext().hasSameUnqualifiedType(op->getType(),
640 "peephole significantly changed types?");
644 // If we're converting an r-value of non-atomic type to an r-value
645 // of atomic type, just emit directly into the relevant sub-object.
647 AggValueSlot valueDest = Dest;
648 if (!valueDest.isIgnored() && CGF.CGM.isPaddedAtomicType(atomicType)) {
649 // Zero-initialize. (Strictly speaking, we only need to intialize
650 // the padding at the end, but this is simpler.)
651 if (!Dest.isZeroed())
652 CGF.EmitNullInitialization(Dest.getAddr(), atomicType);
654 // Build a GEP to refer to the subobject.
655 llvm::Value *valueAddr =
656 CGF.Builder.CreateStructGEP(nullptr, valueDest.getAddr(), 0);
657 valueDest = AggValueSlot::forAddr(valueAddr,
658 valueDest.getAlignment(),
659 valueDest.getQualifiers(),
660 valueDest.isExternallyDestructed(),
661 valueDest.requiresGCollection(),
662 valueDest.isPotentiallyAliased(),
663 AggValueSlot::IsZeroed);
666 CGF.EmitAggExpr(E->getSubExpr(), valueDest);
670 // Otherwise, we're converting an atomic type to a non-atomic type.
671 // Make an atomic temporary, emit into that, and then copy the value out.
672 AggValueSlot atomicSlot =
673 CGF.CreateAggTemp(atomicType, "atomic-to-nonatomic.temp");
674 CGF.EmitAggExpr(E->getSubExpr(), atomicSlot);
676 llvm::Value *valueAddr =
677 Builder.CreateStructGEP(nullptr, atomicSlot.getAddr(), 0);
678 RValue rvalue = RValue::getAggregate(valueAddr, atomicSlot.isVolatile());
679 return EmitFinalDestCopy(valueType, rvalue);
682 case CK_LValueToRValue:
683 // If we're loading from a volatile type, force the destination
685 if (E->getSubExpr()->getType().isVolatileQualified()) {
686 EnsureDest(E->getType());
687 return Visit(E->getSubExpr());
693 case CK_UserDefinedConversion:
694 case CK_ConstructorConversion:
695 assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(),
697 "Implicit cast types must be compatible");
698 Visit(E->getSubExpr());
701 case CK_LValueBitCast:
702 llvm_unreachable("should not be emitting lvalue bitcast as rvalue");
706 case CK_ArrayToPointerDecay:
707 case CK_FunctionToPointerDecay:
708 case CK_NullToPointer:
709 case CK_NullToMemberPointer:
710 case CK_BaseToDerivedMemberPointer:
711 case CK_DerivedToBaseMemberPointer:
712 case CK_MemberPointerToBoolean:
713 case CK_ReinterpretMemberPointer:
714 case CK_IntegralToPointer:
715 case CK_PointerToIntegral:
716 case CK_PointerToBoolean:
719 case CK_IntegralCast:
720 case CK_IntegralToBoolean:
721 case CK_IntegralToFloating:
722 case CK_FloatingToIntegral:
723 case CK_FloatingToBoolean:
724 case CK_FloatingCast:
725 case CK_CPointerToObjCPointerCast:
726 case CK_BlockPointerToObjCPointerCast:
727 case CK_AnyPointerToBlockPointerCast:
728 case CK_ObjCObjectLValueCast:
729 case CK_FloatingRealToComplex:
730 case CK_FloatingComplexToReal:
731 case CK_FloatingComplexToBoolean:
732 case CK_FloatingComplexCast:
733 case CK_FloatingComplexToIntegralComplex:
734 case CK_IntegralRealToComplex:
735 case CK_IntegralComplexToReal:
736 case CK_IntegralComplexToBoolean:
737 case CK_IntegralComplexCast:
738 case CK_IntegralComplexToFloatingComplex:
739 case CK_ARCProduceObject:
740 case CK_ARCConsumeObject:
741 case CK_ARCReclaimReturnedObject:
742 case CK_ARCExtendBlockObject:
743 case CK_CopyAndAutoreleaseBlockObject:
744 case CK_BuiltinFnToFnPtr:
745 case CK_ZeroToOCLEvent:
746 case CK_AddressSpaceConversion:
747 llvm_unreachable("cast kind invalid for aggregate types");
751 void AggExprEmitter::VisitCallExpr(const CallExpr *E) {
752 if (E->getCallReturnType(CGF.getContext())->isReferenceType()) {
753 EmitAggLoadOfLValue(E);
757 RValue RV = CGF.EmitCallExpr(E, getReturnValueSlot());
758 EmitMoveFromReturnSlot(E, RV);
761 void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
762 RValue RV = CGF.EmitObjCMessageExpr(E, getReturnValueSlot());
763 EmitMoveFromReturnSlot(E, RV);
766 void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {
767 CGF.EmitIgnoredExpr(E->getLHS());
771 void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
772 CodeGenFunction::StmtExprEvaluation eval(CGF);
773 CGF.EmitCompoundStmt(*E->getSubStmt(), true, Dest);
776 void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
777 if (E->getOpcode() == BO_PtrMemD || E->getOpcode() == BO_PtrMemI)
778 VisitPointerToDataMemberBinaryOperator(E);
780 CGF.ErrorUnsupported(E, "aggregate binary expression");
783 void AggExprEmitter::VisitPointerToDataMemberBinaryOperator(
784 const BinaryOperator *E) {
785 LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E);
786 EmitFinalDestCopy(E->getType(), LV);
789 /// Is the value of the given expression possibly a reference to or
790 /// into a __block variable?
791 static bool isBlockVarRef(const Expr *E) {
792 // Make sure we look through parens.
793 E = E->IgnoreParens();
795 // Check for a direct reference to a __block variable.
796 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
797 const VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
798 return (var && var->hasAttr<BlocksAttr>());
801 // More complicated stuff.
804 if (const BinaryOperator *op = dyn_cast<BinaryOperator>(E)) {
805 // For an assignment or pointer-to-member operation, just care
807 if (op->isAssignmentOp() || op->isPtrMemOp())
808 return isBlockVarRef(op->getLHS());
810 // For a comma, just care about the RHS.
811 if (op->getOpcode() == BO_Comma)
812 return isBlockVarRef(op->getRHS());
814 // FIXME: pointer arithmetic?
817 // Check both sides of a conditional operator.
818 } else if (const AbstractConditionalOperator *op
819 = dyn_cast<AbstractConditionalOperator>(E)) {
820 return isBlockVarRef(op->getTrueExpr())
821 || isBlockVarRef(op->getFalseExpr());
823 // OVEs are required to support BinaryConditionalOperators.
824 } else if (const OpaqueValueExpr *op
825 = dyn_cast<OpaqueValueExpr>(E)) {
826 if (const Expr *src = op->getSourceExpr())
827 return isBlockVarRef(src);
829 // Casts are necessary to get things like (*(int*)&var) = foo().
830 // We don't really care about the kind of cast here, except
831 // we don't want to look through l2r casts, because it's okay
832 // to get the *value* in a __block variable.
833 } else if (const CastExpr *cast = dyn_cast<CastExpr>(E)) {
834 if (cast->getCastKind() == CK_LValueToRValue)
836 return isBlockVarRef(cast->getSubExpr());
838 // Handle unary operators. Again, just aggressively look through
839 // it, ignoring the operation.
840 } else if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E)) {
841 return isBlockVarRef(uop->getSubExpr());
843 // Look into the base of a field access.
844 } else if (const MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
845 return isBlockVarRef(mem->getBase());
847 // Look into the base of a subscript.
848 } else if (const ArraySubscriptExpr *sub = dyn_cast<ArraySubscriptExpr>(E)) {
849 return isBlockVarRef(sub->getBase());
855 void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
856 // For an assignment to work, the value on the right has
857 // to be compatible with the value on the left.
858 assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
859 E->getRHS()->getType())
860 && "Invalid assignment");
862 // If the LHS might be a __block variable, and the RHS can
863 // potentially cause a block copy, we need to evaluate the RHS first
864 // so that the assignment goes the right place.
865 // This is pretty semantically fragile.
866 if (isBlockVarRef(E->getLHS()) &&
867 E->getRHS()->HasSideEffects(CGF.getContext())) {
868 // Ensure that we have a destination, and evaluate the RHS into that.
869 EnsureDest(E->getRHS()->getType());
872 // Now emit the LHS and copy into it.
873 LValue LHS = CGF.EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
875 // That copy is an atomic copy if the LHS is atomic.
876 if (LHS.getType()->isAtomicType() ||
877 CGF.LValueIsSuitableForInlineAtomic(LHS)) {
878 CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false);
882 EmitCopy(E->getLHS()->getType(),
883 AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed,
884 needsGC(E->getLHS()->getType()),
885 AggValueSlot::IsAliased),
890 LValue LHS = CGF.EmitLValue(E->getLHS());
892 // If we have an atomic type, evaluate into the destination and then
893 // do an atomic copy.
894 if (LHS.getType()->isAtomicType() ||
895 CGF.LValueIsSuitableForInlineAtomic(LHS)) {
896 EnsureDest(E->getRHS()->getType());
898 CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false);
902 // Codegen the RHS so that it stores directly into the LHS.
903 AggValueSlot LHSSlot =
904 AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed,
905 needsGC(E->getLHS()->getType()),
906 AggValueSlot::IsAliased);
907 // A non-volatile aggregate destination might have volatile member.
908 if (!LHSSlot.isVolatile() &&
909 CGF.hasVolatileMember(E->getLHS()->getType()))
910 LHSSlot.setVolatile(true);
912 CGF.EmitAggExpr(E->getRHS(), LHSSlot);
914 // Copy into the destination if the assignment isn't ignored.
915 EmitFinalDestCopy(E->getType(), LHS);
918 void AggExprEmitter::
919 VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
920 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
921 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
922 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
924 // Bind the common expression if necessary.
925 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
927 CodeGenFunction::ConditionalEvaluation eval(CGF);
928 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock,
929 CGF.getProfileCount(E));
931 // Save whether the destination's lifetime is externally managed.
932 bool isExternallyDestructed = Dest.isExternallyDestructed();
935 CGF.EmitBlock(LHSBlock);
936 CGF.incrementProfileCounter(E);
937 Visit(E->getTrueExpr());
940 assert(CGF.HaveInsertPoint() && "expression evaluation ended with no IP!");
941 CGF.Builder.CreateBr(ContBlock);
943 // If the result of an agg expression is unused, then the emission
944 // of the LHS might need to create a destination slot. That's fine
945 // with us, and we can safely emit the RHS into the same slot, but
946 // we shouldn't claim that it's already being destructed.
947 Dest.setExternallyDestructed(isExternallyDestructed);
950 CGF.EmitBlock(RHSBlock);
951 Visit(E->getFalseExpr());
954 CGF.EmitBlock(ContBlock);
957 void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) {
958 Visit(CE->getChosenSubExpr());
961 void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
962 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
963 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
966 // If EmitVAArg fails, we fall back to the LLVM instruction.
968 Builder.CreateVAArg(ArgValue, CGF.ConvertType(VE->getType()));
969 if (!Dest.isIgnored())
970 Builder.CreateStore(Val, Dest.getAddr());
974 EmitFinalDestCopy(VE->getType(), CGF.MakeAddrLValue(ArgPtr, VE->getType()));
977 void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
978 // Ensure that we have a slot, but if we already do, remember
979 // whether it was externally destructed.
980 bool wasExternallyDestructed = Dest.isExternallyDestructed();
981 EnsureDest(E->getType());
983 // We're going to push a destructor if there isn't already one.
984 Dest.setExternallyDestructed();
986 Visit(E->getSubExpr());
988 // Push that destructor we promised.
989 if (!wasExternallyDestructed)
990 CGF.EmitCXXTemporary(E->getTemporary(), E->getType(), Dest.getAddr());
994 AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) {
995 AggValueSlot Slot = EnsureSlot(E->getType());
996 CGF.EmitCXXConstructExpr(E, Slot);
1000 AggExprEmitter::VisitLambdaExpr(LambdaExpr *E) {
1001 AggValueSlot Slot = EnsureSlot(E->getType());
1002 CGF.EmitLambdaExpr(E, Slot);
1005 void AggExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
1006 CGF.enterFullExpression(E);
1007 CodeGenFunction::RunCleanupsScope cleanups(CGF);
1008 Visit(E->getSubExpr());
1011 void AggExprEmitter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1012 QualType T = E->getType();
1013 AggValueSlot Slot = EnsureSlot(T);
1014 EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T));
1017 void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
1018 QualType T = E->getType();
1019 AggValueSlot Slot = EnsureSlot(T);
1020 EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T));
1023 /// isSimpleZero - If emitting this value will obviously just cause a store of
1024 /// zero to memory, return true. This can return false if uncertain, so it just
1025 /// handles simple cases.
1026 static bool isSimpleZero(const Expr *E, CodeGenFunction &CGF) {
1027 E = E->IgnoreParens();
1030 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E))
1031 return IL->getValue() == 0;
1033 if (const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(E))
1034 return FL->getValue().isPosZero();
1036 if ((isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) &&
1037 CGF.getTypes().isZeroInitializable(E->getType()))
1039 // (int*)0 - Null pointer expressions.
1040 if (const CastExpr *ICE = dyn_cast<CastExpr>(E))
1041 return ICE->getCastKind() == CK_NullToPointer;
1043 if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E))
1044 return CL->getValue() == 0;
1046 // Otherwise, hard case: conservatively return false.
1052 AggExprEmitter::EmitInitializationToLValue(Expr *E, LValue LV) {
1053 QualType type = LV.getType();
1054 // FIXME: Ignore result?
1055 // FIXME: Are initializers affected by volatile?
1056 if (Dest.isZeroed() && isSimpleZero(E, CGF)) {
1057 // Storing "i32 0" to a zero'd memory location is a noop.
1059 } else if (isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) {
1060 return EmitNullInitializationToLValue(LV);
1061 } else if (isa<NoInitExpr>(E)) {
1064 } else if (type->isReferenceType()) {
1065 RValue RV = CGF.EmitReferenceBindingToExpr(E);
1066 return CGF.EmitStoreThroughLValue(RV, LV);
1069 switch (CGF.getEvaluationKind(type)) {
1071 CGF.EmitComplexExprIntoLValue(E, LV, /*isInit*/ true);
1074 CGF.EmitAggExpr(E, AggValueSlot::forLValue(LV,
1075 AggValueSlot::IsDestructed,
1076 AggValueSlot::DoesNotNeedGCBarriers,
1077 AggValueSlot::IsNotAliased,
1081 if (LV.isSimple()) {
1082 CGF.EmitScalarInit(E, /*D=*/nullptr, LV, /*Captured=*/false);
1084 CGF.EmitStoreThroughLValue(RValue::get(CGF.EmitScalarExpr(E)), LV);
1088 llvm_unreachable("bad evaluation kind");
1091 void AggExprEmitter::EmitNullInitializationToLValue(LValue lv) {
1092 QualType type = lv.getType();
1094 // If the destination slot is already zeroed out before the aggregate is
1095 // copied into it, we don't have to emit any zeros here.
1096 if (Dest.isZeroed() && CGF.getTypes().isZeroInitializable(type))
1099 if (CGF.hasScalarEvaluationKind(type)) {
1100 // For non-aggregates, we can store the appropriate null constant.
1101 llvm::Value *null = CGF.CGM.EmitNullConstant(type);
1102 // Note that the following is not equivalent to
1103 // EmitStoreThroughBitfieldLValue for ARC types.
1104 if (lv.isBitField()) {
1105 CGF.EmitStoreThroughBitfieldLValue(RValue::get(null), lv);
1107 assert(lv.isSimple());
1108 CGF.EmitStoreOfScalar(null, lv, /* isInitialization */ true);
1111 // There's a potential optimization opportunity in combining
1112 // memsets; that would be easy for arrays, but relatively
1113 // difficult for structures with the current code.
1114 CGF.EmitNullInitialization(lv.getAddress(), lv.getType());
1118 void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
1120 // FIXME: Assess perf here? Figure out what cases are worth optimizing here
1121 // (Length of globals? Chunks of zeroed-out space?).
1123 // If we can, prefer a copy from a global; this is a lot less code for long
1124 // globals, and it's easier for the current optimizers to analyze.
1125 if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) {
1126 llvm::GlobalVariable* GV =
1127 new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true,
1128 llvm::GlobalValue::InternalLinkage, C, "");
1129 EmitFinalDestCopy(E->getType(), CGF.MakeAddrLValue(GV, E->getType()));
1133 if (E->hadArrayRangeDesignator())
1134 CGF.ErrorUnsupported(E, "GNU array range designator extension");
1136 AggValueSlot Dest = EnsureSlot(E->getType());
1138 LValue DestLV = CGF.MakeAddrLValue(Dest.getAddr(), E->getType(),
1139 Dest.getAlignment());
1141 // Handle initialization of an array.
1142 if (E->getType()->isArrayType()) {
1143 if (E->isStringLiteralInit())
1144 return Visit(E->getInit(0));
1146 QualType elementType =
1147 CGF.getContext().getAsArrayType(E->getType())->getElementType();
1149 llvm::PointerType *APType =
1150 cast<llvm::PointerType>(Dest.getAddr()->getType());
1151 llvm::ArrayType *AType =
1152 cast<llvm::ArrayType>(APType->getElementType());
1154 EmitArrayInit(Dest.getAddr(), AType, elementType, E);
1158 if (E->getType()->isAtomicType()) {
1159 // An _Atomic(T) object can be list-initialized from an expression
1160 // of the same type.
1161 assert(E->getNumInits() == 1 &&
1162 CGF.getContext().hasSameUnqualifiedType(E->getInit(0)->getType(),
1164 "unexpected list initialization for atomic object");
1165 return Visit(E->getInit(0));
1168 assert(E->getType()->isRecordType() && "Only support structs/unions here!");
1170 // Do struct initialization; this code just sets each individual member
1171 // to the approprate value. This makes bitfield support automatic;
1172 // the disadvantage is that the generated code is more difficult for
1173 // the optimizer, especially with bitfields.
1174 unsigned NumInitElements = E->getNumInits();
1175 RecordDecl *record = E->getType()->castAs<RecordType>()->getDecl();
1177 // Prepare a 'this' for CXXDefaultInitExprs.
1178 CodeGenFunction::FieldConstructionScope FCS(CGF, Dest.getAddr());
1180 if (record->isUnion()) {
1181 // Only initialize one field of a union. The field itself is
1182 // specified by the initializer list.
1183 if (!E->getInitializedFieldInUnion()) {
1184 // Empty union; we have nothing to do.
1187 // Make sure that it's really an empty and not a failure of
1188 // semantic analysis.
1189 for (const auto *Field : record->fields())
1190 assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed");
1195 // FIXME: volatility
1196 FieldDecl *Field = E->getInitializedFieldInUnion();
1198 LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestLV, Field);
1199 if (NumInitElements) {
1200 // Store the initializer into the field
1201 EmitInitializationToLValue(E->getInit(0), FieldLoc);
1203 // Default-initialize to null.
1204 EmitNullInitializationToLValue(FieldLoc);
1210 // We'll need to enter cleanup scopes in case any of the member
1211 // initializers throw an exception.
1212 SmallVector<EHScopeStack::stable_iterator, 16> cleanups;
1213 llvm::Instruction *cleanupDominator = nullptr;
1215 // Here we iterate over the fields; this makes it simpler to both
1216 // default-initialize fields and skip over unnamed fields.
1217 unsigned curInitIndex = 0;
1218 for (const auto *field : record->fields()) {
1219 // We're done once we hit the flexible array member.
1220 if (field->getType()->isIncompleteArrayType())
1223 // Always skip anonymous bitfields.
1224 if (field->isUnnamedBitfield())
1227 // We're done if we reach the end of the explicit initializers, we
1228 // have a zeroed object, and the rest of the fields are
1229 // zero-initializable.
1230 if (curInitIndex == NumInitElements && Dest.isZeroed() &&
1231 CGF.getTypes().isZeroInitializable(E->getType()))
1235 LValue LV = CGF.EmitLValueForFieldInitialization(DestLV, field);
1236 // We never generate write-barries for initialized fields.
1239 if (curInitIndex < NumInitElements) {
1240 // Store the initializer into the field.
1241 EmitInitializationToLValue(E->getInit(curInitIndex++), LV);
1243 // We're out of initalizers; default-initialize to null
1244 EmitNullInitializationToLValue(LV);
1247 // Push a destructor if necessary.
1248 // FIXME: if we have an array of structures, all explicitly
1249 // initialized, we can end up pushing a linear number of cleanups.
1250 bool pushedCleanup = false;
1251 if (QualType::DestructionKind dtorKind
1252 = field->getType().isDestructedType()) {
1253 assert(LV.isSimple());
1254 if (CGF.needsEHCleanup(dtorKind)) {
1255 if (!cleanupDominator)
1256 cleanupDominator = CGF.Builder.CreateUnreachable(); // placeholder
1258 CGF.pushDestroy(EHCleanup, LV.getAddress(), field->getType(),
1259 CGF.getDestroyer(dtorKind), false);
1260 cleanups.push_back(CGF.EHStack.stable_begin());
1261 pushedCleanup = true;
1265 // If the GEP didn't get used because of a dead zero init or something
1266 // else, clean it up for -O0 builds and general tidiness.
1267 if (!pushedCleanup && LV.isSimple())
1268 if (llvm::GetElementPtrInst *GEP =
1269 dyn_cast<llvm::GetElementPtrInst>(LV.getAddress()))
1270 if (GEP->use_empty())
1271 GEP->eraseFromParent();
1274 // Deactivate all the partial cleanups in reverse order, which
1275 // generally means popping them.
1276 for (unsigned i = cleanups.size(); i != 0; --i)
1277 CGF.DeactivateCleanupBlock(cleanups[i-1], cleanupDominator);
1279 // Destroy the placeholder if we made one.
1280 if (cleanupDominator)
1281 cleanupDominator->eraseFromParent();
1284 void AggExprEmitter::VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E) {
1285 AggValueSlot Dest = EnsureSlot(E->getType());
1287 LValue DestLV = CGF.MakeAddrLValue(Dest.getAddr(), E->getType(),
1288 Dest.getAlignment());
1289 EmitInitializationToLValue(E->getBase(), DestLV);
1290 VisitInitListExpr(E->getUpdater());
1293 //===----------------------------------------------------------------------===//
1294 // Entry Points into this File
1295 //===----------------------------------------------------------------------===//
1297 /// GetNumNonZeroBytesInInit - Get an approximate count of the number of
1298 /// non-zero bytes that will be stored when outputting the initializer for the
1299 /// specified initializer expression.
1300 static CharUnits GetNumNonZeroBytesInInit(const Expr *E, CodeGenFunction &CGF) {
1301 E = E->IgnoreParens();
1303 // 0 and 0.0 won't require any non-zero stores!
1304 if (isSimpleZero(E, CGF)) return CharUnits::Zero();
1306 // If this is an initlist expr, sum up the size of sizes of the (present)
1307 // elements. If this is something weird, assume the whole thing is non-zero.
1308 const InitListExpr *ILE = dyn_cast<InitListExpr>(E);
1309 if (!ILE || !CGF.getTypes().isZeroInitializable(ILE->getType()))
1310 return CGF.getContext().getTypeSizeInChars(E->getType());
1312 // InitListExprs for structs have to be handled carefully. If there are
1313 // reference members, we need to consider the size of the reference, not the
1314 // referencee. InitListExprs for unions and arrays can't have references.
1315 if (const RecordType *RT = E->getType()->getAs<RecordType>()) {
1316 if (!RT->isUnionType()) {
1317 RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl();
1318 CharUnits NumNonZeroBytes = CharUnits::Zero();
1320 unsigned ILEElement = 0;
1321 for (const auto *Field : SD->fields()) {
1322 // We're done once we hit the flexible array member or run out of
1323 // InitListExpr elements.
1324 if (Field->getType()->isIncompleteArrayType() ||
1325 ILEElement == ILE->getNumInits())
1327 if (Field->isUnnamedBitfield())
1330 const Expr *E = ILE->getInit(ILEElement++);
1332 // Reference values are always non-null and have the width of a pointer.
1333 if (Field->getType()->isReferenceType())
1334 NumNonZeroBytes += CGF.getContext().toCharUnitsFromBits(
1335 CGF.getTarget().getPointerWidth(0));
1337 NumNonZeroBytes += GetNumNonZeroBytesInInit(E, CGF);
1340 return NumNonZeroBytes;
1345 CharUnits NumNonZeroBytes = CharUnits::Zero();
1346 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
1347 NumNonZeroBytes += GetNumNonZeroBytesInInit(ILE->getInit(i), CGF);
1348 return NumNonZeroBytes;
1351 /// CheckAggExprForMemSetUse - If the initializer is large and has a lot of
1352 /// zeros in it, emit a memset and avoid storing the individual zeros.
1354 static void CheckAggExprForMemSetUse(AggValueSlot &Slot, const Expr *E,
1355 CodeGenFunction &CGF) {
1356 // If the slot is already known to be zeroed, nothing to do. Don't mess with
1358 if (Slot.isZeroed() || Slot.isVolatile() || Slot.getAddr() == nullptr)
1361 // C++ objects with a user-declared constructor don't need zero'ing.
1362 if (CGF.getLangOpts().CPlusPlus)
1363 if (const RecordType *RT = CGF.getContext()
1364 .getBaseElementType(E->getType())->getAs<RecordType>()) {
1365 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1366 if (RD->hasUserDeclaredConstructor())
1370 // If the type is 16-bytes or smaller, prefer individual stores over memset.
1371 std::pair<CharUnits, CharUnits> TypeInfo =
1372 CGF.getContext().getTypeInfoInChars(E->getType());
1373 if (TypeInfo.first <= CharUnits::fromQuantity(16))
1376 // Check to see if over 3/4 of the initializer are known to be zero. If so,
1377 // we prefer to emit memset + individual stores for the rest.
1378 CharUnits NumNonZeroBytes = GetNumNonZeroBytesInInit(E, CGF);
1379 if (NumNonZeroBytes*4 > TypeInfo.first)
1382 // Okay, it seems like a good idea to use an initial memset, emit the call.
1383 llvm::Constant *SizeVal = CGF.Builder.getInt64(TypeInfo.first.getQuantity());
1384 CharUnits Align = TypeInfo.second;
1386 llvm::Value *Loc = Slot.getAddr();
1388 Loc = CGF.Builder.CreateBitCast(Loc, CGF.Int8PtrTy);
1389 CGF.Builder.CreateMemSet(Loc, CGF.Builder.getInt8(0), SizeVal,
1390 Align.getQuantity(), false);
1392 // Tell the AggExprEmitter that the slot is known zero.
1399 /// EmitAggExpr - Emit the computation of the specified expression of aggregate
1400 /// type. The result is computed into DestPtr. Note that if DestPtr is null,
1401 /// the value of the aggregate expression is not needed. If VolatileDest is
1402 /// true, DestPtr cannot be 0.
1403 void CodeGenFunction::EmitAggExpr(const Expr *E, AggValueSlot Slot) {
1404 assert(E && hasAggregateEvaluationKind(E->getType()) &&
1405 "Invalid aggregate expression to emit");
1406 assert((Slot.getAddr() != nullptr || Slot.isIgnored()) &&
1407 "slot has bits but no address");
1409 // Optimize the slot if possible.
1410 CheckAggExprForMemSetUse(Slot, E, *this);
1412 AggExprEmitter(*this, Slot, Slot.isIgnored()).Visit(const_cast<Expr*>(E));
1415 LValue CodeGenFunction::EmitAggExprToLValue(const Expr *E) {
1416 assert(hasAggregateEvaluationKind(E->getType()) && "Invalid argument!");
1417 llvm::Value *Temp = CreateMemTemp(E->getType());
1418 LValue LV = MakeAddrLValue(Temp, E->getType());
1419 EmitAggExpr(E, AggValueSlot::forLValue(LV, AggValueSlot::IsNotDestructed,
1420 AggValueSlot::DoesNotNeedGCBarriers,
1421 AggValueSlot::IsNotAliased));
1425 void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr,
1426 llvm::Value *SrcPtr, QualType Ty,
1428 CharUnits alignment,
1429 bool isAssignment) {
1430 assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
1432 if (getLangOpts().CPlusPlus) {
1433 if (const RecordType *RT = Ty->getAs<RecordType>()) {
1434 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
1435 assert((Record->hasTrivialCopyConstructor() ||
1436 Record->hasTrivialCopyAssignment() ||
1437 Record->hasTrivialMoveConstructor() ||
1438 Record->hasTrivialMoveAssignment() ||
1439 Record->isUnion()) &&
1440 "Trying to aggregate-copy a type without a trivial copy/move "
1441 "constructor or assignment operator");
1442 // Ignore empty classes in C++.
1443 if (Record->isEmpty())
1448 // Aggregate assignment turns into llvm.memcpy. This is almost valid per
1449 // C99 6.5.16.1p3, which states "If the value being stored in an object is
1450 // read from another object that overlaps in anyway the storage of the first
1451 // object, then the overlap shall be exact and the two objects shall have
1452 // qualified or unqualified versions of a compatible type."
1454 // memcpy is not defined if the source and destination pointers are exactly
1455 // equal, but other compilers do this optimization, and almost every memcpy
1456 // implementation handles this case safely. If there is a libc that does not
1457 // safely handle this, we can add a target hook.
1459 // Get data size and alignment info for this aggregate. If this is an
1460 // assignment don't copy the tail padding. Otherwise copying it is fine.
1461 std::pair<CharUnits, CharUnits> TypeInfo;
1463 TypeInfo = getContext().getTypeInfoDataSizeInChars(Ty);
1465 TypeInfo = getContext().getTypeInfoInChars(Ty);
1467 if (alignment.isZero())
1468 alignment = TypeInfo.second;
1470 llvm::Value *SizeVal = nullptr;
1471 if (TypeInfo.first.isZero()) {
1472 // But note that getTypeInfo returns 0 for a VLA.
1473 if (auto *VAT = dyn_cast_or_null<VariableArrayType>(
1474 getContext().getAsArrayType(Ty))) {
1476 SizeVal = emitArrayLength(VAT, BaseEltTy, DestPtr);
1477 TypeInfo = getContext().getTypeInfoDataSizeInChars(BaseEltTy);
1478 std::pair<CharUnits, CharUnits> LastElementTypeInfo;
1480 LastElementTypeInfo = getContext().getTypeInfoInChars(BaseEltTy);
1481 assert(!TypeInfo.first.isZero());
1482 SizeVal = Builder.CreateNUWMul(
1484 llvm::ConstantInt::get(SizeTy, TypeInfo.first.getQuantity()));
1485 if (!isAssignment) {
1486 SizeVal = Builder.CreateNUWSub(
1488 llvm::ConstantInt::get(SizeTy, TypeInfo.first.getQuantity()));
1489 SizeVal = Builder.CreateNUWAdd(
1490 SizeVal, llvm::ConstantInt::get(
1491 SizeTy, LastElementTypeInfo.first.getQuantity()));
1496 SizeVal = llvm::ConstantInt::get(SizeTy, TypeInfo.first.getQuantity());
1499 // FIXME: If we have a volatile struct, the optimizer can remove what might
1500 // appear to be `extra' memory ops:
1502 // volatile struct { int i; } a, b;
1509 // we need to use a different call here. We use isVolatile to indicate when
1510 // either the source or the destination is volatile.
1512 llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType());
1514 llvm::Type::getInt8PtrTy(getLLVMContext(), DPT->getAddressSpace());
1515 DestPtr = Builder.CreateBitCast(DestPtr, DBP);
1517 llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType());
1519 llvm::Type::getInt8PtrTy(getLLVMContext(), SPT->getAddressSpace());
1520 SrcPtr = Builder.CreateBitCast(SrcPtr, SBP);
1522 // Don't do any of the memmove_collectable tests if GC isn't set.
1523 if (CGM.getLangOpts().getGC() == LangOptions::NonGC) {
1525 } else if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
1526 RecordDecl *Record = RecordTy->getDecl();
1527 if (Record->hasObjectMember()) {
1528 CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
1532 } else if (Ty->isArrayType()) {
1533 QualType BaseType = getContext().getBaseElementType(Ty);
1534 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
1535 if (RecordTy->getDecl()->hasObjectMember()) {
1536 CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
1543 // Determine the metadata to describe the position of any padding in this
1544 // memcpy, as well as the TBAA tags for the members of the struct, in case
1545 // the optimizer wishes to expand it in to scalar memory operations.
1546 llvm::MDNode *TBAAStructTag = CGM.getTBAAStructInfo(Ty);
1548 Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, alignment.getQuantity(),
1549 isVolatile, /*TBAATag=*/nullptr, TBAAStructTag);