1ec2b103cSEd Schouten //===--- CGExprAgg.cpp - Emit LLVM Code from Aggregate Expressions --------===//
2ec2b103cSEd Schouten //
322989816SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
422989816SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
522989816SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6ec2b103cSEd Schouten //
7ec2b103cSEd Schouten //===----------------------------------------------------------------------===//
8ec2b103cSEd Schouten //
9ec2b103cSEd Schouten // This contains code to emit Aggregate Expr nodes as LLVM code.
10ec2b103cSEd Schouten //
11ec2b103cSEd Schouten //===----------------------------------------------------------------------===//
12ec2b103cSEd Schouten
1348675466SDimitry Andric #include "CGCXXABI.h"
144c8b2481SRoman Divacky #include "CGObjCRuntime.h"
15706b4fc4SDimitry Andric #include "CodeGenFunction.h"
16809500fcSDimitry Andric #include "CodeGenModule.h"
1748675466SDimitry Andric #include "ConstantEmitter.h"
18ac9a064cSDimitry Andric #include "EHScopeStack.h"
19cfca06d7SDimitry Andric #include "TargetInfo.h"
20ec2b103cSEd Schouten #include "clang/AST/ASTContext.h"
21706b4fc4SDimitry Andric #include "clang/AST/Attr.h"
22ec2b103cSEd Schouten #include "clang/AST/DeclCXX.h"
23dbe13110SDimitry Andric #include "clang/AST/DeclTemplate.h"
24ec2b103cSEd Schouten #include "clang/AST/StmtVisitor.h"
25809500fcSDimitry Andric #include "llvm/IR/Constants.h"
26809500fcSDimitry Andric #include "llvm/IR/Function.h"
27809500fcSDimitry Andric #include "llvm/IR/GlobalVariable.h"
28ac9a064cSDimitry Andric #include "llvm/IR/Instruction.h"
2948675466SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
30706b4fc4SDimitry Andric #include "llvm/IR/Intrinsics.h"
31ec2b103cSEd Schouten using namespace clang;
32ec2b103cSEd Schouten using namespace CodeGen;
33ec2b103cSEd Schouten
34ec2b103cSEd Schouten //===----------------------------------------------------------------------===//
35ec2b103cSEd Schouten // Aggregate Expression Emitter
36ec2b103cSEd Schouten //===----------------------------------------------------------------------===//
37ec2b103cSEd Schouten
38ac9a064cSDimitry Andric namespace llvm {
39ac9a064cSDimitry Andric extern cl::opt<bool> EnableSingleByteCoverage;
40ac9a064cSDimitry Andric } // namespace llvm
41ac9a064cSDimitry Andric
42ec2b103cSEd Schouten namespace {
431569ce68SRoman Divacky class AggExprEmitter : public StmtVisitor<AggExprEmitter> {
44ec2b103cSEd Schouten CodeGenFunction &CGF;
45ec2b103cSEd Schouten CGBuilderTy &Builder;
46bca07a45SDimitry Andric AggValueSlot Dest;
47798321d8SDimitry Andric bool IsResultUnused;
48d7279c4cSRoman Divacky
EnsureSlot(QualType T)49bca07a45SDimitry Andric AggValueSlot EnsureSlot(QualType T) {
50bca07a45SDimitry Andric if (!Dest.isIgnored()) return Dest;
51bca07a45SDimitry Andric return CGF.CreateAggTemp(T, "agg.tmp.ensured");
52d7279c4cSRoman Divacky }
EnsureDest(QualType T)5356d91b49SDimitry Andric void EnsureDest(QualType T) {
5456d91b49SDimitry Andric if (!Dest.isIgnored()) return;
5556d91b49SDimitry Andric Dest = CGF.CreateAggTemp(T, "agg.tmp.ensured");
5656d91b49SDimitry Andric }
57d7279c4cSRoman Divacky
5848675466SDimitry Andric // Calls `Fn` with a valid return value slot, potentially creating a temporary
5948675466SDimitry Andric // to do so. If a temporary is created, an appropriate copy into `Dest` will
6048675466SDimitry Andric // be emitted, as will lifetime markers.
6148675466SDimitry Andric //
6248675466SDimitry Andric // The given function should take a ReturnValueSlot, and return an RValue that
6348675466SDimitry Andric // points to said slot.
6448675466SDimitry Andric void withReturnValueSlot(const Expr *E,
6548675466SDimitry Andric llvm::function_ref<RValue(ReturnValueSlot)> Fn);
6648675466SDimitry Andric
67ec2b103cSEd Schouten public:
AggExprEmitter(CodeGenFunction & cgf,AggValueSlot Dest,bool IsResultUnused)68798321d8SDimitry Andric AggExprEmitter(CodeGenFunction &cgf, AggValueSlot Dest, bool IsResultUnused)
69798321d8SDimitry Andric : CGF(cgf), Builder(CGF.Builder), Dest(Dest),
70798321d8SDimitry Andric IsResultUnused(IsResultUnused) { }
71ec2b103cSEd Schouten
72ec2b103cSEd Schouten //===--------------------------------------------------------------------===//
73ec2b103cSEd Schouten // Utilities
74ec2b103cSEd Schouten //===--------------------------------------------------------------------===//
75ec2b103cSEd Schouten
76ec2b103cSEd Schouten /// EmitAggLoadOfLValue - Given an expression with aggregate type that
77ec2b103cSEd Schouten /// represents a value lvalue, this method emits the address of the lvalue,
78ec2b103cSEd Schouten /// then loads the result into DestPtr.
79ec2b103cSEd Schouten void EmitAggLoadOfLValue(const Expr *E);
80ec2b103cSEd Schouten
81ec2b103cSEd Schouten /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
8248675466SDimitry Andric /// SrcIsRValue is true if source comes from an RValue.
8348675466SDimitry Andric void EmitFinalDestCopy(QualType type, const LValue &src,
84ac9a064cSDimitry Andric CodeGenFunction::ExprValueKind SrcValueKind =
85ac9a064cSDimitry Andric CodeGenFunction::EVK_NonRValue);
8645b53394SDimitry Andric void EmitFinalDestCopy(QualType type, RValue src);
8756d91b49SDimitry Andric void EmitCopy(QualType type, const AggValueSlot &dest,
8856d91b49SDimitry Andric const AggValueSlot &src);
89ec2b103cSEd Schouten
90e3b55780SDimitry Andric void EmitArrayInit(Address DestPtr, llvm::ArrayType *AType, QualType ArrayQTy,
91e3b55780SDimitry Andric Expr *ExprToVisit, ArrayRef<Expr *> Args,
92e3b55780SDimitry Andric Expr *ArrayFiller);
93dbe13110SDimitry Andric
needsGC(QualType T)9436981b17SDimitry Andric AggValueSlot::NeedsGCBarriers_t needsGC(QualType T) {
95dbe13110SDimitry Andric if (CGF.getLangOpts().getGC() && TypeRequiresGCollection(T))
9636981b17SDimitry Andric return AggValueSlot::NeedsGCBarriers;
9736981b17SDimitry Andric return AggValueSlot::DoesNotNeedGCBarriers;
9836981b17SDimitry Andric }
99d7279c4cSRoman Divacky
100d7279c4cSRoman Divacky bool TypeRequiresGCollection(QualType T);
101d7279c4cSRoman Divacky
102ec2b103cSEd Schouten //===--------------------------------------------------------------------===//
103ec2b103cSEd Schouten // Visitor Methods
104ec2b103cSEd Schouten //===--------------------------------------------------------------------===//
105ec2b103cSEd Schouten
Visit(Expr * E)1065e20cdd8SDimitry Andric void Visit(Expr *E) {
1075e20cdd8SDimitry Andric ApplyDebugLocation DL(CGF, E);
1085e20cdd8SDimitry Andric StmtVisitor<AggExprEmitter>::Visit(E);
1095e20cdd8SDimitry Andric }
1105e20cdd8SDimitry Andric
VisitStmt(Stmt * S)111ec2b103cSEd Schouten void VisitStmt(Stmt *S) {
112ec2b103cSEd Schouten CGF.ErrorUnsupported(S, "aggregate expression");
113ec2b103cSEd Schouten }
VisitParenExpr(ParenExpr * PE)114ec2b103cSEd Schouten void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); }
VisitGenericSelectionExpr(GenericSelectionExpr * GE)11501af97d3SDimitry Andric void VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
11601af97d3SDimitry Andric Visit(GE->getResultExpr());
11701af97d3SDimitry Andric }
VisitCoawaitExpr(CoawaitExpr * E)1187442d6faSDimitry Andric void VisitCoawaitExpr(CoawaitExpr *E) {
1197442d6faSDimitry Andric CGF.EmitCoawaitExpr(*E, Dest, IsResultUnused);
1207442d6faSDimitry Andric }
VisitCoyieldExpr(CoyieldExpr * E)1217442d6faSDimitry Andric void VisitCoyieldExpr(CoyieldExpr *E) {
1227442d6faSDimitry Andric CGF.EmitCoyieldExpr(*E, Dest, IsResultUnused);
1237442d6faSDimitry Andric }
VisitUnaryCoawait(UnaryOperator * E)1247442d6faSDimitry Andric void VisitUnaryCoawait(UnaryOperator *E) { Visit(E->getSubExpr()); }
VisitUnaryExtension(UnaryOperator * E)125ec2b103cSEd Schouten void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); }
VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr * E)126180abc3dSDimitry Andric void VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
127180abc3dSDimitry Andric return Visit(E->getReplacement());
128180abc3dSDimitry Andric }
129ec2b103cSEd Schouten
VisitConstantExpr(ConstantExpr * E)130676fbe81SDimitry Andric void VisitConstantExpr(ConstantExpr *E) {
131c0981da4SDimitry Andric EnsureDest(E->getType());
132c0981da4SDimitry Andric
133cfca06d7SDimitry Andric if (llvm::Value *Result = ConstantEmitter(CGF).tryEmitConstantExpr(E)) {
1341de139fdSDimitry Andric CGF.CreateCoercedStore(
1351de139fdSDimitry Andric Result, Dest.getAddress(),
1361de139fdSDimitry Andric llvm::TypeSize::getFixed(
1371de139fdSDimitry Andric Dest.getPreferredSize(CGF.getContext(), E->getType())
1381de139fdSDimitry Andric .getQuantity()),
139cfca06d7SDimitry Andric E->getType().isVolatileQualified());
140cfca06d7SDimitry Andric return;
141cfca06d7SDimitry Andric }
142676fbe81SDimitry Andric return Visit(E->getSubExpr());
143676fbe81SDimitry Andric }
144676fbe81SDimitry Andric
145ec2b103cSEd Schouten // l-values.
VisitDeclRefExpr(DeclRefExpr * E)146461a67faSDimitry Andric void VisitDeclRefExpr(DeclRefExpr *E) { EmitAggLoadOfLValue(E); }
VisitMemberExpr(MemberExpr * ME)147ec2b103cSEd Schouten void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); }
VisitUnaryDeref(UnaryOperator * E)148ec2b103cSEd Schouten void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); }
VisitStringLiteral(StringLiteral * E)149ec2b103cSEd Schouten void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); }
150180abc3dSDimitry Andric void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
VisitArraySubscriptExpr(ArraySubscriptExpr * E)151ec2b103cSEd Schouten void VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
152ec2b103cSEd Schouten EmitAggLoadOfLValue(E);
153ec2b103cSEd Schouten }
VisitPredefinedExpr(const PredefinedExpr * E)154ec2b103cSEd Schouten void VisitPredefinedExpr(const PredefinedExpr *E) {
155ec2b103cSEd Schouten EmitAggLoadOfLValue(E);
156ec2b103cSEd Schouten }
157ec2b103cSEd Schouten
158ec2b103cSEd Schouten // Operators.
1594c8b2481SRoman Divacky void VisitCastExpr(CastExpr *E);
160ec2b103cSEd Schouten void VisitCallExpr(const CallExpr *E);
161ec2b103cSEd Schouten void VisitStmtExpr(const StmtExpr *E);
162ec2b103cSEd Schouten void VisitBinaryOperator(const BinaryOperator *BO);
16373490b89SRoman Divacky void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO);
164ec2b103cSEd Schouten void VisitBinAssign(const BinaryOperator *E);
165ec2b103cSEd Schouten void VisitBinComma(const BinaryOperator *E);
16648675466SDimitry Andric void VisitBinCmp(const BinaryOperator *E);
VisitCXXRewrittenBinaryOperator(CXXRewrittenBinaryOperator * E)167519fc96cSDimitry Andric void VisitCXXRewrittenBinaryOperator(CXXRewrittenBinaryOperator *E) {
168519fc96cSDimitry Andric Visit(E->getSemanticForm());
169519fc96cSDimitry Andric }
170ec2b103cSEd Schouten
171ec2b103cSEd Schouten void VisitObjCMessageExpr(ObjCMessageExpr *E);
VisitObjCIvarRefExpr(ObjCIvarRefExpr * E)172ec2b103cSEd Schouten void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
173ec2b103cSEd Schouten EmitAggLoadOfLValue(E);
174ec2b103cSEd Schouten }
175ec2b103cSEd Schouten
1762e645aa5SDimitry Andric void VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E);
177bca07a45SDimitry Andric void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO);
1784c8b2481SRoman Divacky void VisitChooseExpr(const ChooseExpr *CE);
179ec2b103cSEd Schouten void VisitInitListExpr(InitListExpr *E);
180e3b55780SDimitry Andric void VisitCXXParenListOrInitListExpr(Expr *ExprToVisit, ArrayRef<Expr *> Args,
181e3b55780SDimitry Andric FieldDecl *InitializedFieldInUnion,
182e3b55780SDimitry Andric Expr *ArrayFiller);
183bab175ecSDimitry Andric void VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E,
184bab175ecSDimitry Andric llvm::Value *outerBegin = nullptr);
185abe15e55SRoman Divacky void VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
VisitNoInitExpr(NoInitExpr * E)1862e645aa5SDimitry Andric void VisitNoInitExpr(NoInitExpr *E) { } // Do nothing.
VisitCXXDefaultArgExpr(CXXDefaultArgExpr * DAE)187ec2b103cSEd Schouten void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
18822989816SDimitry Andric CodeGenFunction::CXXDefaultArgExprScope Scope(CGF, DAE);
189ec2b103cSEd Schouten Visit(DAE->getExpr());
190ec2b103cSEd Schouten }
VisitCXXDefaultInitExpr(CXXDefaultInitExpr * DIE)1916a037251SDimitry Andric void VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
19222989816SDimitry Andric CodeGenFunction::CXXDefaultInitExprScope Scope(CGF, DIE);
1936a037251SDimitry Andric Visit(DIE->getExpr());
1946a037251SDimitry Andric }
195ec2b103cSEd Schouten void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
196ec2b103cSEd Schouten void VisitCXXConstructExpr(const CXXConstructExpr *E);
1972b6b257fSDimitry Andric void VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
198dbe13110SDimitry Andric void VisitLambdaExpr(LambdaExpr *E);
199bfef3995SDimitry Andric void VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E);
200bca07a45SDimitry Andric void VisitExprWithCleanups(ExprWithCleanups *E);
2014ba67500SRoman Divacky void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
VisitCXXTypeidExpr(CXXTypeidExpr * E)202b3d5a323SRoman Divacky void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); }
203180abc3dSDimitry Andric void VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E);
204bca07a45SDimitry Andric void VisitOpaqueValueExpr(OpaqueValueExpr *E);
205bca07a45SDimitry Andric
VisitPseudoObjectExpr(PseudoObjectExpr * E)206dbe13110SDimitry Andric void VisitPseudoObjectExpr(PseudoObjectExpr *E) {
207dbe13110SDimitry Andric if (E->isGLValue()) {
208dbe13110SDimitry Andric LValue LV = CGF.EmitPseudoObjectLValue(E);
20956d91b49SDimitry Andric return EmitFinalDestCopy(E->getType(), LV);
210dbe13110SDimitry Andric }
211dbe13110SDimitry Andric
212e3b55780SDimitry Andric AggValueSlot Slot = EnsureSlot(E->getType());
213e3b55780SDimitry Andric bool NeedsDestruction =
214e3b55780SDimitry Andric !Slot.isExternallyDestructed() &&
215e3b55780SDimitry Andric E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct;
216e3b55780SDimitry Andric if (NeedsDestruction)
217e3b55780SDimitry Andric Slot.setExternallyDestructed();
218e3b55780SDimitry Andric CGF.EmitPseudoObjectRValue(E, Slot);
219e3b55780SDimitry Andric if (NeedsDestruction)
220e3b55780SDimitry Andric CGF.pushDestroy(QualType::DK_nontrivial_c_struct, Slot.getAddress(),
221e3b55780SDimitry Andric E->getType());
222dbe13110SDimitry Andric }
223dbe13110SDimitry Andric
224ec2b103cSEd Schouten void VisitVAArgExpr(VAArgExpr *E);
225e3b55780SDimitry Andric void VisitCXXParenListInitExpr(CXXParenListInitExpr *E);
226e3b55780SDimitry Andric void VisitCXXParenListOrInitListExpr(Expr *ExprToVisit, ArrayRef<Expr *> Args,
227e3b55780SDimitry Andric Expr *ArrayFiller);
228ec2b103cSEd Schouten
229180abc3dSDimitry Andric void EmitInitializationToLValue(Expr *E, LValue Address);
230180abc3dSDimitry Andric void EmitNullInitializationToLValue(LValue Address);
231ec2b103cSEd Schouten // case Expr::ChooseExprClass:
VisitCXXThrowExpr(const CXXThrowExpr * E)23234d02d0bSRoman Divacky void VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); }
VisitAtomicExpr(AtomicExpr * E)23336981b17SDimitry Andric void VisitAtomicExpr(AtomicExpr *E) {
23445b53394SDimitry Andric RValue Res = CGF.EmitAtomicExpr(E);
23545b53394SDimitry Andric EmitFinalDestCopy(E->getType(), Res);
23636981b17SDimitry Andric }
VisitPackIndexingExpr(PackIndexingExpr * E)237ac9a064cSDimitry Andric void VisitPackIndexingExpr(PackIndexingExpr *E) {
238ac9a064cSDimitry Andric Visit(E->getSelectedExpr());
239ac9a064cSDimitry Andric }
240ec2b103cSEd Schouten };
241ec2b103cSEd Schouten } // end anonymous namespace.
242ec2b103cSEd Schouten
243ec2b103cSEd Schouten //===----------------------------------------------------------------------===//
244ec2b103cSEd Schouten // Utilities
245ec2b103cSEd Schouten //===----------------------------------------------------------------------===//
246ec2b103cSEd Schouten
247ec2b103cSEd Schouten /// EmitAggLoadOfLValue - Given an expression with aggregate type that
248ec2b103cSEd Schouten /// represents a value lvalue, this method emits the address of the lvalue,
249ec2b103cSEd Schouten /// then loads the result into DestPtr.
EmitAggLoadOfLValue(const Expr * E)250ec2b103cSEd Schouten void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) {
251ec2b103cSEd Schouten LValue LV = CGF.EmitLValue(E);
252809500fcSDimitry Andric
253809500fcSDimitry Andric // If the type of the l-value is atomic, then do an atomic load.
2545e20cdd8SDimitry Andric if (LV.getType()->isAtomicType() || CGF.LValueIsSuitableForInlineAtomic(LV)) {
255bfef3995SDimitry Andric CGF.EmitAtomicLoad(LV, E->getExprLoc(), Dest);
256809500fcSDimitry Andric return;
257809500fcSDimitry Andric }
258809500fcSDimitry Andric
25956d91b49SDimitry Andric EmitFinalDestCopy(E->getType(), LV);
260ec2b103cSEd Schouten }
261ec2b103cSEd Schouten
26248675466SDimitry Andric /// True if the given aggregate type requires special GC API calls.
TypeRequiresGCollection(QualType T)263d7279c4cSRoman Divacky bool AggExprEmitter::TypeRequiresGCollection(QualType T) {
264d7279c4cSRoman Divacky // Only record types have members that might require garbage collection.
265d7279c4cSRoman Divacky const RecordType *RecordTy = T->getAs<RecordType>();
266d7279c4cSRoman Divacky if (!RecordTy) return false;
267d7279c4cSRoman Divacky
268d7279c4cSRoman Divacky // Don't mess with non-trivial C++ types.
269d7279c4cSRoman Divacky RecordDecl *Record = RecordTy->getDecl();
270d7279c4cSRoman Divacky if (isa<CXXRecordDecl>(Record) &&
271809500fcSDimitry Andric (cast<CXXRecordDecl>(Record)->hasNonTrivialCopyConstructor() ||
272d7279c4cSRoman Divacky !cast<CXXRecordDecl>(Record)->hasTrivialDestructor()))
273d7279c4cSRoman Divacky return false;
274d7279c4cSRoman Divacky
275d7279c4cSRoman Divacky // Check whether the type has an object member.
276d7279c4cSRoman Divacky return Record->hasObjectMember();
277d7279c4cSRoman Divacky }
278d7279c4cSRoman Divacky
withReturnValueSlot(const Expr * E,llvm::function_ref<RValue (ReturnValueSlot)> EmitCall)27948675466SDimitry Andric void AggExprEmitter::withReturnValueSlot(
28048675466SDimitry Andric const Expr *E, llvm::function_ref<RValue(ReturnValueSlot)> EmitCall) {
28148675466SDimitry Andric QualType RetTy = E->getType();
28248675466SDimitry Andric bool RequiresDestruction =
283cfca06d7SDimitry Andric !Dest.isExternallyDestructed() &&
28448675466SDimitry Andric RetTy.isDestructedType() == QualType::DK_nontrivial_c_struct;
28548675466SDimitry Andric
28648675466SDimitry Andric // If it makes no observable difference, save a memcpy + temporary.
28748675466SDimitry Andric //
28848675466SDimitry Andric // We need to always provide our own temporary if destruction is required.
28948675466SDimitry Andric // Otherwise, EmitCall will emit its own, notice that it's "unused", and end
29048675466SDimitry Andric // its lifetime before we have the chance to emit a proper destructor call.
29148675466SDimitry Andric bool UseTemp = Dest.isPotentiallyAliased() || Dest.requiresGCollection() ||
292ac9a064cSDimitry Andric (RequiresDestruction && Dest.isIgnored());
29348675466SDimitry Andric
29448675466SDimitry Andric Address RetAddr = Address::invalid();
295ac9a064cSDimitry Andric RawAddress RetAllocaAddr = RawAddress::invalid();
29648675466SDimitry Andric
29748675466SDimitry Andric EHScopeStack::stable_iterator LifetimeEndBlock;
29848675466SDimitry Andric llvm::Value *LifetimeSizePtr = nullptr;
29948675466SDimitry Andric llvm::IntrinsicInst *LifetimeStartInst = nullptr;
30048675466SDimitry Andric if (!UseTemp) {
30148675466SDimitry Andric RetAddr = Dest.getAddress();
30248675466SDimitry Andric } else {
30348675466SDimitry Andric RetAddr = CGF.CreateMemTemp(RetTy, "tmp", &RetAllocaAddr);
304344a3780SDimitry Andric llvm::TypeSize Size =
30548675466SDimitry Andric CGF.CGM.getDataLayout().getTypeAllocSize(CGF.ConvertTypeForMem(RetTy));
30648675466SDimitry Andric LifetimeSizePtr = CGF.EmitLifetimeStart(Size, RetAllocaAddr.getPointer());
30748675466SDimitry Andric if (LifetimeSizePtr) {
30848675466SDimitry Andric LifetimeStartInst =
30948675466SDimitry Andric cast<llvm::IntrinsicInst>(std::prev(Builder.GetInsertPoint()));
31048675466SDimitry Andric assert(LifetimeStartInst->getIntrinsicID() ==
31148675466SDimitry Andric llvm::Intrinsic::lifetime_start &&
31248675466SDimitry Andric "Last insertion wasn't a lifetime.start?");
31348675466SDimitry Andric
31448675466SDimitry Andric CGF.pushFullExprCleanup<CodeGenFunction::CallLifetimeEnd>(
31548675466SDimitry Andric NormalEHLifetimeMarker, RetAllocaAddr, LifetimeSizePtr);
31648675466SDimitry Andric LifetimeEndBlock = CGF.EHStack.stable_begin();
31748675466SDimitry Andric }
3184ba67500SRoman Divacky }
31936981b17SDimitry Andric
32048675466SDimitry Andric RValue Src =
321cfca06d7SDimitry Andric EmitCall(ReturnValueSlot(RetAddr, Dest.isVolatile(), IsResultUnused,
322cfca06d7SDimitry Andric Dest.isExternallyDestructed()));
32348675466SDimitry Andric
32448675466SDimitry Andric if (!UseTemp)
32548675466SDimitry Andric return;
32648675466SDimitry Andric
327ac9a064cSDimitry Andric assert(Dest.isIgnored() || Dest.emitRawPointer(CGF) !=
328ac9a064cSDimitry Andric Src.getAggregatePointer(E->getType(), CGF));
32948675466SDimitry Andric EmitFinalDestCopy(E->getType(), Src);
33048675466SDimitry Andric
33148675466SDimitry Andric if (!RequiresDestruction && LifetimeStartInst) {
33248675466SDimitry Andric // If there's no dtor to run, the copy was the last use of our temporary.
33348675466SDimitry Andric // Since we're not guaranteed to be in an ExprWithCleanups, clean up
33448675466SDimitry Andric // eagerly.
33548675466SDimitry Andric CGF.DeactivateCleanupBlock(LifetimeEndBlock, LifetimeStartInst);
33648675466SDimitry Andric CGF.EmitLifetimeEnd(LifetimeSizePtr, RetAllocaAddr.getPointer());
33748675466SDimitry Andric }
338d7279c4cSRoman Divacky }
339d7279c4cSRoman Divacky
340ec2b103cSEd Schouten /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
EmitFinalDestCopy(QualType type,RValue src)34145b53394SDimitry Andric void AggExprEmitter::EmitFinalDestCopy(QualType type, RValue src) {
34256d91b49SDimitry Andric assert(src.isAggregate() && "value must be aggregate value!");
34345b53394SDimitry Andric LValue srcLV = CGF.MakeAddrLValue(src.getAggregateAddress(), type);
344ac9a064cSDimitry Andric EmitFinalDestCopy(type, srcLV, CodeGenFunction::EVK_RValue);
34556d91b49SDimitry Andric }
346ec2b103cSEd Schouten
34756d91b49SDimitry Andric /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
EmitFinalDestCopy(QualType type,const LValue & src,CodeGenFunction::ExprValueKind SrcValueKind)348ac9a064cSDimitry Andric void AggExprEmitter::EmitFinalDestCopy(
349ac9a064cSDimitry Andric QualType type, const LValue &src,
350ac9a064cSDimitry Andric CodeGenFunction::ExprValueKind SrcValueKind) {
351bca07a45SDimitry Andric // If Dest is ignored, then we're evaluating an aggregate expression
35256d91b49SDimitry Andric // in a context that doesn't care about the result. Note that loads
35356d91b49SDimitry Andric // from volatile l-values force the existence of a non-ignored
35456d91b49SDimitry Andric // destination.
35556d91b49SDimitry Andric if (Dest.isIgnored())
356ec2b103cSEd Schouten return;
3573d1dcd9bSDimitry Andric
35848675466SDimitry Andric // Copy non-trivial C structs here.
35948675466SDimitry Andric LValue DstLV = CGF.MakeAddrLValue(
36048675466SDimitry Andric Dest.getAddress(), Dest.isVolatile() ? type.withVolatile() : type);
36148675466SDimitry Andric
362ac9a064cSDimitry Andric if (SrcValueKind == CodeGenFunction::EVK_RValue) {
36348675466SDimitry Andric if (type.isNonTrivialToPrimitiveDestructiveMove() == QualType::PCK_Struct) {
36448675466SDimitry Andric if (Dest.isPotentiallyAliased())
36548675466SDimitry Andric CGF.callCStructMoveAssignmentOperator(DstLV, src);
36648675466SDimitry Andric else
36748675466SDimitry Andric CGF.callCStructMoveConstructor(DstLV, src);
36848675466SDimitry Andric return;
36948675466SDimitry Andric }
37048675466SDimitry Andric } else {
37148675466SDimitry Andric if (type.isNonTrivialToPrimitiveCopy() == QualType::PCK_Struct) {
37248675466SDimitry Andric if (Dest.isPotentiallyAliased())
37348675466SDimitry Andric CGF.callCStructCopyAssignmentOperator(DstLV, src);
37448675466SDimitry Andric else
37548675466SDimitry Andric CGF.callCStructCopyConstructor(DstLV, src);
37648675466SDimitry Andric return;
37748675466SDimitry Andric }
37848675466SDimitry Andric }
37948675466SDimitry Andric
380706b4fc4SDimitry Andric AggValueSlot srcAgg = AggValueSlot::forLValue(
381ac9a064cSDimitry Andric src, AggValueSlot::IsDestructed, needsGC(type), AggValueSlot::IsAliased,
382ac9a064cSDimitry Andric AggValueSlot::MayOverlap);
38356d91b49SDimitry Andric EmitCopy(type, Dest, srcAgg);
384ec2b103cSEd Schouten }
385ec2b103cSEd Schouten
38656d91b49SDimitry Andric /// Perform a copy from the source into the destination.
38756d91b49SDimitry Andric ///
38856d91b49SDimitry Andric /// \param type - the type of the aggregate being copied; qualifiers are
38956d91b49SDimitry Andric /// ignored
EmitCopy(QualType type,const AggValueSlot & dest,const AggValueSlot & src)39056d91b49SDimitry Andric void AggExprEmitter::EmitCopy(QualType type, const AggValueSlot &dest,
39156d91b49SDimitry Andric const AggValueSlot &src) {
39256d91b49SDimitry Andric if (dest.requiresGCollection()) {
39348675466SDimitry Andric CharUnits sz = dest.getPreferredSize(CGF.getContext(), type);
39456d91b49SDimitry Andric llvm::Value *size = llvm::ConstantInt::get(CGF.SizeTy, sz.getQuantity());
3954c8b2481SRoman Divacky CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF,
39645b53394SDimitry Andric dest.getAddress(),
39745b53394SDimitry Andric src.getAddress(),
39856d91b49SDimitry Andric size);
3994c8b2481SRoman Divacky return;
4004c8b2481SRoman Divacky }
40156d91b49SDimitry Andric
402ec2b103cSEd Schouten // If the result of the assignment is used, copy the LHS there also.
40356d91b49SDimitry Andric // It's volatile if either side is. Use the minimum alignment of
40456d91b49SDimitry Andric // the two sides.
40548675466SDimitry Andric LValue DestLV = CGF.MakeAddrLValue(dest.getAddress(), type);
40648675466SDimitry Andric LValue SrcLV = CGF.MakeAddrLValue(src.getAddress(), type);
40748675466SDimitry Andric CGF.EmitAggregateCopy(DestLV, SrcLV, type, dest.mayOverlap(),
40845b53394SDimitry Andric dest.isVolatile() || src.isVolatile());
409dbe13110SDimitry Andric }
410dbe13110SDimitry Andric
41148675466SDimitry Andric /// Emit the initializer for a std::initializer_list initialized with a
412dbe13110SDimitry Andric /// real initializer list.
413bfef3995SDimitry Andric void
VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr * E)414bfef3995SDimitry Andric AggExprEmitter::VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E) {
415bfef3995SDimitry Andric // Emit an array containing the elements. The array is externally destructed
416bfef3995SDimitry Andric // if the std::initializer_list object is.
417bfef3995SDimitry Andric ASTContext &Ctx = CGF.getContext();
418bfef3995SDimitry Andric LValue Array = CGF.EmitLValue(E->getSubExpr());
419bfef3995SDimitry Andric assert(Array.isSimple() && "initializer_list array not a simple lvalue");
420ac9a064cSDimitry Andric Address ArrayPtr = Array.getAddress();
421dbe13110SDimitry Andric
422bfef3995SDimitry Andric const ConstantArrayType *ArrayType =
423bfef3995SDimitry Andric Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
424bfef3995SDimitry Andric assert(ArrayType && "std::initializer_list constructed from non-array");
425dbe13110SDimitry Andric
426bfef3995SDimitry Andric RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
427bfef3995SDimitry Andric RecordDecl::field_iterator Field = Record->field_begin();
428ac9a064cSDimitry Andric assert(Field != Record->field_end() &&
429ac9a064cSDimitry Andric Ctx.hasSameType(Field->getType()->getPointeeType(),
430ac9a064cSDimitry Andric ArrayType->getElementType()) &&
431ac9a064cSDimitry Andric "Expected std::initializer_list first field to be const E *");
432dbe13110SDimitry Andric
433dbe13110SDimitry Andric // Start pointer.
434bfef3995SDimitry Andric AggValueSlot Dest = EnsureSlot(E->getType());
43545b53394SDimitry Andric LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType());
436bfef3995SDimitry Andric LValue Start = CGF.EmitLValueForFieldInitialization(DestLV, *Field);
437ac9a064cSDimitry Andric llvm::Value *ArrayStart = ArrayPtr.emitRawPointer(CGF);
438bfef3995SDimitry Andric CGF.EmitStoreThroughLValue(RValue::get(ArrayStart), Start);
439bfef3995SDimitry Andric ++Field;
440ac9a064cSDimitry Andric assert(Field != Record->field_end() &&
441ac9a064cSDimitry Andric "Expected std::initializer_list to have two fields");
442bfef3995SDimitry Andric
443bfef3995SDimitry Andric llvm::Value *Size = Builder.getInt(ArrayType->getSize());
444bfef3995SDimitry Andric LValue EndOrLength = CGF.EmitLValueForFieldInitialization(DestLV, *Field);
445ac9a064cSDimitry Andric if (Ctx.hasSameType(Field->getType(), Ctx.getSizeType())) {
446dbe13110SDimitry Andric // Length.
447bfef3995SDimitry Andric CGF.EmitStoreThroughLValue(RValue::get(Size), EndOrLength);
448ac9a064cSDimitry Andric
449dbe13110SDimitry Andric } else {
450ac9a064cSDimitry Andric // End pointer.
451ac9a064cSDimitry Andric assert(Field->getType()->isPointerType() &&
452ac9a064cSDimitry Andric Ctx.hasSameType(Field->getType()->getPointeeType(),
453ac9a064cSDimitry Andric ArrayType->getElementType()) &&
454ac9a064cSDimitry Andric "Expected std::initializer_list second field to be const E *");
455ac9a064cSDimitry Andric llvm::Value *Zero = llvm::ConstantInt::get(CGF.PtrDiffTy, 0);
456ac9a064cSDimitry Andric llvm::Value *IdxEnd[] = { Zero, Size };
457ac9a064cSDimitry Andric llvm::Value *ArrayEnd = Builder.CreateInBoundsGEP(
458ac9a064cSDimitry Andric ArrayPtr.getElementType(), ArrayPtr.emitRawPointer(CGF), IdxEnd,
459ac9a064cSDimitry Andric "arrayend");
460ac9a064cSDimitry Andric CGF.EmitStoreThroughLValue(RValue::get(ArrayEnd), EndOrLength);
461dbe13110SDimitry Andric }
462ac9a064cSDimitry Andric
463ac9a064cSDimitry Andric assert(++Field == Record->field_end() &&
464ac9a064cSDimitry Andric "Expected std::initializer_list to only have two fields");
465dbe13110SDimitry Andric }
466dbe13110SDimitry Andric
46748675466SDimitry Andric /// Determine if E is a trivial array filler, that is, one that is
4689f4dbff6SDimitry Andric /// equivalent to zero-initialization.
isTrivialFiller(Expr * E)4699f4dbff6SDimitry Andric static bool isTrivialFiller(Expr *E) {
4709f4dbff6SDimitry Andric if (!E)
4719f4dbff6SDimitry Andric return true;
4729f4dbff6SDimitry Andric
4739f4dbff6SDimitry Andric if (isa<ImplicitValueInitExpr>(E))
4749f4dbff6SDimitry Andric return true;
4759f4dbff6SDimitry Andric
4769f4dbff6SDimitry Andric if (auto *ILE = dyn_cast<InitListExpr>(E)) {
4779f4dbff6SDimitry Andric if (ILE->getNumInits())
4789f4dbff6SDimitry Andric return false;
4799f4dbff6SDimitry Andric return isTrivialFiller(ILE->getArrayFiller());
4809f4dbff6SDimitry Andric }
4819f4dbff6SDimitry Andric
4829f4dbff6SDimitry Andric if (auto *Cons = dyn_cast_or_null<CXXConstructExpr>(E))
4839f4dbff6SDimitry Andric return Cons->getConstructor()->isDefaultConstructor() &&
4849f4dbff6SDimitry Andric Cons->getConstructor()->isTrivial();
4859f4dbff6SDimitry Andric
4869f4dbff6SDimitry Andric // FIXME: Are there other cases where we can avoid emitting an initializer?
4879f4dbff6SDimitry Andric return false;
4889f4dbff6SDimitry Andric }
4899f4dbff6SDimitry Andric
490e3b55780SDimitry Andric /// Emit initialization of an array from an initializer list. ExprToVisit must
491e3b55780SDimitry Andric /// be either an InitListEpxr a CXXParenInitListExpr.
EmitArrayInit(Address DestPtr,llvm::ArrayType * AType,QualType ArrayQTy,Expr * ExprToVisit,ArrayRef<Expr * > Args,Expr * ArrayFiller)49245b53394SDimitry Andric void AggExprEmitter::EmitArrayInit(Address DestPtr, llvm::ArrayType *AType,
493e3b55780SDimitry Andric QualType ArrayQTy, Expr *ExprToVisit,
494e3b55780SDimitry Andric ArrayRef<Expr *> Args, Expr *ArrayFiller) {
495e3b55780SDimitry Andric uint64_t NumInitElements = Args.size();
496dbe13110SDimitry Andric
497dbe13110SDimitry Andric uint64_t NumArrayElements = AType->getNumElements();
498ac9a064cSDimitry Andric for (const auto *Init : Args) {
499ac9a064cSDimitry Andric if (const auto *Embed = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) {
500ac9a064cSDimitry Andric NumInitElements += Embed->getDataElementCount() - 1;
501ac9a064cSDimitry Andric if (NumInitElements > NumArrayElements) {
502ac9a064cSDimitry Andric NumInitElements = NumArrayElements;
503ac9a064cSDimitry Andric break;
504ac9a064cSDimitry Andric }
505ac9a064cSDimitry Andric }
506ac9a064cSDimitry Andric }
507ac9a064cSDimitry Andric
508dbe13110SDimitry Andric assert(NumInitElements <= NumArrayElements);
509dbe13110SDimitry Andric
51048675466SDimitry Andric QualType elementType =
51148675466SDimitry Andric CGF.getContext().getAsArrayType(ArrayQTy)->getElementType();
51245b53394SDimitry Andric CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
51345b53394SDimitry Andric CharUnits elementAlign =
51445b53394SDimitry Andric DestPtr.getAlignment().alignmentOfArrayElement(elementSize);
51577fc4c14SDimitry Andric llvm::Type *llvmElementType = CGF.ConvertTypeForMem(elementType);
516dbe13110SDimitry Andric
51748675466SDimitry Andric // Consider initializing the array by copying from a global. For this to be
51848675466SDimitry Andric // more efficient than per-element initialization, the size of the elements
51948675466SDimitry Andric // with explicit initializers should be large enough.
52048675466SDimitry Andric if (NumInitElements * elementSize.getQuantity() > 16 &&
52148675466SDimitry Andric elementType.isTriviallyCopyableType(CGF.getContext())) {
52248675466SDimitry Andric CodeGen::CodeGenModule &CGM = CGF.CGM;
523706b4fc4SDimitry Andric ConstantEmitter Emitter(CGF);
524ac9a064cSDimitry Andric QualType GVArrayQTy = CGM.getContext().getAddrSpaceQualType(
525ac9a064cSDimitry Andric CGM.getContext().removeAddrSpaceQualType(ArrayQTy),
526ac9a064cSDimitry Andric CGM.GetGlobalConstantAddressSpace());
527ac9a064cSDimitry Andric LangAS AS = GVArrayQTy.getAddressSpace();
528e3b55780SDimitry Andric if (llvm::Constant *C =
529ac9a064cSDimitry Andric Emitter.tryEmitForInitializer(ExprToVisit, AS, GVArrayQTy)) {
53048675466SDimitry Andric auto GV = new llvm::GlobalVariable(
53148675466SDimitry Andric CGM.getModule(), C->getType(),
5327fa27ce4SDimitry Andric /* isConstant= */ true, llvm::GlobalValue::PrivateLinkage, C,
5337fa27ce4SDimitry Andric "constinit",
53448675466SDimitry Andric /* InsertBefore= */ nullptr, llvm::GlobalVariable::NotThreadLocal,
53548675466SDimitry Andric CGM.getContext().getTargetAddressSpace(AS));
53648675466SDimitry Andric Emitter.finalize(GV);
537ac9a064cSDimitry Andric CharUnits Align = CGM.getContext().getTypeAlignInChars(GVArrayQTy);
538519fc96cSDimitry Andric GV->setAlignment(Align.getAsAlign());
53977fc4c14SDimitry Andric Address GVAddr(GV, GV->getValueType(), Align);
540ac9a064cSDimitry Andric EmitFinalDestCopy(ArrayQTy, CGF.MakeAddrLValue(GVAddr, GVArrayQTy));
54148675466SDimitry Andric return;
54248675466SDimitry Andric }
54348675466SDimitry Andric }
54448675466SDimitry Andric
545dbe13110SDimitry Andric // Exception safety requires us to destroy all the
546dbe13110SDimitry Andric // already-constructed members if an initializer throws.
547dbe13110SDimitry Andric // For that, we'll need an EH cleanup.
548dbe13110SDimitry Andric QualType::DestructionKind dtorKind = elementType.isDestructedType();
54945b53394SDimitry Andric Address endOfInit = Address::invalid();
550ac9a064cSDimitry Andric CodeGenFunction::CleanupDeactivationScope deactivation(CGF);
551ac9a064cSDimitry Andric
552ac9a064cSDimitry Andric llvm::Value *begin = DestPtr.emitRawPointer(CGF);
553ac9a064cSDimitry Andric if (dtorKind) {
554ac9a064cSDimitry Andric CodeGenFunction::AllocaTrackerRAII allocaTracker(CGF);
555dbe13110SDimitry Andric // In principle we could tell the cleanup where we are more
556dbe13110SDimitry Andric // directly, but the control flow can get so varied here that it
557dbe13110SDimitry Andric // would actually be quite complex. Therefore we go through an
558dbe13110SDimitry Andric // alloca.
559ac9a064cSDimitry Andric llvm::Instruction *dominatingIP =
560ac9a064cSDimitry Andric Builder.CreateFlagLoad(llvm::ConstantInt::getNullValue(CGF.Int8PtrTy));
56145b53394SDimitry Andric endOfInit = CGF.CreateTempAlloca(begin->getType(), CGF.getPointerAlign(),
562dbe13110SDimitry Andric "arrayinit.endOfInit");
563ac9a064cSDimitry Andric Builder.CreateStore(begin, endOfInit);
564dbe13110SDimitry Andric CGF.pushIrregularPartialArrayCleanup(begin, endOfInit, elementType,
56545b53394SDimitry Andric elementAlign,
566dbe13110SDimitry Andric CGF.getDestroyer(dtorKind));
567ac9a064cSDimitry Andric cast<EHCleanupScope>(*CGF.EHStack.find(CGF.EHStack.stable_begin()))
568ac9a064cSDimitry Andric .AddAuxAllocas(allocaTracker.Take());
569dbe13110SDimitry Andric
570ac9a064cSDimitry Andric CGF.DeferredDeactivationCleanupStack.push_back(
571ac9a064cSDimitry Andric {CGF.EHStack.stable_begin(), dominatingIP});
572dbe13110SDimitry Andric }
573dbe13110SDimitry Andric
574dbe13110SDimitry Andric llvm::Value *one = llvm::ConstantInt::get(CGF.SizeTy, 1);
575dbe13110SDimitry Andric
576ac9a064cSDimitry Andric auto Emit = [&](Expr *Init, uint64_t ArrayIndex) {
577dbe13110SDimitry Andric llvm::Value *element = begin;
578ac9a064cSDimitry Andric if (ArrayIndex > 0) {
579344a3780SDimitry Andric element = Builder.CreateInBoundsGEP(
580ac9a064cSDimitry Andric llvmElementType, begin,
581ac9a064cSDimitry Andric llvm::ConstantInt::get(CGF.SizeTy, ArrayIndex), "arrayinit.element");
582dbe13110SDimitry Andric
583dbe13110SDimitry Andric // Tell the cleanup that it needs to destroy up to this
584dbe13110SDimitry Andric // element. TODO: some of these stores can be trivially
585dbe13110SDimitry Andric // observed to be unnecessary.
586ac9a064cSDimitry Andric if (endOfInit.isValid())
587ac9a064cSDimitry Andric Builder.CreateStore(element, endOfInit);
588dbe13110SDimitry Andric }
589dbe13110SDimitry Andric
59077fc4c14SDimitry Andric LValue elementLV = CGF.MakeAddrLValue(
59177fc4c14SDimitry Andric Address(element, llvmElementType, elementAlign), elementType);
592ac9a064cSDimitry Andric EmitInitializationToLValue(Init, elementLV);
593ac9a064cSDimitry Andric return true;
594ac9a064cSDimitry Andric };
595ac9a064cSDimitry Andric
596ac9a064cSDimitry Andric unsigned ArrayIndex = 0;
597ac9a064cSDimitry Andric // Emit the explicit initializers.
598ac9a064cSDimitry Andric for (uint64_t i = 0; i != NumInitElements; ++i) {
599ac9a064cSDimitry Andric if (ArrayIndex >= NumInitElements)
600ac9a064cSDimitry Andric break;
601ac9a064cSDimitry Andric if (auto *EmbedS = dyn_cast<EmbedExpr>(Args[i]->IgnoreParenImpCasts())) {
602ac9a064cSDimitry Andric EmbedS->doForEachDataElement(Emit, ArrayIndex);
603ac9a064cSDimitry Andric } else {
604ac9a064cSDimitry Andric Emit(Args[i], ArrayIndex);
605ac9a064cSDimitry Andric ArrayIndex++;
606ac9a064cSDimitry Andric }
607dbe13110SDimitry Andric }
608dbe13110SDimitry Andric
609dbe13110SDimitry Andric // Check whether there's a non-trivial array-fill expression.
610e3b55780SDimitry Andric bool hasTrivialFiller = isTrivialFiller(ArrayFiller);
611dbe13110SDimitry Andric
612dbe13110SDimitry Andric // Any remaining elements need to be zero-initialized, possibly
613dbe13110SDimitry Andric // using the filler expression. We can skip this if the we're
614dbe13110SDimitry Andric // emitting to zeroed memory.
615dbe13110SDimitry Andric if (NumInitElements != NumArrayElements &&
616dbe13110SDimitry Andric !(Dest.isZeroed() && hasTrivialFiller &&
617dbe13110SDimitry Andric CGF.getTypes().isZeroInitializable(elementType))) {
618dbe13110SDimitry Andric
619dbe13110SDimitry Andric // Use an actual loop. This is basically
620dbe13110SDimitry Andric // do { *array++ = filler; } while (array != end);
621dbe13110SDimitry Andric
622dbe13110SDimitry Andric // Advance to the start of the rest of the array.
623ac9a064cSDimitry Andric llvm::Value *element = begin;
624dbe13110SDimitry Andric if (NumInitElements) {
625344a3780SDimitry Andric element = Builder.CreateInBoundsGEP(
626ac9a064cSDimitry Andric llvmElementType, element,
627ac9a064cSDimitry Andric llvm::ConstantInt::get(CGF.SizeTy, NumInitElements),
628ac9a064cSDimitry Andric "arrayinit.start");
62945b53394SDimitry Andric if (endOfInit.isValid()) Builder.CreateStore(element, endOfInit);
630dbe13110SDimitry Andric }
631dbe13110SDimitry Andric
632dbe13110SDimitry Andric // Compute the end of the array.
633344a3780SDimitry Andric llvm::Value *end = Builder.CreateInBoundsGEP(
634344a3780SDimitry Andric llvmElementType, begin,
635344a3780SDimitry Andric llvm::ConstantInt::get(CGF.SizeTy, NumArrayElements), "arrayinit.end");
636dbe13110SDimitry Andric
637dbe13110SDimitry Andric llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
638dbe13110SDimitry Andric llvm::BasicBlock *bodyBB = CGF.createBasicBlock("arrayinit.body");
639dbe13110SDimitry Andric
640dbe13110SDimitry Andric // Jump into the body.
641dbe13110SDimitry Andric CGF.EmitBlock(bodyBB);
642dbe13110SDimitry Andric llvm::PHINode *currentElement =
643dbe13110SDimitry Andric Builder.CreatePHI(element->getType(), 2, "arrayinit.cur");
644dbe13110SDimitry Andric currentElement->addIncoming(element, entryBB);
645dbe13110SDimitry Andric
646dbe13110SDimitry Andric // Emit the actual filler expression.
6472410013dSDimitry Andric {
6482410013dSDimitry Andric // C++1z [class.temporary]p5:
6492410013dSDimitry Andric // when a default constructor is called to initialize an element of
6502410013dSDimitry Andric // an array with no corresponding initializer [...] the destruction of
6512410013dSDimitry Andric // every temporary created in a default argument is sequenced before
6522410013dSDimitry Andric // the construction of the next array element, if any
6532410013dSDimitry Andric CodeGenFunction::RunCleanupsScope CleanupsScope(CGF);
6546f8fc217SDimitry Andric LValue elementLV = CGF.MakeAddrLValue(
6556f8fc217SDimitry Andric Address(currentElement, llvmElementType, elementAlign), elementType);
656e3b55780SDimitry Andric if (ArrayFiller)
657e3b55780SDimitry Andric EmitInitializationToLValue(ArrayFiller, elementLV);
658dbe13110SDimitry Andric else
659dbe13110SDimitry Andric EmitNullInitializationToLValue(elementLV);
6602410013dSDimitry Andric }
661dbe13110SDimitry Andric
662dbe13110SDimitry Andric // Move on to the next element.
663344a3780SDimitry Andric llvm::Value *nextElement = Builder.CreateInBoundsGEP(
664344a3780SDimitry Andric llvmElementType, currentElement, one, "arrayinit.next");
665dbe13110SDimitry Andric
666dbe13110SDimitry Andric // Tell the EH cleanup that we finished with the last element.
66745b53394SDimitry Andric if (endOfInit.isValid()) Builder.CreateStore(nextElement, endOfInit);
668dbe13110SDimitry Andric
669dbe13110SDimitry Andric // Leave the loop if we're done.
670dbe13110SDimitry Andric llvm::Value *done = Builder.CreateICmpEQ(nextElement, end,
671dbe13110SDimitry Andric "arrayinit.done");
672dbe13110SDimitry Andric llvm::BasicBlock *endBB = CGF.createBasicBlock("arrayinit.end");
673dbe13110SDimitry Andric Builder.CreateCondBr(done, endBB, bodyBB);
674dbe13110SDimitry Andric currentElement->addIncoming(nextElement, Builder.GetInsertBlock());
675dbe13110SDimitry Andric
676dbe13110SDimitry Andric CGF.EmitBlock(endBB);
677dbe13110SDimitry Andric }
678ec2b103cSEd Schouten }
679ec2b103cSEd Schouten
680ec2b103cSEd Schouten //===----------------------------------------------------------------------===//
681ec2b103cSEd Schouten // Visitor Methods
682ec2b103cSEd Schouten //===----------------------------------------------------------------------===//
683ec2b103cSEd Schouten
VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr * E)684180abc3dSDimitry Andric void AggExprEmitter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E){
685706b4fc4SDimitry Andric Visit(E->getSubExpr());
686180abc3dSDimitry Andric }
687180abc3dSDimitry Andric
VisitOpaqueValueExpr(OpaqueValueExpr * e)688bca07a45SDimitry Andric void AggExprEmitter::VisitOpaqueValueExpr(OpaqueValueExpr *e) {
68948675466SDimitry Andric // If this is a unique OVE, just visit its source expression.
69048675466SDimitry Andric if (e->isUnique())
69148675466SDimitry Andric Visit(e->getSourceExpr());
69248675466SDimitry Andric else
69348675466SDimitry Andric EmitFinalDestCopy(e->getType(), CGF.getOrCreateOpaqueLValueMapping(e));
694bca07a45SDimitry Andric }
695bca07a45SDimitry Andric
696180abc3dSDimitry Andric void
VisitCompoundLiteralExpr(CompoundLiteralExpr * E)697180abc3dSDimitry Andric AggExprEmitter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
698809500fcSDimitry Andric if (Dest.isPotentiallyAliased() &&
699809500fcSDimitry Andric E->getType().isPODType(CGF.getContext())) {
700180abc3dSDimitry Andric // For a POD type, just emit a load of the lvalue + a copy, because our
701180abc3dSDimitry Andric // compound literal might alias the destination.
702180abc3dSDimitry Andric EmitAggLoadOfLValue(E);
703180abc3dSDimitry Andric return;
704180abc3dSDimitry Andric }
705180abc3dSDimitry Andric
706180abc3dSDimitry Andric AggValueSlot Slot = EnsureSlot(E->getType());
707cfca06d7SDimitry Andric
708cfca06d7SDimitry Andric // Block-scope compound literals are destroyed at the end of the enclosing
709cfca06d7SDimitry Andric // scope in C.
710cfca06d7SDimitry Andric bool Destruct =
711cfca06d7SDimitry Andric !CGF.getLangOpts().CPlusPlus && !Slot.isExternallyDestructed();
712cfca06d7SDimitry Andric if (Destruct)
713cfca06d7SDimitry Andric Slot.setExternallyDestructed();
714cfca06d7SDimitry Andric
715180abc3dSDimitry Andric CGF.EmitAggExpr(E->getInitializer(), Slot);
716cfca06d7SDimitry Andric
717cfca06d7SDimitry Andric if (Destruct)
718cfca06d7SDimitry Andric if (QualType::DestructionKind DtorKind = E->getType().isDestructedType())
719cfca06d7SDimitry Andric CGF.pushLifetimeExtendedDestroy(
720cfca06d7SDimitry Andric CGF.getCleanupKind(DtorKind), Slot.getAddress(), E->getType(),
721cfca06d7SDimitry Andric CGF.getDestroyer(DtorKind), DtorKind & EHCleanup);
722180abc3dSDimitry Andric }
723180abc3dSDimitry Andric
724809500fcSDimitry Andric /// Attempt to look through various unimportant expressions to find a
725809500fcSDimitry Andric /// cast of the given kind.
findPeephole(Expr * op,CastKind kind,const ASTContext & ctx)726cfca06d7SDimitry Andric static Expr *findPeephole(Expr *op, CastKind kind, const ASTContext &ctx) {
727cfca06d7SDimitry Andric op = op->IgnoreParenNoopCasts(ctx);
728cfca06d7SDimitry Andric if (auto castE = dyn_cast<CastExpr>(op)) {
729809500fcSDimitry Andric if (castE->getCastKind() == kind)
730809500fcSDimitry Andric return castE->getSubExpr();
731809500fcSDimitry Andric }
7329f4dbff6SDimitry Andric return nullptr;
733809500fcSDimitry Andric }
734180abc3dSDimitry Andric
VisitCastExpr(CastExpr * E)7354c8b2481SRoman Divacky void AggExprEmitter::VisitCastExpr(CastExpr *E) {
73645b53394SDimitry Andric if (const auto *ECE = dyn_cast<ExplicitCastExpr>(E))
73745b53394SDimitry Andric CGF.CGM.EmitExplicitCastExprType(ECE, &CGF);
7384c8b2481SRoman Divacky switch (E->getCastKind()) {
7393d1dcd9bSDimitry Andric case CK_Dynamic: {
74013cc256eSDimitry Andric // FIXME: Can this actually happen? We have no test coverage for it.
741d7279c4cSRoman Divacky assert(isa<CXXDynamicCastExpr>(E) && "CK_Dynamic without a dynamic_cast?");
74213cc256eSDimitry Andric LValue LV = CGF.EmitCheckedLValue(E->getSubExpr(),
74313cc256eSDimitry Andric CodeGenFunction::TCK_Load);
744d7279c4cSRoman Divacky // FIXME: Do we also need to handle property references here?
745d7279c4cSRoman Divacky if (LV.isSimple())
746ac9a064cSDimitry Andric CGF.EmitDynamicCast(LV.getAddress(), cast<CXXDynamicCastExpr>(E));
747d7279c4cSRoman Divacky else
748d7279c4cSRoman Divacky CGF.CGM.ErrorUnsupported(E, "non-simple lvalue dynamic_cast");
749d7279c4cSRoman Divacky
750bca07a45SDimitry Andric if (!Dest.isIgnored())
751d7279c4cSRoman Divacky CGF.CGM.ErrorUnsupported(E, "lvalue dynamic_cast with a destination");
752d7279c4cSRoman Divacky break;
753d7279c4cSRoman Divacky }
754d7279c4cSRoman Divacky
7553d1dcd9bSDimitry Andric case CK_ToUnion: {
7565e20cdd8SDimitry Andric // Evaluate even if the destination is ignored.
7575e20cdd8SDimitry Andric if (Dest.isIgnored()) {
7585e20cdd8SDimitry Andric CGF.EmitAnyExpr(E->getSubExpr(), AggValueSlot::ignored(),
7595e20cdd8SDimitry Andric /*ignoreResult=*/true);
7605e20cdd8SDimitry Andric break;
7615e20cdd8SDimitry Andric }
76201af97d3SDimitry Andric
763ec2b103cSEd Schouten // GCC union extension
7643d1dcd9bSDimitry Andric QualType Ty = E->getSubExpr()->getType();
7657fa27ce4SDimitry Andric Address CastPtr = Dest.getAddress().withElementType(CGF.ConvertType(Ty));
766180abc3dSDimitry Andric EmitInitializationToLValue(E->getSubExpr(),
767180abc3dSDimitry Andric CGF.MakeAddrLValue(CastPtr, Ty));
7684c8b2481SRoman Divacky break;
769ec2b103cSEd Schouten }
770ec2b103cSEd Schouten
77122989816SDimitry Andric case CK_LValueToRValueBitCast: {
77222989816SDimitry Andric if (Dest.isIgnored()) {
77322989816SDimitry Andric CGF.EmitAnyExpr(E->getSubExpr(), AggValueSlot::ignored(),
77422989816SDimitry Andric /*ignoreResult=*/true);
77522989816SDimitry Andric break;
77622989816SDimitry Andric }
77722989816SDimitry Andric
77822989816SDimitry Andric LValue SourceLV = CGF.EmitLValue(E->getSubExpr());
779ac9a064cSDimitry Andric Address SourceAddress = SourceLV.getAddress().withElementType(CGF.Int8Ty);
7807fa27ce4SDimitry Andric Address DestAddress = Dest.getAddress().withElementType(CGF.Int8Ty);
78122989816SDimitry Andric llvm::Value *SizeVal = llvm::ConstantInt::get(
78222989816SDimitry Andric CGF.SizeTy,
78322989816SDimitry Andric CGF.getContext().getTypeSizeInChars(E->getType()).getQuantity());
78422989816SDimitry Andric Builder.CreateMemCpy(DestAddress, SourceAddress, SizeVal);
78522989816SDimitry Andric break;
78622989816SDimitry Andric }
78722989816SDimitry Andric
7883d1dcd9bSDimitry Andric case CK_DerivedToBase:
7893d1dcd9bSDimitry Andric case CK_BaseToDerived:
7903d1dcd9bSDimitry Andric case CK_UncheckedDerivedToBase: {
79136981b17SDimitry Andric llvm_unreachable("cannot perform hierarchy conversion in EmitAggExpr: "
792d7279c4cSRoman Divacky "should have been unpacked before we got here");
793d7279c4cSRoman Divacky }
794d7279c4cSRoman Divacky
795809500fcSDimitry Andric case CK_NonAtomicToAtomic:
796809500fcSDimitry Andric case CK_AtomicToNonAtomic: {
797809500fcSDimitry Andric bool isToAtomic = (E->getCastKind() == CK_NonAtomicToAtomic);
798809500fcSDimitry Andric
799809500fcSDimitry Andric // Determine the atomic and value types.
800809500fcSDimitry Andric QualType atomicType = E->getSubExpr()->getType();
801809500fcSDimitry Andric QualType valueType = E->getType();
802809500fcSDimitry Andric if (isToAtomic) std::swap(atomicType, valueType);
803809500fcSDimitry Andric
804809500fcSDimitry Andric assert(atomicType->isAtomicType());
805809500fcSDimitry Andric assert(CGF.getContext().hasSameUnqualifiedType(valueType,
806809500fcSDimitry Andric atomicType->castAs<AtomicType>()->getValueType()));
807809500fcSDimitry Andric
808809500fcSDimitry Andric // Just recurse normally if we're ignoring the result or the
809809500fcSDimitry Andric // atomic type doesn't change representation.
810809500fcSDimitry Andric if (Dest.isIgnored() || !CGF.CGM.isPaddedAtomicType(atomicType)) {
811809500fcSDimitry Andric return Visit(E->getSubExpr());
812809500fcSDimitry Andric }
813809500fcSDimitry Andric
814809500fcSDimitry Andric CastKind peepholeTarget =
815809500fcSDimitry Andric (isToAtomic ? CK_AtomicToNonAtomic : CK_NonAtomicToAtomic);
816809500fcSDimitry Andric
817809500fcSDimitry Andric // These two cases are reverses of each other; try to peephole them.
818cfca06d7SDimitry Andric if (Expr *op =
819cfca06d7SDimitry Andric findPeephole(E->getSubExpr(), peepholeTarget, CGF.getContext())) {
820809500fcSDimitry Andric assert(CGF.getContext().hasSameUnqualifiedType(op->getType(),
821809500fcSDimitry Andric E->getType()) &&
822809500fcSDimitry Andric "peephole significantly changed types?");
823809500fcSDimitry Andric return Visit(op);
824809500fcSDimitry Andric }
825809500fcSDimitry Andric
826809500fcSDimitry Andric // If we're converting an r-value of non-atomic type to an r-value
827bfef3995SDimitry Andric // of atomic type, just emit directly into the relevant sub-object.
828809500fcSDimitry Andric if (isToAtomic) {
829bfef3995SDimitry Andric AggValueSlot valueDest = Dest;
830bfef3995SDimitry Andric if (!valueDest.isIgnored() && CGF.CGM.isPaddedAtomicType(atomicType)) {
83148675466SDimitry Andric // Zero-initialize. (Strictly speaking, we only need to initialize
832bfef3995SDimitry Andric // the padding at the end, but this is simpler.)
833bfef3995SDimitry Andric if (!Dest.isZeroed())
83445b53394SDimitry Andric CGF.EmitNullInitialization(Dest.getAddress(), atomicType);
835bfef3995SDimitry Andric
836bfef3995SDimitry Andric // Build a GEP to refer to the subobject.
83745b53394SDimitry Andric Address valueAddr =
83822989816SDimitry Andric CGF.Builder.CreateStructGEP(valueDest.getAddress(), 0);
839bfef3995SDimitry Andric valueDest = AggValueSlot::forAddr(valueAddr,
840bfef3995SDimitry Andric valueDest.getQualifiers(),
841bfef3995SDimitry Andric valueDest.isExternallyDestructed(),
842bfef3995SDimitry Andric valueDest.requiresGCollection(),
843bfef3995SDimitry Andric valueDest.isPotentiallyAliased(),
84448675466SDimitry Andric AggValueSlot::DoesNotOverlap,
845bfef3995SDimitry Andric AggValueSlot::IsZeroed);
846bfef3995SDimitry Andric }
847bfef3995SDimitry Andric
848bfef3995SDimitry Andric CGF.EmitAggExpr(E->getSubExpr(), valueDest);
849809500fcSDimitry Andric return;
850809500fcSDimitry Andric }
851809500fcSDimitry Andric
852809500fcSDimitry Andric // Otherwise, we're converting an atomic type to a non-atomic type.
853bfef3995SDimitry Andric // Make an atomic temporary, emit into that, and then copy the value out.
854809500fcSDimitry Andric AggValueSlot atomicSlot =
855809500fcSDimitry Andric CGF.CreateAggTemp(atomicType, "atomic-to-nonatomic.temp");
856809500fcSDimitry Andric CGF.EmitAggExpr(E->getSubExpr(), atomicSlot);
857809500fcSDimitry Andric
85822989816SDimitry Andric Address valueAddr = Builder.CreateStructGEP(atomicSlot.getAddress(), 0);
859809500fcSDimitry Andric RValue rvalue = RValue::getAggregate(valueAddr, atomicSlot.isVolatile());
860809500fcSDimitry Andric return EmitFinalDestCopy(valueType, rvalue);
861809500fcSDimitry Andric }
86222989816SDimitry Andric case CK_AddressSpaceConversion:
86322989816SDimitry Andric return Visit(E->getSubExpr());
864809500fcSDimitry Andric
86556d91b49SDimitry Andric case CK_LValueToRValue:
86656d91b49SDimitry Andric // If we're loading from a volatile type, force the destination
86756d91b49SDimitry Andric // into existence.
86856d91b49SDimitry Andric if (E->getSubExpr()->getType().isVolatileQualified()) {
869cfca06d7SDimitry Andric bool Destruct =
870cfca06d7SDimitry Andric !Dest.isExternallyDestructed() &&
871cfca06d7SDimitry Andric E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct;
872cfca06d7SDimitry Andric if (Destruct)
873cfca06d7SDimitry Andric Dest.setExternallyDestructed();
87456d91b49SDimitry Andric EnsureDest(E->getType());
875cfca06d7SDimitry Andric Visit(E->getSubExpr());
876cfca06d7SDimitry Andric
877cfca06d7SDimitry Andric if (Destruct)
878cfca06d7SDimitry Andric CGF.pushDestroy(QualType::DK_nontrivial_c_struct, Dest.getAddress(),
879cfca06d7SDimitry Andric E->getType());
880cfca06d7SDimitry Andric
881cfca06d7SDimitry Andric return;
88256d91b49SDimitry Andric }
883809500fcSDimitry Andric
884e3b55780SDimitry Andric [[fallthrough]];
88556d91b49SDimitry Andric
886ac9a064cSDimitry Andric case CK_HLSLArrayRValue:
887ac9a064cSDimitry Andric Visit(E->getSubExpr());
888ac9a064cSDimitry Andric break;
88922989816SDimitry Andric
8903d1dcd9bSDimitry Andric case CK_NoOp:
8913d1dcd9bSDimitry Andric case CK_UserDefinedConversion:
8923d1dcd9bSDimitry Andric case CK_ConstructorConversion:
893ec2b103cSEd Schouten assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(),
894ec2b103cSEd Schouten E->getType()) &&
895ec2b103cSEd Schouten "Implicit cast types must be compatible");
896ec2b103cSEd Schouten Visit(E->getSubExpr());
8974c8b2481SRoman Divacky break;
8984c8b2481SRoman Divacky
8993d1dcd9bSDimitry Andric case CK_LValueBitCast:
900bca07a45SDimitry Andric llvm_unreachable("should not be emitting lvalue bitcast as rvalue");
901bca07a45SDimitry Andric
902bca07a45SDimitry Andric case CK_Dependent:
903bca07a45SDimitry Andric case CK_BitCast:
904bca07a45SDimitry Andric case CK_ArrayToPointerDecay:
905bca07a45SDimitry Andric case CK_FunctionToPointerDecay:
906bca07a45SDimitry Andric case CK_NullToPointer:
907bca07a45SDimitry Andric case CK_NullToMemberPointer:
908bca07a45SDimitry Andric case CK_BaseToDerivedMemberPointer:
909bca07a45SDimitry Andric case CK_DerivedToBaseMemberPointer:
910bca07a45SDimitry Andric case CK_MemberPointerToBoolean:
911dbe13110SDimitry Andric case CK_ReinterpretMemberPointer:
912bca07a45SDimitry Andric case CK_IntegralToPointer:
913bca07a45SDimitry Andric case CK_PointerToIntegral:
914bca07a45SDimitry Andric case CK_PointerToBoolean:
915bca07a45SDimitry Andric case CK_ToVoid:
916bca07a45SDimitry Andric case CK_VectorSplat:
917bca07a45SDimitry Andric case CK_IntegralCast:
9180414e226SDimitry Andric case CK_BooleanToSignedIntegral:
919bca07a45SDimitry Andric case CK_IntegralToBoolean:
920bca07a45SDimitry Andric case CK_IntegralToFloating:
921bca07a45SDimitry Andric case CK_FloatingToIntegral:
922bca07a45SDimitry Andric case CK_FloatingToBoolean:
923bca07a45SDimitry Andric case CK_FloatingCast:
92436981b17SDimitry Andric case CK_CPointerToObjCPointerCast:
92536981b17SDimitry Andric case CK_BlockPointerToObjCPointerCast:
926bca07a45SDimitry Andric case CK_AnyPointerToBlockPointerCast:
927bca07a45SDimitry Andric case CK_ObjCObjectLValueCast:
928bca07a45SDimitry Andric case CK_FloatingRealToComplex:
929bca07a45SDimitry Andric case CK_FloatingComplexToReal:
930bca07a45SDimitry Andric case CK_FloatingComplexToBoolean:
931bca07a45SDimitry Andric case CK_FloatingComplexCast:
932bca07a45SDimitry Andric case CK_FloatingComplexToIntegralComplex:
933bca07a45SDimitry Andric case CK_IntegralRealToComplex:
934bca07a45SDimitry Andric case CK_IntegralComplexToReal:
935bca07a45SDimitry Andric case CK_IntegralComplexToBoolean:
936bca07a45SDimitry Andric case CK_IntegralComplexCast:
937bca07a45SDimitry Andric case CK_IntegralComplexToFloatingComplex:
93836981b17SDimitry Andric case CK_ARCProduceObject:
93936981b17SDimitry Andric case CK_ARCConsumeObject:
94036981b17SDimitry Andric case CK_ARCReclaimReturnedObject:
94136981b17SDimitry Andric case CK_ARCExtendBlockObject:
942dbe13110SDimitry Andric case CK_CopyAndAutoreleaseBlockObject:
94313cc256eSDimitry Andric case CK_BuiltinFnToFnPtr:
944676fbe81SDimitry Andric case CK_ZeroToOCLOpaqueType:
945344a3780SDimitry Andric case CK_MatrixCast:
946ac9a064cSDimitry Andric case CK_HLSLVectorTruncation:
94722989816SDimitry Andric
948bab175ecSDimitry Andric case CK_IntToOCLSampler:
949b60736ecSDimitry Andric case CK_FloatingToFixedPoint:
950b60736ecSDimitry Andric case CK_FixedPointToFloating:
951676fbe81SDimitry Andric case CK_FixedPointCast:
952676fbe81SDimitry Andric case CK_FixedPointToBoolean:
95322989816SDimitry Andric case CK_FixedPointToIntegral:
95422989816SDimitry Andric case CK_IntegralToFixedPoint:
955bca07a45SDimitry Andric llvm_unreachable("cast kind invalid for aggregate types");
9564c8b2481SRoman Divacky }
957ec2b103cSEd Schouten }
958ec2b103cSEd Schouten
VisitCallExpr(const CallExpr * E)959ec2b103cSEd Schouten void AggExprEmitter::VisitCallExpr(const CallExpr *E) {
9605e20cdd8SDimitry Andric if (E->getCallReturnType(CGF.getContext())->isReferenceType()) {
961ec2b103cSEd Schouten EmitAggLoadOfLValue(E);
962ec2b103cSEd Schouten return;
963ec2b103cSEd Schouten }
964ec2b103cSEd Schouten
96548675466SDimitry Andric withReturnValueSlot(E, [&](ReturnValueSlot Slot) {
96648675466SDimitry Andric return CGF.EmitCallExpr(E, Slot);
96748675466SDimitry Andric });
968ec2b103cSEd Schouten }
969ec2b103cSEd Schouten
VisitObjCMessageExpr(ObjCMessageExpr * E)970ec2b103cSEd Schouten void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
97148675466SDimitry Andric withReturnValueSlot(E, [&](ReturnValueSlot Slot) {
97248675466SDimitry Andric return CGF.EmitObjCMessageExpr(E, Slot);
97348675466SDimitry Andric });
974ec2b103cSEd Schouten }
975ec2b103cSEd Schouten
VisitBinComma(const BinaryOperator * E)976ec2b103cSEd Schouten void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {
977bca07a45SDimitry Andric CGF.EmitIgnoredExpr(E->getLHS());
978bca07a45SDimitry Andric Visit(E->getRHS());
9794c8b2481SRoman Divacky }
9804c8b2481SRoman Divacky
VisitStmtExpr(const StmtExpr * E)981ec2b103cSEd Schouten void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
982bca07a45SDimitry Andric CodeGenFunction::StmtExprEvaluation eval(CGF);
983bca07a45SDimitry Andric CGF.EmitCompoundStmt(*E->getSubStmt(), true, Dest);
984ec2b103cSEd Schouten }
985ec2b103cSEd Schouten
98648675466SDimitry Andric enum CompareKind {
98748675466SDimitry Andric CK_Less,
98848675466SDimitry Andric CK_Greater,
98948675466SDimitry Andric CK_Equal,
99048675466SDimitry Andric };
99148675466SDimitry Andric
EmitCompare(CGBuilderTy & Builder,CodeGenFunction & CGF,const BinaryOperator * E,llvm::Value * LHS,llvm::Value * RHS,CompareKind Kind,const char * NameSuffix="")99248675466SDimitry Andric static llvm::Value *EmitCompare(CGBuilderTy &Builder, CodeGenFunction &CGF,
99348675466SDimitry Andric const BinaryOperator *E, llvm::Value *LHS,
99448675466SDimitry Andric llvm::Value *RHS, CompareKind Kind,
99548675466SDimitry Andric const char *NameSuffix = "") {
99648675466SDimitry Andric QualType ArgTy = E->getLHS()->getType();
99748675466SDimitry Andric if (const ComplexType *CT = ArgTy->getAs<ComplexType>())
99848675466SDimitry Andric ArgTy = CT->getElementType();
99948675466SDimitry Andric
100048675466SDimitry Andric if (const auto *MPT = ArgTy->getAs<MemberPointerType>()) {
100148675466SDimitry Andric assert(Kind == CK_Equal &&
100248675466SDimitry Andric "member pointers may only be compared for equality");
100348675466SDimitry Andric return CGF.CGM.getCXXABI().EmitMemberPointerComparison(
100448675466SDimitry Andric CGF, LHS, RHS, MPT, /*IsInequality*/ false);
100548675466SDimitry Andric }
100648675466SDimitry Andric
100748675466SDimitry Andric // Compute the comparison instructions for the specified comparison kind.
100848675466SDimitry Andric struct CmpInstInfo {
100948675466SDimitry Andric const char *Name;
101048675466SDimitry Andric llvm::CmpInst::Predicate FCmp;
101148675466SDimitry Andric llvm::CmpInst::Predicate SCmp;
101248675466SDimitry Andric llvm::CmpInst::Predicate UCmp;
101348675466SDimitry Andric };
101448675466SDimitry Andric CmpInstInfo InstInfo = [&]() -> CmpInstInfo {
101548675466SDimitry Andric using FI = llvm::FCmpInst;
101648675466SDimitry Andric using II = llvm::ICmpInst;
101748675466SDimitry Andric switch (Kind) {
101848675466SDimitry Andric case CK_Less:
101948675466SDimitry Andric return {"cmp.lt", FI::FCMP_OLT, II::ICMP_SLT, II::ICMP_ULT};
102048675466SDimitry Andric case CK_Greater:
102148675466SDimitry Andric return {"cmp.gt", FI::FCMP_OGT, II::ICMP_SGT, II::ICMP_UGT};
102248675466SDimitry Andric case CK_Equal:
102348675466SDimitry Andric return {"cmp.eq", FI::FCMP_OEQ, II::ICMP_EQ, II::ICMP_EQ};
102448675466SDimitry Andric }
102548675466SDimitry Andric llvm_unreachable("Unrecognised CompareKind enum");
102648675466SDimitry Andric }();
102748675466SDimitry Andric
102848675466SDimitry Andric if (ArgTy->hasFloatingRepresentation())
102948675466SDimitry Andric return Builder.CreateFCmp(InstInfo.FCmp, LHS, RHS,
103048675466SDimitry Andric llvm::Twine(InstInfo.Name) + NameSuffix);
103148675466SDimitry Andric if (ArgTy->isIntegralOrEnumerationType() || ArgTy->isPointerType()) {
103248675466SDimitry Andric auto Inst =
103348675466SDimitry Andric ArgTy->hasSignedIntegerRepresentation() ? InstInfo.SCmp : InstInfo.UCmp;
103448675466SDimitry Andric return Builder.CreateICmp(Inst, LHS, RHS,
103548675466SDimitry Andric llvm::Twine(InstInfo.Name) + NameSuffix);
103648675466SDimitry Andric }
103748675466SDimitry Andric
103848675466SDimitry Andric llvm_unreachable("unsupported aggregate binary expression should have "
103948675466SDimitry Andric "already been handled");
104048675466SDimitry Andric }
104148675466SDimitry Andric
VisitBinCmp(const BinaryOperator * E)104248675466SDimitry Andric void AggExprEmitter::VisitBinCmp(const BinaryOperator *E) {
104348675466SDimitry Andric using llvm::BasicBlock;
104448675466SDimitry Andric using llvm::PHINode;
104548675466SDimitry Andric using llvm::Value;
104648675466SDimitry Andric assert(CGF.getContext().hasSameType(E->getLHS()->getType(),
104748675466SDimitry Andric E->getRHS()->getType()));
104848675466SDimitry Andric const ComparisonCategoryInfo &CmpInfo =
104948675466SDimitry Andric CGF.getContext().CompCategories.getInfoForType(E->getType());
105048675466SDimitry Andric assert(CmpInfo.Record->isTriviallyCopyable() &&
105148675466SDimitry Andric "cannot copy non-trivially copyable aggregate");
105248675466SDimitry Andric
105348675466SDimitry Andric QualType ArgTy = E->getLHS()->getType();
105448675466SDimitry Andric
105548675466SDimitry Andric if (!ArgTy->isIntegralOrEnumerationType() && !ArgTy->isRealFloatingType() &&
105648675466SDimitry Andric !ArgTy->isNullPtrType() && !ArgTy->isPointerType() &&
105748675466SDimitry Andric !ArgTy->isMemberPointerType() && !ArgTy->isAnyComplexType()) {
105848675466SDimitry Andric return CGF.ErrorUnsupported(E, "aggregate three-way comparison");
105948675466SDimitry Andric }
106048675466SDimitry Andric bool IsComplex = ArgTy->isAnyComplexType();
106148675466SDimitry Andric
106248675466SDimitry Andric // Evaluate the operands to the expression and extract their values.
106348675466SDimitry Andric auto EmitOperand = [&](Expr *E) -> std::pair<Value *, Value *> {
106448675466SDimitry Andric RValue RV = CGF.EmitAnyExpr(E);
106548675466SDimitry Andric if (RV.isScalar())
106648675466SDimitry Andric return {RV.getScalarVal(), nullptr};
106748675466SDimitry Andric if (RV.isAggregate())
1068ac9a064cSDimitry Andric return {RV.getAggregatePointer(E->getType(), CGF), nullptr};
106948675466SDimitry Andric assert(RV.isComplex());
107048675466SDimitry Andric return RV.getComplexVal();
107148675466SDimitry Andric };
107248675466SDimitry Andric auto LHSValues = EmitOperand(E->getLHS()),
107348675466SDimitry Andric RHSValues = EmitOperand(E->getRHS());
107448675466SDimitry Andric
107548675466SDimitry Andric auto EmitCmp = [&](CompareKind K) {
107648675466SDimitry Andric Value *Cmp = EmitCompare(Builder, CGF, E, LHSValues.first, RHSValues.first,
107748675466SDimitry Andric K, IsComplex ? ".r" : "");
107848675466SDimitry Andric if (!IsComplex)
107948675466SDimitry Andric return Cmp;
108048675466SDimitry Andric assert(K == CompareKind::CK_Equal);
108148675466SDimitry Andric Value *CmpImag = EmitCompare(Builder, CGF, E, LHSValues.second,
108248675466SDimitry Andric RHSValues.second, K, ".i");
108348675466SDimitry Andric return Builder.CreateAnd(Cmp, CmpImag, "and.eq");
108448675466SDimitry Andric };
108548675466SDimitry Andric auto EmitCmpRes = [&](const ComparisonCategoryInfo::ValueInfo *VInfo) {
108648675466SDimitry Andric return Builder.getInt(VInfo->getIntValue());
108748675466SDimitry Andric };
108848675466SDimitry Andric
108948675466SDimitry Andric Value *Select;
109048675466SDimitry Andric if (ArgTy->isNullPtrType()) {
109148675466SDimitry Andric Select = EmitCmpRes(CmpInfo.getEqualOrEquiv());
109248675466SDimitry Andric } else if (!CmpInfo.isPartial()) {
109348675466SDimitry Andric Value *SelectOne =
109448675466SDimitry Andric Builder.CreateSelect(EmitCmp(CK_Less), EmitCmpRes(CmpInfo.getLess()),
109548675466SDimitry Andric EmitCmpRes(CmpInfo.getGreater()), "sel.lt");
109648675466SDimitry Andric Select = Builder.CreateSelect(EmitCmp(CK_Equal),
109748675466SDimitry Andric EmitCmpRes(CmpInfo.getEqualOrEquiv()),
109848675466SDimitry Andric SelectOne, "sel.eq");
109948675466SDimitry Andric } else {
110048675466SDimitry Andric Value *SelectEq = Builder.CreateSelect(
110148675466SDimitry Andric EmitCmp(CK_Equal), EmitCmpRes(CmpInfo.getEqualOrEquiv()),
110248675466SDimitry Andric EmitCmpRes(CmpInfo.getUnordered()), "sel.eq");
110348675466SDimitry Andric Value *SelectGT = Builder.CreateSelect(EmitCmp(CK_Greater),
110448675466SDimitry Andric EmitCmpRes(CmpInfo.getGreater()),
110548675466SDimitry Andric SelectEq, "sel.gt");
110648675466SDimitry Andric Select = Builder.CreateSelect(
110748675466SDimitry Andric EmitCmp(CK_Less), EmitCmpRes(CmpInfo.getLess()), SelectGT, "sel.lt");
110848675466SDimitry Andric }
110948675466SDimitry Andric // Create the return value in the destination slot.
111048675466SDimitry Andric EnsureDest(E->getType());
111148675466SDimitry Andric LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType());
111248675466SDimitry Andric
111348675466SDimitry Andric // Emit the address of the first (and only) field in the comparison category
111448675466SDimitry Andric // type, and initialize it from the constant integer value selected above.
111548675466SDimitry Andric LValue FieldLV = CGF.EmitLValueForFieldInitialization(
111648675466SDimitry Andric DestLV, *CmpInfo.Record->field_begin());
111748675466SDimitry Andric CGF.EmitStoreThroughLValue(RValue::get(Select), FieldLV, /*IsInit*/ true);
111848675466SDimitry Andric
111948675466SDimitry Andric // All done! The result is in the Dest slot.
112048675466SDimitry Andric }
112148675466SDimitry Andric
VisitBinaryOperator(const BinaryOperator * E)1122ec2b103cSEd Schouten void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
11233d1dcd9bSDimitry Andric if (E->getOpcode() == BO_PtrMemD || E->getOpcode() == BO_PtrMemI)
112473490b89SRoman Divacky VisitPointerToDataMemberBinaryOperator(E);
112573490b89SRoman Divacky else
1126ec2b103cSEd Schouten CGF.ErrorUnsupported(E, "aggregate binary expression");
1127ec2b103cSEd Schouten }
1128ec2b103cSEd Schouten
VisitPointerToDataMemberBinaryOperator(const BinaryOperator * E)112973490b89SRoman Divacky void AggExprEmitter::VisitPointerToDataMemberBinaryOperator(
113073490b89SRoman Divacky const BinaryOperator *E) {
113173490b89SRoman Divacky LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E);
113256d91b49SDimitry Andric EmitFinalDestCopy(E->getType(), LV);
113356d91b49SDimitry Andric }
113456d91b49SDimitry Andric
113556d91b49SDimitry Andric /// Is the value of the given expression possibly a reference to or
113656d91b49SDimitry Andric /// into a __block variable?
isBlockVarRef(const Expr * E)113756d91b49SDimitry Andric static bool isBlockVarRef(const Expr *E) {
113856d91b49SDimitry Andric // Make sure we look through parens.
113956d91b49SDimitry Andric E = E->IgnoreParens();
114056d91b49SDimitry Andric
114156d91b49SDimitry Andric // Check for a direct reference to a __block variable.
114256d91b49SDimitry Andric if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
114356d91b49SDimitry Andric const VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
114456d91b49SDimitry Andric return (var && var->hasAttr<BlocksAttr>());
114556d91b49SDimitry Andric }
114656d91b49SDimitry Andric
114756d91b49SDimitry Andric // More complicated stuff.
114856d91b49SDimitry Andric
114956d91b49SDimitry Andric // Binary operators.
115056d91b49SDimitry Andric if (const BinaryOperator *op = dyn_cast<BinaryOperator>(E)) {
115156d91b49SDimitry Andric // For an assignment or pointer-to-member operation, just care
115256d91b49SDimitry Andric // about the LHS.
115356d91b49SDimitry Andric if (op->isAssignmentOp() || op->isPtrMemOp())
115456d91b49SDimitry Andric return isBlockVarRef(op->getLHS());
115556d91b49SDimitry Andric
115656d91b49SDimitry Andric // For a comma, just care about the RHS.
115756d91b49SDimitry Andric if (op->getOpcode() == BO_Comma)
115856d91b49SDimitry Andric return isBlockVarRef(op->getRHS());
115956d91b49SDimitry Andric
116056d91b49SDimitry Andric // FIXME: pointer arithmetic?
116156d91b49SDimitry Andric return false;
116256d91b49SDimitry Andric
116356d91b49SDimitry Andric // Check both sides of a conditional operator.
116456d91b49SDimitry Andric } else if (const AbstractConditionalOperator *op
116556d91b49SDimitry Andric = dyn_cast<AbstractConditionalOperator>(E)) {
116656d91b49SDimitry Andric return isBlockVarRef(op->getTrueExpr())
116756d91b49SDimitry Andric || isBlockVarRef(op->getFalseExpr());
116856d91b49SDimitry Andric
116956d91b49SDimitry Andric // OVEs are required to support BinaryConditionalOperators.
117056d91b49SDimitry Andric } else if (const OpaqueValueExpr *op
117156d91b49SDimitry Andric = dyn_cast<OpaqueValueExpr>(E)) {
117256d91b49SDimitry Andric if (const Expr *src = op->getSourceExpr())
117356d91b49SDimitry Andric return isBlockVarRef(src);
117456d91b49SDimitry Andric
117556d91b49SDimitry Andric // Casts are necessary to get things like (*(int*)&var) = foo().
117656d91b49SDimitry Andric // We don't really care about the kind of cast here, except
117756d91b49SDimitry Andric // we don't want to look through l2r casts, because it's okay
117856d91b49SDimitry Andric // to get the *value* in a __block variable.
117956d91b49SDimitry Andric } else if (const CastExpr *cast = dyn_cast<CastExpr>(E)) {
118056d91b49SDimitry Andric if (cast->getCastKind() == CK_LValueToRValue)
118156d91b49SDimitry Andric return false;
118256d91b49SDimitry Andric return isBlockVarRef(cast->getSubExpr());
118356d91b49SDimitry Andric
118456d91b49SDimitry Andric // Handle unary operators. Again, just aggressively look through
118556d91b49SDimitry Andric // it, ignoring the operation.
118656d91b49SDimitry Andric } else if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E)) {
118756d91b49SDimitry Andric return isBlockVarRef(uop->getSubExpr());
118856d91b49SDimitry Andric
118956d91b49SDimitry Andric // Look into the base of a field access.
119056d91b49SDimitry Andric } else if (const MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
119156d91b49SDimitry Andric return isBlockVarRef(mem->getBase());
119256d91b49SDimitry Andric
119356d91b49SDimitry Andric // Look into the base of a subscript.
119456d91b49SDimitry Andric } else if (const ArraySubscriptExpr *sub = dyn_cast<ArraySubscriptExpr>(E)) {
119556d91b49SDimitry Andric return isBlockVarRef(sub->getBase());
119656d91b49SDimitry Andric }
119756d91b49SDimitry Andric
119856d91b49SDimitry Andric return false;
119973490b89SRoman Divacky }
120073490b89SRoman Divacky
VisitBinAssign(const BinaryOperator * E)1201ec2b103cSEd Schouten void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
1202ec2b103cSEd Schouten // For an assignment to work, the value on the right has
1203ec2b103cSEd Schouten // to be compatible with the value on the left.
1204ec2b103cSEd Schouten assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
1205ec2b103cSEd Schouten E->getRHS()->getType())
1206ec2b103cSEd Schouten && "Invalid assignment");
1207bca07a45SDimitry Andric
120856d91b49SDimitry Andric // If the LHS might be a __block variable, and the RHS can
120956d91b49SDimitry Andric // potentially cause a block copy, we need to evaluate the RHS first
121056d91b49SDimitry Andric // so that the assignment goes the right place.
121156d91b49SDimitry Andric // This is pretty semantically fragile.
121256d91b49SDimitry Andric if (isBlockVarRef(E->getLHS()) &&
121301af97d3SDimitry Andric E->getRHS()->HasSideEffects(CGF.getContext())) {
121456d91b49SDimitry Andric // Ensure that we have a destination, and evaluate the RHS into that.
121556d91b49SDimitry Andric EnsureDest(E->getRHS()->getType());
121656d91b49SDimitry Andric Visit(E->getRHS());
121756d91b49SDimitry Andric
121856d91b49SDimitry Andric // Now emit the LHS and copy into it.
121913cc256eSDimitry Andric LValue LHS = CGF.EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
122056d91b49SDimitry Andric
1221809500fcSDimitry Andric // That copy is an atomic copy if the LHS is atomic.
12225e20cdd8SDimitry Andric if (LHS.getType()->isAtomicType() ||
12235e20cdd8SDimitry Andric CGF.LValueIsSuitableForInlineAtomic(LHS)) {
1224809500fcSDimitry Andric CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false);
1225809500fcSDimitry Andric return;
1226809500fcSDimitry Andric }
1227809500fcSDimitry Andric
122856d91b49SDimitry Andric EmitCopy(E->getLHS()->getType(),
1229ac9a064cSDimitry Andric AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed,
123036981b17SDimitry Andric needsGC(E->getLHS()->getType()),
123148675466SDimitry Andric AggValueSlot::IsAliased,
123248675466SDimitry Andric AggValueSlot::MayOverlap),
123356d91b49SDimitry Andric Dest);
123401af97d3SDimitry Andric return;
123501af97d3SDimitry Andric }
123601af97d3SDimitry Andric
1237ec2b103cSEd Schouten LValue LHS = CGF.EmitLValue(E->getLHS());
1238ec2b103cSEd Schouten
1239809500fcSDimitry Andric // If we have an atomic type, evaluate into the destination and then
1240809500fcSDimitry Andric // do an atomic copy.
12415e20cdd8SDimitry Andric if (LHS.getType()->isAtomicType() ||
12425e20cdd8SDimitry Andric CGF.LValueIsSuitableForInlineAtomic(LHS)) {
1243809500fcSDimitry Andric EnsureDest(E->getRHS()->getType());
1244809500fcSDimitry Andric Visit(E->getRHS());
1245809500fcSDimitry Andric CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false);
1246809500fcSDimitry Andric return;
1247809500fcSDimitry Andric }
1248809500fcSDimitry Andric
1249ec2b103cSEd Schouten // Codegen the RHS so that it stores directly into the LHS.
1250706b4fc4SDimitry Andric AggValueSlot LHSSlot = AggValueSlot::forLValue(
1251ac9a064cSDimitry Andric LHS, AggValueSlot::IsDestructed, needsGC(E->getLHS()->getType()),
1252706b4fc4SDimitry Andric AggValueSlot::IsAliased, AggValueSlot::MayOverlap);
1253809500fcSDimitry Andric // A non-volatile aggregate destination might have volatile member.
1254809500fcSDimitry Andric if (!LHSSlot.isVolatile() &&
1255809500fcSDimitry Andric CGF.hasVolatileMember(E->getLHS()->getType()))
1256809500fcSDimitry Andric LHSSlot.setVolatile(true);
1257809500fcSDimitry Andric
125856d91b49SDimitry Andric CGF.EmitAggExpr(E->getRHS(), LHSSlot);
125956d91b49SDimitry Andric
126056d91b49SDimitry Andric // Copy into the destination if the assignment isn't ignored.
126156d91b49SDimitry Andric EmitFinalDestCopy(E->getType(), LHS);
1262b60736ecSDimitry Andric
1263b60736ecSDimitry Andric if (!Dest.isIgnored() && !Dest.isExternallyDestructed() &&
1264b60736ecSDimitry Andric E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
1265b60736ecSDimitry Andric CGF.pushDestroy(QualType::DK_nontrivial_c_struct, Dest.getAddress(),
1266b60736ecSDimitry Andric E->getType());
1267ec2b103cSEd Schouten }
1268ec2b103cSEd Schouten
1269bca07a45SDimitry Andric void AggExprEmitter::
VisitAbstractConditionalOperator(const AbstractConditionalOperator * E)1270bca07a45SDimitry Andric VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
1271ec2b103cSEd Schouten llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
1272ec2b103cSEd Schouten llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
1273ec2b103cSEd Schouten llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
1274ec2b103cSEd Schouten
1275bca07a45SDimitry Andric // Bind the common expression if necessary.
1276bca07a45SDimitry Andric CodeGenFunction::OpaqueValueMapping binding(CGF, E);
1277bca07a45SDimitry Andric
1278bca07a45SDimitry Andric CodeGenFunction::ConditionalEvaluation eval(CGF);
12795e20cdd8SDimitry Andric CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock,
12805e20cdd8SDimitry Andric CGF.getProfileCount(E));
1281ec2b103cSEd Schouten
1282bca07a45SDimitry Andric // Save whether the destination's lifetime is externally managed.
128336981b17SDimitry Andric bool isExternallyDestructed = Dest.isExternallyDestructed();
1284b60736ecSDimitry Andric bool destructNonTrivialCStruct =
1285b60736ecSDimitry Andric !isExternallyDestructed &&
1286b60736ecSDimitry Andric E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct;
1287b60736ecSDimitry Andric isExternallyDestructed |= destructNonTrivialCStruct;
1288b60736ecSDimitry Andric Dest.setExternallyDestructed(isExternallyDestructed);
1289bca07a45SDimitry Andric
1290bca07a45SDimitry Andric eval.begin(CGF);
1291ec2b103cSEd Schouten CGF.EmitBlock(LHSBlock);
1292ac9a064cSDimitry Andric if (llvm::EnableSingleByteCoverage)
1293ac9a064cSDimitry Andric CGF.incrementProfileCounter(E->getTrueExpr());
1294ac9a064cSDimitry Andric else
12955e20cdd8SDimitry Andric CGF.incrementProfileCounter(E);
1296bca07a45SDimitry Andric Visit(E->getTrueExpr());
1297bca07a45SDimitry Andric eval.end(CGF);
1298ec2b103cSEd Schouten
1299bca07a45SDimitry Andric assert(CGF.HaveInsertPoint() && "expression evaluation ended with no IP!");
1300bca07a45SDimitry Andric CGF.Builder.CreateBr(ContBlock);
1301ec2b103cSEd Schouten
1302bca07a45SDimitry Andric // If the result of an agg expression is unused, then the emission
1303bca07a45SDimitry Andric // of the LHS might need to create a destination slot. That's fine
1304bca07a45SDimitry Andric // with us, and we can safely emit the RHS into the same slot, but
130536981b17SDimitry Andric // we shouldn't claim that it's already being destructed.
130636981b17SDimitry Andric Dest.setExternallyDestructed(isExternallyDestructed);
1307ec2b103cSEd Schouten
1308bca07a45SDimitry Andric eval.begin(CGF);
1309ec2b103cSEd Schouten CGF.EmitBlock(RHSBlock);
1310ac9a064cSDimitry Andric if (llvm::EnableSingleByteCoverage)
1311ac9a064cSDimitry Andric CGF.incrementProfileCounter(E->getFalseExpr());
1312bca07a45SDimitry Andric Visit(E->getFalseExpr());
1313bca07a45SDimitry Andric eval.end(CGF);
1314ec2b103cSEd Schouten
1315b60736ecSDimitry Andric if (destructNonTrivialCStruct)
1316b60736ecSDimitry Andric CGF.pushDestroy(QualType::DK_nontrivial_c_struct, Dest.getAddress(),
1317b60736ecSDimitry Andric E->getType());
1318b60736ecSDimitry Andric
1319ec2b103cSEd Schouten CGF.EmitBlock(ContBlock);
1320ac9a064cSDimitry Andric if (llvm::EnableSingleByteCoverage)
1321ac9a064cSDimitry Andric CGF.incrementProfileCounter(E);
1322ec2b103cSEd Schouten }
1323ec2b103cSEd Schouten
VisitChooseExpr(const ChooseExpr * CE)13244c8b2481SRoman Divacky void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) {
1325bfef3995SDimitry Andric Visit(CE->getChosenSubExpr());
13264c8b2481SRoman Divacky }
13274c8b2481SRoman Divacky
VisitVAArgExpr(VAArgExpr * VE)1328ec2b103cSEd Schouten void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
132945b53394SDimitry Andric Address ArgValue = Address::invalid();
1330ac9a064cSDimitry Andric CGF.EmitVAArg(VE, ArgValue, Dest);
1331ec2b103cSEd Schouten
13322b6b257fSDimitry Andric // If EmitVAArg fails, emit an error.
1333ac9a064cSDimitry Andric if (!ArgValue.isValid()) {
13342b6b257fSDimitry Andric CGF.ErrorUnsupported(VE, "aggregate va_arg expression");
1335ec2b103cSEd Schouten return;
1336ec2b103cSEd Schouten }
1337ec2b103cSEd Schouten }
1338ec2b103cSEd Schouten
VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr * E)1339ec2b103cSEd Schouten void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
1340bca07a45SDimitry Andric // Ensure that we have a slot, but if we already do, remember
134136981b17SDimitry Andric // whether it was externally destructed.
134236981b17SDimitry Andric bool wasExternallyDestructed = Dest.isExternallyDestructed();
134356d91b49SDimitry Andric EnsureDest(E->getType());
134436981b17SDimitry Andric
134536981b17SDimitry Andric // We're going to push a destructor if there isn't already one.
134636981b17SDimitry Andric Dest.setExternallyDestructed();
1347ec2b103cSEd Schouten
1348ec2b103cSEd Schouten Visit(E->getSubExpr());
1349ec2b103cSEd Schouten
135036981b17SDimitry Andric // Push that destructor we promised.
135136981b17SDimitry Andric if (!wasExternallyDestructed)
135245b53394SDimitry Andric CGF.EmitCXXTemporary(E->getTemporary(), E->getType(), Dest.getAddress());
1353ec2b103cSEd Schouten }
1354ec2b103cSEd Schouten
1355ec2b103cSEd Schouten void
VisitCXXConstructExpr(const CXXConstructExpr * E)1356ec2b103cSEd Schouten AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) {
1357bca07a45SDimitry Andric AggValueSlot Slot = EnsureSlot(E->getType());
1358bca07a45SDimitry Andric CGF.EmitCXXConstructExpr(E, Slot);
1359ec2b103cSEd Schouten }
1360ec2b103cSEd Schouten
VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr * E)13612b6b257fSDimitry Andric void AggExprEmitter::VisitCXXInheritedCtorInitExpr(
13622b6b257fSDimitry Andric const CXXInheritedCtorInitExpr *E) {
13632b6b257fSDimitry Andric AggValueSlot Slot = EnsureSlot(E->getType());
13642b6b257fSDimitry Andric CGF.EmitInheritedCXXConstructorCall(
13652b6b257fSDimitry Andric E->getConstructor(), E->constructsVBase(), Slot.getAddress(),
13662b6b257fSDimitry Andric E->inheritedFromVBase(), E);
13672b6b257fSDimitry Andric }
13682b6b257fSDimitry Andric
1369dbe13110SDimitry Andric void
VisitLambdaExpr(LambdaExpr * E)1370dbe13110SDimitry Andric AggExprEmitter::VisitLambdaExpr(LambdaExpr *E) {
1371dbe13110SDimitry Andric AggValueSlot Slot = EnsureSlot(E->getType());
137222989816SDimitry Andric LValue SlotLV = CGF.MakeAddrLValue(Slot.getAddress(), E->getType());
137322989816SDimitry Andric
137422989816SDimitry Andric // We'll need to enter cleanup scopes in case any of the element
1375ac9a064cSDimitry Andric // initializers throws an exception or contains branch out of the expressions.
1376ac9a064cSDimitry Andric CodeGenFunction::CleanupDeactivationScope scope(CGF);
137722989816SDimitry Andric
137822989816SDimitry Andric CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
137922989816SDimitry Andric for (LambdaExpr::const_capture_init_iterator i = E->capture_init_begin(),
138022989816SDimitry Andric e = E->capture_init_end();
138122989816SDimitry Andric i != e; ++i, ++CurField) {
138222989816SDimitry Andric // Emit initialization
138322989816SDimitry Andric LValue LV = CGF.EmitLValueForFieldInitialization(SlotLV, *CurField);
138422989816SDimitry Andric if (CurField->hasCapturedVLAType()) {
138522989816SDimitry Andric CGF.EmitLambdaVLACapture(CurField->getCapturedVLAType(), LV);
138622989816SDimitry Andric continue;
138722989816SDimitry Andric }
138822989816SDimitry Andric
138922989816SDimitry Andric EmitInitializationToLValue(*i, LV);
139022989816SDimitry Andric
139122989816SDimitry Andric // Push a destructor if necessary.
139222989816SDimitry Andric if (QualType::DestructionKind DtorKind =
139322989816SDimitry Andric CurField->getType().isDestructedType()) {
139422989816SDimitry Andric assert(LV.isSimple());
1395ac9a064cSDimitry Andric if (DtorKind)
1396ac9a064cSDimitry Andric CGF.pushDestroyAndDeferDeactivation(NormalAndEHCleanup, LV.getAddress(),
1397ac9a064cSDimitry Andric CurField->getType(),
139822989816SDimitry Andric CGF.getDestroyer(DtorKind), false);
139922989816SDimitry Andric }
140022989816SDimitry Andric }
140122989816SDimitry Andric }
140222989816SDimitry Andric
VisitExprWithCleanups(ExprWithCleanups * E)1403bca07a45SDimitry Andric void AggExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
1404dbe13110SDimitry Andric CodeGenFunction::RunCleanupsScope cleanups(CGF);
1405dbe13110SDimitry Andric Visit(E->getSubExpr());
1406ec2b103cSEd Schouten }
1407ec2b103cSEd Schouten
VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr * E)14084ba67500SRoman Divacky void AggExprEmitter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1409bca07a45SDimitry Andric QualType T = E->getType();
1410bca07a45SDimitry Andric AggValueSlot Slot = EnsureSlot(T);
141145b53394SDimitry Andric EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddress(), T));
1412abe15e55SRoman Divacky }
1413abe15e55SRoman Divacky
VisitImplicitValueInitExpr(ImplicitValueInitExpr * E)1414abe15e55SRoman Divacky void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
1415bca07a45SDimitry Andric QualType T = E->getType();
1416bca07a45SDimitry Andric AggValueSlot Slot = EnsureSlot(T);
141745b53394SDimitry Andric EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddress(), T));
1418bca07a45SDimitry Andric }
1419abe15e55SRoman Divacky
1420b60736ecSDimitry Andric /// Determine whether the given cast kind is known to always convert values
1421b60736ecSDimitry Andric /// with all zero bits in their value representation to values with all zero
1422b60736ecSDimitry Andric /// bits in their value representation.
castPreservesZero(const CastExpr * CE)1423b60736ecSDimitry Andric static bool castPreservesZero(const CastExpr *CE) {
1424b60736ecSDimitry Andric switch (CE->getCastKind()) {
1425b60736ecSDimitry Andric // No-ops.
1426b60736ecSDimitry Andric case CK_NoOp:
1427b60736ecSDimitry Andric case CK_UserDefinedConversion:
1428b60736ecSDimitry Andric case CK_ConstructorConversion:
1429b60736ecSDimitry Andric case CK_BitCast:
1430b60736ecSDimitry Andric case CK_ToUnion:
1431b60736ecSDimitry Andric case CK_ToVoid:
1432b60736ecSDimitry Andric // Conversions between (possibly-complex) integral, (possibly-complex)
1433b60736ecSDimitry Andric // floating-point, and bool.
1434b60736ecSDimitry Andric case CK_BooleanToSignedIntegral:
1435b60736ecSDimitry Andric case CK_FloatingCast:
1436b60736ecSDimitry Andric case CK_FloatingComplexCast:
1437b60736ecSDimitry Andric case CK_FloatingComplexToBoolean:
1438b60736ecSDimitry Andric case CK_FloatingComplexToIntegralComplex:
1439b60736ecSDimitry Andric case CK_FloatingComplexToReal:
1440b60736ecSDimitry Andric case CK_FloatingRealToComplex:
1441b60736ecSDimitry Andric case CK_FloatingToBoolean:
1442b60736ecSDimitry Andric case CK_FloatingToIntegral:
1443b60736ecSDimitry Andric case CK_IntegralCast:
1444b60736ecSDimitry Andric case CK_IntegralComplexCast:
1445b60736ecSDimitry Andric case CK_IntegralComplexToBoolean:
1446b60736ecSDimitry Andric case CK_IntegralComplexToFloatingComplex:
1447b60736ecSDimitry Andric case CK_IntegralComplexToReal:
1448b60736ecSDimitry Andric case CK_IntegralRealToComplex:
1449b60736ecSDimitry Andric case CK_IntegralToBoolean:
1450b60736ecSDimitry Andric case CK_IntegralToFloating:
1451b60736ecSDimitry Andric // Reinterpreting integers as pointers and vice versa.
1452b60736ecSDimitry Andric case CK_IntegralToPointer:
1453b60736ecSDimitry Andric case CK_PointerToIntegral:
1454b60736ecSDimitry Andric // Language extensions.
1455b60736ecSDimitry Andric case CK_VectorSplat:
1456344a3780SDimitry Andric case CK_MatrixCast:
1457b60736ecSDimitry Andric case CK_NonAtomicToAtomic:
1458b60736ecSDimitry Andric case CK_AtomicToNonAtomic:
1459ac9a064cSDimitry Andric case CK_HLSLVectorTruncation:
1460b60736ecSDimitry Andric return true;
1461b60736ecSDimitry Andric
1462b60736ecSDimitry Andric case CK_BaseToDerivedMemberPointer:
1463b60736ecSDimitry Andric case CK_DerivedToBaseMemberPointer:
1464b60736ecSDimitry Andric case CK_MemberPointerToBoolean:
1465b60736ecSDimitry Andric case CK_NullToMemberPointer:
1466b60736ecSDimitry Andric case CK_ReinterpretMemberPointer:
1467b60736ecSDimitry Andric // FIXME: ABI-dependent.
1468b60736ecSDimitry Andric return false;
1469b60736ecSDimitry Andric
1470b60736ecSDimitry Andric case CK_AnyPointerToBlockPointerCast:
1471b60736ecSDimitry Andric case CK_BlockPointerToObjCPointerCast:
1472b60736ecSDimitry Andric case CK_CPointerToObjCPointerCast:
1473b60736ecSDimitry Andric case CK_ObjCObjectLValueCast:
1474b60736ecSDimitry Andric case CK_IntToOCLSampler:
1475b60736ecSDimitry Andric case CK_ZeroToOCLOpaqueType:
1476b60736ecSDimitry Andric // FIXME: Check these.
1477b60736ecSDimitry Andric return false;
1478b60736ecSDimitry Andric
1479b60736ecSDimitry Andric case CK_FixedPointCast:
1480b60736ecSDimitry Andric case CK_FixedPointToBoolean:
1481b60736ecSDimitry Andric case CK_FixedPointToFloating:
1482b60736ecSDimitry Andric case CK_FixedPointToIntegral:
1483b60736ecSDimitry Andric case CK_FloatingToFixedPoint:
1484b60736ecSDimitry Andric case CK_IntegralToFixedPoint:
1485b60736ecSDimitry Andric // FIXME: Do all fixed-point types represent zero as all 0 bits?
1486b60736ecSDimitry Andric return false;
1487b60736ecSDimitry Andric
1488b60736ecSDimitry Andric case CK_AddressSpaceConversion:
1489b60736ecSDimitry Andric case CK_BaseToDerived:
1490b60736ecSDimitry Andric case CK_DerivedToBase:
1491b60736ecSDimitry Andric case CK_Dynamic:
1492b60736ecSDimitry Andric case CK_NullToPointer:
1493b60736ecSDimitry Andric case CK_PointerToBoolean:
1494b60736ecSDimitry Andric // FIXME: Preserves zeroes only if zero pointers and null pointers have the
1495b60736ecSDimitry Andric // same representation in all involved address spaces.
1496b60736ecSDimitry Andric return false;
1497b60736ecSDimitry Andric
1498b60736ecSDimitry Andric case CK_ARCConsumeObject:
1499b60736ecSDimitry Andric case CK_ARCExtendBlockObject:
1500b60736ecSDimitry Andric case CK_ARCProduceObject:
1501b60736ecSDimitry Andric case CK_ARCReclaimReturnedObject:
1502b60736ecSDimitry Andric case CK_CopyAndAutoreleaseBlockObject:
1503b60736ecSDimitry Andric case CK_ArrayToPointerDecay:
1504b60736ecSDimitry Andric case CK_FunctionToPointerDecay:
1505b60736ecSDimitry Andric case CK_BuiltinFnToFnPtr:
1506b60736ecSDimitry Andric case CK_Dependent:
1507b60736ecSDimitry Andric case CK_LValueBitCast:
1508b60736ecSDimitry Andric case CK_LValueToRValue:
1509b60736ecSDimitry Andric case CK_LValueToRValueBitCast:
1510b60736ecSDimitry Andric case CK_UncheckedDerivedToBase:
1511ac9a064cSDimitry Andric case CK_HLSLArrayRValue:
1512b60736ecSDimitry Andric return false;
1513b60736ecSDimitry Andric }
1514b60736ecSDimitry Andric llvm_unreachable("Unhandled clang::CastKind enum");
1515b60736ecSDimitry Andric }
1516b60736ecSDimitry Andric
1517bca07a45SDimitry Andric /// isSimpleZero - If emitting this value will obviously just cause a store of
1518bca07a45SDimitry Andric /// zero to memory, return true. This can return false if uncertain, so it just
1519bca07a45SDimitry Andric /// handles simple cases.
isSimpleZero(const Expr * E,CodeGenFunction & CGF)1520bca07a45SDimitry Andric static bool isSimpleZero(const Expr *E, CodeGenFunction &CGF) {
152101af97d3SDimitry Andric E = E->IgnoreParens();
1522b60736ecSDimitry Andric while (auto *CE = dyn_cast<CastExpr>(E)) {
1523b60736ecSDimitry Andric if (!castPreservesZero(CE))
1524b60736ecSDimitry Andric break;
1525b60736ecSDimitry Andric E = CE->getSubExpr()->IgnoreParens();
1526b60736ecSDimitry Andric }
152701af97d3SDimitry Andric
1528bca07a45SDimitry Andric // 0
1529bca07a45SDimitry Andric if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E))
1530bca07a45SDimitry Andric return IL->getValue() == 0;
1531bca07a45SDimitry Andric // +0.0
1532bca07a45SDimitry Andric if (const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(E))
1533bca07a45SDimitry Andric return FL->getValue().isPosZero();
1534bca07a45SDimitry Andric // int()
1535bca07a45SDimitry Andric if ((isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) &&
1536bca07a45SDimitry Andric CGF.getTypes().isZeroInitializable(E->getType()))
1537bca07a45SDimitry Andric return true;
1538bca07a45SDimitry Andric // (int*)0 - Null pointer expressions.
1539bca07a45SDimitry Andric if (const CastExpr *ICE = dyn_cast<CastExpr>(E))
1540bab175ecSDimitry Andric return ICE->getCastKind() == CK_NullToPointer &&
154122989816SDimitry Andric CGF.getTypes().isPointerZeroInitializable(E->getType()) &&
154222989816SDimitry Andric !E->HasSideEffects(CGF.getContext());
1543bca07a45SDimitry Andric // '\0'
1544bca07a45SDimitry Andric if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E))
1545bca07a45SDimitry Andric return CL->getValue() == 0;
1546bca07a45SDimitry Andric
1547bca07a45SDimitry Andric // Otherwise, hard case: conservatively return false.
1548bca07a45SDimitry Andric return false;
1549abe15e55SRoman Divacky }
1550bca07a45SDimitry Andric
155173490b89SRoman Divacky
1552ecb7e5c8SRoman Divacky void
EmitInitializationToLValue(Expr * E,LValue LV)1553180abc3dSDimitry Andric AggExprEmitter::EmitInitializationToLValue(Expr *E, LValue LV) {
1554180abc3dSDimitry Andric QualType type = LV.getType();
1555ec2b103cSEd Schouten // FIXME: Ignore result?
1556ec2b103cSEd Schouten // FIXME: Are initializers affected by volatile?
1557bca07a45SDimitry Andric if (Dest.isZeroed() && isSimpleZero(E, CGF)) {
1558bca07a45SDimitry Andric // Storing "i32 0" to a zero'd memory location is a noop.
1559809500fcSDimitry Andric return;
1560809500fcSDimitry Andric } else if (isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) {
1561809500fcSDimitry Andric return EmitNullInitializationToLValue(LV);
15622e645aa5SDimitry Andric } else if (isa<NoInitExpr>(E)) {
15632e645aa5SDimitry Andric // Do nothing.
15642e645aa5SDimitry Andric return;
1565180abc3dSDimitry Andric } else if (type->isReferenceType()) {
1566bfef3995SDimitry Andric RValue RV = CGF.EmitReferenceBindingToExpr(E);
1567809500fcSDimitry Andric return CGF.EmitStoreThroughLValue(RV, LV);
1568809500fcSDimitry Andric }
1569809500fcSDimitry Andric
1570809500fcSDimitry Andric switch (CGF.getEvaluationKind(type)) {
1571809500fcSDimitry Andric case TEK_Complex:
1572809500fcSDimitry Andric CGF.EmitComplexExprIntoLValue(E, LV, /*isInit*/ true);
1573809500fcSDimitry Andric return;
1574809500fcSDimitry Andric case TEK_Aggregate:
1575706b4fc4SDimitry Andric CGF.EmitAggExpr(
1576ac9a064cSDimitry Andric E, AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed,
157736981b17SDimitry Andric AggValueSlot::DoesNotNeedGCBarriers,
157836981b17SDimitry Andric AggValueSlot::IsNotAliased,
1579706b4fc4SDimitry Andric AggValueSlot::MayOverlap, Dest.isZeroed()));
1580809500fcSDimitry Andric return;
1581809500fcSDimitry Andric case TEK_Scalar:
1582809500fcSDimitry Andric if (LV.isSimple()) {
15839f4dbff6SDimitry Andric CGF.EmitScalarInit(E, /*D=*/nullptr, LV, /*Captured=*/false);
1584ec2b103cSEd Schouten } else {
1585180abc3dSDimitry Andric CGF.EmitStoreThroughLValue(RValue::get(CGF.EmitScalarExpr(E)), LV);
1586ec2b103cSEd Schouten }
1587809500fcSDimitry Andric return;
1588809500fcSDimitry Andric }
1589809500fcSDimitry Andric llvm_unreachable("bad evaluation kind");
1590ec2b103cSEd Schouten }
1591ec2b103cSEd Schouten
EmitNullInitializationToLValue(LValue lv)1592180abc3dSDimitry Andric void AggExprEmitter::EmitNullInitializationToLValue(LValue lv) {
1593180abc3dSDimitry Andric QualType type = lv.getType();
1594180abc3dSDimitry Andric
1595bca07a45SDimitry Andric // If the destination slot is already zeroed out before the aggregate is
1596bca07a45SDimitry Andric // copied into it, we don't have to emit any zeros here.
1597180abc3dSDimitry Andric if (Dest.isZeroed() && CGF.getTypes().isZeroInitializable(type))
1598bca07a45SDimitry Andric return;
1599bca07a45SDimitry Andric
1600809500fcSDimitry Andric if (CGF.hasScalarEvaluationKind(type)) {
1601809500fcSDimitry Andric // For non-aggregates, we can store the appropriate null constant.
1602809500fcSDimitry Andric llvm::Value *null = CGF.CGM.EmitNullConstant(type);
1603dbe13110SDimitry Andric // Note that the following is not equivalent to
1604dbe13110SDimitry Andric // EmitStoreThroughBitfieldLValue for ARC types.
1605dbe13110SDimitry Andric if (lv.isBitField()) {
1606dbe13110SDimitry Andric CGF.EmitStoreThroughBitfieldLValue(RValue::get(null), lv);
1607dbe13110SDimitry Andric } else {
1608dbe13110SDimitry Andric assert(lv.isSimple());
1609dbe13110SDimitry Andric CGF.EmitStoreOfScalar(null, lv, /* isInitialization */ true);
1610dbe13110SDimitry Andric }
1611ec2b103cSEd Schouten } else {
1612ec2b103cSEd Schouten // There's a potential optimization opportunity in combining
1613ec2b103cSEd Schouten // memsets; that would be easy for arrays, but relatively
1614ec2b103cSEd Schouten // difficult for structures with the current code.
1615ac9a064cSDimitry Andric CGF.EmitNullInitialization(lv.getAddress(), lv.getType());
1616ec2b103cSEd Schouten }
1617ec2b103cSEd Schouten }
1618ec2b103cSEd Schouten
VisitCXXParenListInitExpr(CXXParenListInitExpr * E)1619e3b55780SDimitry Andric void AggExprEmitter::VisitCXXParenListInitExpr(CXXParenListInitExpr *E) {
1620e3b55780SDimitry Andric VisitCXXParenListOrInitListExpr(E, E->getInitExprs(),
1621e3b55780SDimitry Andric E->getInitializedFieldInUnion(),
1622e3b55780SDimitry Andric E->getArrayFiller());
1623ec2b103cSEd Schouten }
1624e3b55780SDimitry Andric
VisitInitListExpr(InitListExpr * E)1625e3b55780SDimitry Andric void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
1626bca07a45SDimitry Andric if (E->hadArrayRangeDesignator())
1627ec2b103cSEd Schouten CGF.ErrorUnsupported(E, "GNU array range designator extension");
1628bca07a45SDimitry Andric
1629bab175ecSDimitry Andric if (E->isTransparent())
1630bab175ecSDimitry Andric return Visit(E->getInit(0));
1631bab175ecSDimitry Andric
1632e3b55780SDimitry Andric VisitCXXParenListOrInitListExpr(
1633e3b55780SDimitry Andric E, E->inits(), E->getInitializedFieldInUnion(), E->getArrayFiller());
1634e3b55780SDimitry Andric }
1635bfef3995SDimitry Andric
VisitCXXParenListOrInitListExpr(Expr * ExprToVisit,ArrayRef<Expr * > InitExprs,FieldDecl * InitializedFieldInUnion,Expr * ArrayFiller)1636e3b55780SDimitry Andric void AggExprEmitter::VisitCXXParenListOrInitListExpr(
1637e3b55780SDimitry Andric Expr *ExprToVisit, ArrayRef<Expr *> InitExprs,
1638e3b55780SDimitry Andric FieldDecl *InitializedFieldInUnion, Expr *ArrayFiller) {
1639e3b55780SDimitry Andric #if 0
1640e3b55780SDimitry Andric // FIXME: Assess perf here? Figure out what cases are worth optimizing here
1641e3b55780SDimitry Andric // (Length of globals? Chunks of zeroed-out space?).
1642e3b55780SDimitry Andric //
1643e3b55780SDimitry Andric // If we can, prefer a copy from a global; this is a lot less code for long
1644e3b55780SDimitry Andric // globals, and it's easier for the current optimizers to analyze.
1645e3b55780SDimitry Andric if (llvm::Constant *C =
1646e3b55780SDimitry Andric CGF.CGM.EmitConstantExpr(ExprToVisit, ExprToVisit->getType(), &CGF)) {
1647e3b55780SDimitry Andric llvm::GlobalVariable* GV =
1648e3b55780SDimitry Andric new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true,
1649e3b55780SDimitry Andric llvm::GlobalValue::InternalLinkage, C, "");
1650e3b55780SDimitry Andric EmitFinalDestCopy(ExprToVisit->getType(),
1651e3b55780SDimitry Andric CGF.MakeAddrLValue(GV, ExprToVisit->getType()));
1652e3b55780SDimitry Andric return;
1653e3b55780SDimitry Andric }
1654e3b55780SDimitry Andric #endif
1655e3b55780SDimitry Andric
1656e3b55780SDimitry Andric AggValueSlot Dest = EnsureSlot(ExprToVisit->getType());
1657e3b55780SDimitry Andric
1658e3b55780SDimitry Andric LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), ExprToVisit->getType());
1659ec2b103cSEd Schouten
1660ec2b103cSEd Schouten // Handle initialization of an array.
16617fa27ce4SDimitry Andric if (ExprToVisit->getType()->isConstantArrayType()) {
166245b53394SDimitry Andric auto AType = cast<llvm::ArrayType>(Dest.getAddress().getElementType());
1663e3b55780SDimitry Andric EmitArrayInit(Dest.getAddress(), AType, ExprToVisit->getType(), ExprToVisit,
1664e3b55780SDimitry Andric InitExprs, ArrayFiller);
1665ec2b103cSEd Schouten return;
16667fa27ce4SDimitry Andric } else if (ExprToVisit->getType()->isVariableArrayType()) {
16677fa27ce4SDimitry Andric // A variable array type that has an initializer can only do empty
16687fa27ce4SDimitry Andric // initialization. And because this feature is not exposed as an extension
16697fa27ce4SDimitry Andric // in C++, we can safely memset the array memory to zero.
16707fa27ce4SDimitry Andric assert(InitExprs.size() == 0 &&
16717fa27ce4SDimitry Andric "you can only use an empty initializer with VLAs");
16727fa27ce4SDimitry Andric CGF.EmitNullInitialization(Dest.getAddress(), ExprToVisit->getType());
16737fa27ce4SDimitry Andric return;
1674ec2b103cSEd Schouten }
1675ec2b103cSEd Schouten
1676e3b55780SDimitry Andric assert(ExprToVisit->getType()->isRecordType() &&
1677e3b55780SDimitry Andric "Only support structs/unions here!");
1678ec2b103cSEd Schouten
1679ec2b103cSEd Schouten // Do struct initialization; this code just sets each individual member
1680ec2b103cSEd Schouten // to the approprate value. This makes bitfield support automatic;
1681ec2b103cSEd Schouten // the disadvantage is that the generated code is more difficult for
1682ec2b103cSEd Schouten // the optimizer, especially with bitfields.
1683e3b55780SDimitry Andric unsigned NumInitElements = InitExprs.size();
1684e3b55780SDimitry Andric RecordDecl *record = ExprToVisit->getType()->castAs<RecordType>()->getDecl();
16853d1dcd9bSDimitry Andric
16862b6b257fSDimitry Andric // We'll need to enter cleanup scopes in case any of the element
16872b6b257fSDimitry Andric // initializers throws an exception.
16882b6b257fSDimitry Andric SmallVector<EHScopeStack::stable_iterator, 16> cleanups;
1689ac9a064cSDimitry Andric CodeGenFunction::CleanupDeactivationScope DeactivateCleanups(CGF);
16902b6b257fSDimitry Andric
16912b6b257fSDimitry Andric unsigned curInitIndex = 0;
16922b6b257fSDimitry Andric
16932b6b257fSDimitry Andric // Emit initialization of base classes.
16942b6b257fSDimitry Andric if (auto *CXXRD = dyn_cast<CXXRecordDecl>(record)) {
1695e3b55780SDimitry Andric assert(NumInitElements >= CXXRD->getNumBases() &&
16962b6b257fSDimitry Andric "missing initializer for base class");
16972b6b257fSDimitry Andric for (auto &Base : CXXRD->bases()) {
16982b6b257fSDimitry Andric assert(!Base.isVirtual() && "should not see vbases here");
16992b6b257fSDimitry Andric auto *BaseRD = Base.getType()->getAsCXXRecordDecl();
17002b6b257fSDimitry Andric Address V = CGF.GetAddressOfDirectBaseInCompleteClass(
17012b6b257fSDimitry Andric Dest.getAddress(), CXXRD, BaseRD,
17022b6b257fSDimitry Andric /*isBaseVirtual*/ false);
170348675466SDimitry Andric AggValueSlot AggSlot = AggValueSlot::forAddr(
170448675466SDimitry Andric V, Qualifiers(),
17052b6b257fSDimitry Andric AggValueSlot::IsDestructed,
17062b6b257fSDimitry Andric AggValueSlot::DoesNotNeedGCBarriers,
170748675466SDimitry Andric AggValueSlot::IsNotAliased,
170822989816SDimitry Andric CGF.getOverlapForBaseInit(CXXRD, BaseRD, Base.isVirtual()));
1709e3b55780SDimitry Andric CGF.EmitAggExpr(InitExprs[curInitIndex++], AggSlot);
17102b6b257fSDimitry Andric
17112b6b257fSDimitry Andric if (QualType::DestructionKind dtorKind =
1712ac9a064cSDimitry Andric Base.getType().isDestructedType())
1713ac9a064cSDimitry Andric CGF.pushDestroyAndDeferDeactivation(dtorKind, V, Base.getType());
17142b6b257fSDimitry Andric }
17152b6b257fSDimitry Andric }
17162b6b257fSDimitry Andric
17176a037251SDimitry Andric // Prepare a 'this' for CXXDefaultInitExprs.
171845b53394SDimitry Andric CodeGenFunction::FieldConstructionScope FCS(CGF, Dest.getAddress());
17196a037251SDimitry Andric
1720180abc3dSDimitry Andric if (record->isUnion()) {
1721ec2b103cSEd Schouten // Only initialize one field of a union. The field itself is
1722ec2b103cSEd Schouten // specified by the initializer list.
1723e3b55780SDimitry Andric if (!InitializedFieldInUnion) {
1724ec2b103cSEd Schouten // Empty union; we have nothing to do.
1725ec2b103cSEd Schouten
1726ec2b103cSEd Schouten #ifndef NDEBUG
1727ec2b103cSEd Schouten // Make sure that it's really an empty and not a failure of
1728ec2b103cSEd Schouten // semantic analysis.
17299f4dbff6SDimitry Andric for (const auto *Field : record->fields())
1730ac9a064cSDimitry Andric assert(
1731ac9a064cSDimitry Andric (Field->isUnnamedBitField() || Field->isAnonymousStructOrUnion()) &&
1732ac9a064cSDimitry Andric "Only unnamed bitfields or anonymous class allowed");
1733ec2b103cSEd Schouten #endif
1734ec2b103cSEd Schouten return;
1735ec2b103cSEd Schouten }
1736ec2b103cSEd Schouten
1737ec2b103cSEd Schouten // FIXME: volatility
1738e3b55780SDimitry Andric FieldDecl *Field = InitializedFieldInUnion;
1739ec2b103cSEd Schouten
17406b9a6e39SDimitry Andric LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestLV, Field);
1741ec2b103cSEd Schouten if (NumInitElements) {
1742ec2b103cSEd Schouten // Store the initializer into the field
1743e3b55780SDimitry Andric EmitInitializationToLValue(InitExprs[0], FieldLoc);
1744ec2b103cSEd Schouten } else {
1745bca07a45SDimitry Andric // Default-initialize to null.
1746180abc3dSDimitry Andric EmitNullInitializationToLValue(FieldLoc);
1747ec2b103cSEd Schouten }
1748ec2b103cSEd Schouten
1749ec2b103cSEd Schouten return;
1750ec2b103cSEd Schouten }
1751ec2b103cSEd Schouten
1752ec2b103cSEd Schouten // Here we iterate over the fields; this makes it simpler to both
1753ec2b103cSEd Schouten // default-initialize fields and skip over unnamed fields.
17549f4dbff6SDimitry Andric for (const auto *field : record->fields()) {
1755180abc3dSDimitry Andric // We're done once we hit the flexible array member.
1756180abc3dSDimitry Andric if (field->getType()->isIncompleteArrayType())
1757ec2b103cSEd Schouten break;
1758ec2b103cSEd Schouten
1759180abc3dSDimitry Andric // Always skip anonymous bitfields.
1760ac9a064cSDimitry Andric if (field->isUnnamedBitField())
1761ec2b103cSEd Schouten continue;
1762ec2b103cSEd Schouten
1763180abc3dSDimitry Andric // We're done if we reach the end of the explicit initializers, we
1764180abc3dSDimitry Andric // have a zeroed object, and the rest of the fields are
1765180abc3dSDimitry Andric // zero-initializable.
1766180abc3dSDimitry Andric if (curInitIndex == NumInitElements && Dest.isZeroed() &&
1767e3b55780SDimitry Andric CGF.getTypes().isZeroInitializable(ExprToVisit->getType()))
1768bca07a45SDimitry Andric break;
1769bca07a45SDimitry Andric
17706b9a6e39SDimitry Andric
17719f4dbff6SDimitry Andric LValue LV = CGF.EmitLValueForFieldInitialization(DestLV, field);
1772ec2b103cSEd Schouten // We never generate write-barries for initialized fields.
1773180abc3dSDimitry Andric LV.setNonGC(true);
1774bca07a45SDimitry Andric
1775180abc3dSDimitry Andric if (curInitIndex < NumInitElements) {
1776a16e9ac1SRoman Divacky // Store the initializer into the field.
1777e3b55780SDimitry Andric EmitInitializationToLValue(InitExprs[curInitIndex++], LV);
1778ec2b103cSEd Schouten } else {
17797442d6faSDimitry Andric // We're out of initializers; default-initialize to null
1780180abc3dSDimitry Andric EmitNullInitializationToLValue(LV);
1781180abc3dSDimitry Andric }
1782180abc3dSDimitry Andric
1783180abc3dSDimitry Andric // Push a destructor if necessary.
1784180abc3dSDimitry Andric // FIXME: if we have an array of structures, all explicitly
1785180abc3dSDimitry Andric // initialized, we can end up pushing a linear number of cleanups.
1786180abc3dSDimitry Andric if (QualType::DestructionKind dtorKind
1787180abc3dSDimitry Andric = field->getType().isDestructedType()) {
1788180abc3dSDimitry Andric assert(LV.isSimple());
1789ac9a064cSDimitry Andric if (dtorKind) {
1790ac9a064cSDimitry Andric CGF.pushDestroyAndDeferDeactivation(NormalAndEHCleanup, LV.getAddress(),
1791ac9a064cSDimitry Andric field->getType(),
1792180abc3dSDimitry Andric CGF.getDestroyer(dtorKind), false);
1793180abc3dSDimitry Andric }
1794ec2b103cSEd Schouten }
1795ec2b103cSEd Schouten }
1796ec2b103cSEd Schouten }
1797ec2b103cSEd Schouten
VisitArrayInitLoopExpr(const ArrayInitLoopExpr * E,llvm::Value * outerBegin)1798bab175ecSDimitry Andric void AggExprEmitter::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E,
1799bab175ecSDimitry Andric llvm::Value *outerBegin) {
1800bab175ecSDimitry Andric // Emit the common subexpression.
1801bab175ecSDimitry Andric CodeGenFunction::OpaqueValueMapping binding(CGF, E->getCommonExpr());
1802bab175ecSDimitry Andric
1803bab175ecSDimitry Andric Address destPtr = EnsureSlot(E->getType()).getAddress();
1804bab175ecSDimitry Andric uint64_t numElements = E->getArraySize().getZExtValue();
1805bab175ecSDimitry Andric
1806bab175ecSDimitry Andric if (!numElements)
1807bab175ecSDimitry Andric return;
1808bab175ecSDimitry Andric
1809bab175ecSDimitry Andric // destPtr is an array*. Construct an elementType* by drilling down a level.
1810bab175ecSDimitry Andric llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
1811bab175ecSDimitry Andric llvm::Value *indices[] = {zero, zero};
1812ac9a064cSDimitry Andric llvm::Value *begin = Builder.CreateInBoundsGEP(destPtr.getElementType(),
1813ac9a064cSDimitry Andric destPtr.emitRawPointer(CGF),
1814ac9a064cSDimitry Andric indices, "arrayinit.begin");
1815bab175ecSDimitry Andric
1816bab175ecSDimitry Andric // Prepare to special-case multidimensional array initialization: we avoid
1817bab175ecSDimitry Andric // emitting multiple destructor loops in that case.
1818bab175ecSDimitry Andric if (!outerBegin)
1819bab175ecSDimitry Andric outerBegin = begin;
1820bab175ecSDimitry Andric ArrayInitLoopExpr *InnerLoop = dyn_cast<ArrayInitLoopExpr>(E->getSubExpr());
1821bab175ecSDimitry Andric
1822bab175ecSDimitry Andric QualType elementType =
1823bab175ecSDimitry Andric CGF.getContext().getAsArrayType(E->getType())->getElementType();
1824bab175ecSDimitry Andric CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
1825bab175ecSDimitry Andric CharUnits elementAlign =
1826bab175ecSDimitry Andric destPtr.getAlignment().alignmentOfArrayElement(elementSize);
18276f8fc217SDimitry Andric llvm::Type *llvmElementType = CGF.ConvertTypeForMem(elementType);
1828bab175ecSDimitry Andric
1829bab175ecSDimitry Andric llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1830bab175ecSDimitry Andric llvm::BasicBlock *bodyBB = CGF.createBasicBlock("arrayinit.body");
1831bab175ecSDimitry Andric
1832bab175ecSDimitry Andric // Jump into the body.
1833bab175ecSDimitry Andric CGF.EmitBlock(bodyBB);
1834bab175ecSDimitry Andric llvm::PHINode *index =
1835bab175ecSDimitry Andric Builder.CreatePHI(zero->getType(), 2, "arrayinit.index");
1836bab175ecSDimitry Andric index->addIncoming(zero, entryBB);
18376f8fc217SDimitry Andric llvm::Value *element =
18386f8fc217SDimitry Andric Builder.CreateInBoundsGEP(llvmElementType, begin, index);
1839bab175ecSDimitry Andric
1840bab175ecSDimitry Andric // Prepare for a cleanup.
1841bab175ecSDimitry Andric QualType::DestructionKind dtorKind = elementType.isDestructedType();
1842bab175ecSDimitry Andric EHScopeStack::stable_iterator cleanup;
1843bab175ecSDimitry Andric if (CGF.needsEHCleanup(dtorKind) && !InnerLoop) {
1844bab175ecSDimitry Andric if (outerBegin->getType() != element->getType())
1845bab175ecSDimitry Andric outerBegin = Builder.CreateBitCast(outerBegin, element->getType());
1846bab175ecSDimitry Andric CGF.pushRegularPartialArrayCleanup(outerBegin, element, elementType,
1847bab175ecSDimitry Andric elementAlign,
1848bab175ecSDimitry Andric CGF.getDestroyer(dtorKind));
1849bab175ecSDimitry Andric cleanup = CGF.EHStack.stable_begin();
1850bab175ecSDimitry Andric } else {
1851bab175ecSDimitry Andric dtorKind = QualType::DK_none;
1852bab175ecSDimitry Andric }
1853bab175ecSDimitry Andric
1854bab175ecSDimitry Andric // Emit the actual filler expression.
1855bab175ecSDimitry Andric {
1856bab175ecSDimitry Andric // Temporaries created in an array initialization loop are destroyed
1857bab175ecSDimitry Andric // at the end of each iteration.
1858bab175ecSDimitry Andric CodeGenFunction::RunCleanupsScope CleanupsScope(CGF);
1859bab175ecSDimitry Andric CodeGenFunction::ArrayInitLoopExprScope Scope(CGF, index);
1860ecbca9f5SDimitry Andric LValue elementLV = CGF.MakeAddrLValue(
1861ecbca9f5SDimitry Andric Address(element, llvmElementType, elementAlign), elementType);
1862bab175ecSDimitry Andric
1863bab175ecSDimitry Andric if (InnerLoop) {
1864bab175ecSDimitry Andric // If the subexpression is an ArrayInitLoopExpr, share its cleanup.
1865bab175ecSDimitry Andric auto elementSlot = AggValueSlot::forLValue(
1866ac9a064cSDimitry Andric elementLV, AggValueSlot::IsDestructed,
1867706b4fc4SDimitry Andric AggValueSlot::DoesNotNeedGCBarriers, AggValueSlot::IsNotAliased,
186848675466SDimitry Andric AggValueSlot::DoesNotOverlap);
1869bab175ecSDimitry Andric AggExprEmitter(CGF, elementSlot, false)
1870bab175ecSDimitry Andric .VisitArrayInitLoopExpr(InnerLoop, outerBegin);
1871bab175ecSDimitry Andric } else
1872bab175ecSDimitry Andric EmitInitializationToLValue(E->getSubExpr(), elementLV);
1873bab175ecSDimitry Andric }
1874bab175ecSDimitry Andric
1875bab175ecSDimitry Andric // Move on to the next element.
1876bab175ecSDimitry Andric llvm::Value *nextIndex = Builder.CreateNUWAdd(
1877bab175ecSDimitry Andric index, llvm::ConstantInt::get(CGF.SizeTy, 1), "arrayinit.next");
1878bab175ecSDimitry Andric index->addIncoming(nextIndex, Builder.GetInsertBlock());
1879bab175ecSDimitry Andric
1880bab175ecSDimitry Andric // Leave the loop if we're done.
1881bab175ecSDimitry Andric llvm::Value *done = Builder.CreateICmpEQ(
1882bab175ecSDimitry Andric nextIndex, llvm::ConstantInt::get(CGF.SizeTy, numElements),
1883bab175ecSDimitry Andric "arrayinit.done");
1884bab175ecSDimitry Andric llvm::BasicBlock *endBB = CGF.createBasicBlock("arrayinit.end");
1885bab175ecSDimitry Andric Builder.CreateCondBr(done, endBB, bodyBB);
1886bab175ecSDimitry Andric
1887bab175ecSDimitry Andric CGF.EmitBlock(endBB);
1888bab175ecSDimitry Andric
1889bab175ecSDimitry Andric // Leave the partial-array cleanup if we entered one.
1890bab175ecSDimitry Andric if (dtorKind)
1891bab175ecSDimitry Andric CGF.DeactivateCleanupBlock(cleanup, index);
1892bab175ecSDimitry Andric }
1893bab175ecSDimitry Andric
VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr * E)18942e645aa5SDimitry Andric void AggExprEmitter::VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E) {
18952e645aa5SDimitry Andric AggValueSlot Dest = EnsureSlot(E->getType());
18962e645aa5SDimitry Andric
189745b53394SDimitry Andric LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType());
18982e645aa5SDimitry Andric EmitInitializationToLValue(E->getBase(), DestLV);
18992e645aa5SDimitry Andric VisitInitListExpr(E->getUpdater());
19002e645aa5SDimitry Andric }
19012e645aa5SDimitry Andric
1902ec2b103cSEd Schouten //===----------------------------------------------------------------------===//
1903ec2b103cSEd Schouten // Entry Points into this File
1904ec2b103cSEd Schouten //===----------------------------------------------------------------------===//
1905ec2b103cSEd Schouten
1906bca07a45SDimitry Andric /// GetNumNonZeroBytesInInit - Get an approximate count of the number of
1907bca07a45SDimitry Andric /// non-zero bytes that will be stored when outputting the initializer for the
1908bca07a45SDimitry Andric /// specified initializer expression.
GetNumNonZeroBytesInInit(const Expr * E,CodeGenFunction & CGF)190901af97d3SDimitry Andric static CharUnits GetNumNonZeroBytesInInit(const Expr *E, CodeGenFunction &CGF) {
1910b60736ecSDimitry Andric if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
1911b60736ecSDimitry Andric E = MTE->getSubExpr();
1912b60736ecSDimitry Andric E = E->IgnoreParenNoopCasts(CGF.getContext());
1913bca07a45SDimitry Andric
1914bca07a45SDimitry Andric // 0 and 0.0 won't require any non-zero stores!
191501af97d3SDimitry Andric if (isSimpleZero(E, CGF)) return CharUnits::Zero();
1916bca07a45SDimitry Andric
1917bca07a45SDimitry Andric // If this is an initlist expr, sum up the size of sizes of the (present)
1918bca07a45SDimitry Andric // elements. If this is something weird, assume the whole thing is non-zero.
1919bca07a45SDimitry Andric const InitListExpr *ILE = dyn_cast<InitListExpr>(E);
192048675466SDimitry Andric while (ILE && ILE->isTransparent())
192148675466SDimitry Andric ILE = dyn_cast<InitListExpr>(ILE->getInit(0));
19229f4dbff6SDimitry Andric if (!ILE || !CGF.getTypes().isZeroInitializable(ILE->getType()))
192301af97d3SDimitry Andric return CGF.getContext().getTypeSizeInChars(E->getType());
1924bca07a45SDimitry Andric
1925bca07a45SDimitry Andric // InitListExprs for structs have to be handled carefully. If there are
1926bca07a45SDimitry Andric // reference members, we need to consider the size of the reference, not the
1927bca07a45SDimitry Andric // referencee. InitListExprs for unions and arrays can't have references.
1928bca07a45SDimitry Andric if (const RecordType *RT = E->getType()->getAs<RecordType>()) {
1929bca07a45SDimitry Andric if (!RT->isUnionType()) {
1930519fc96cSDimitry Andric RecordDecl *SD = RT->getDecl();
193101af97d3SDimitry Andric CharUnits NumNonZeroBytes = CharUnits::Zero();
1932bca07a45SDimitry Andric
1933bca07a45SDimitry Andric unsigned ILEElement = 0;
19342b6b257fSDimitry Andric if (auto *CXXRD = dyn_cast<CXXRecordDecl>(SD))
19352b6b257fSDimitry Andric while (ILEElement != CXXRD->getNumBases())
19362b6b257fSDimitry Andric NumNonZeroBytes +=
19372b6b257fSDimitry Andric GetNumNonZeroBytesInInit(ILE->getInit(ILEElement++), CGF);
19389f4dbff6SDimitry Andric for (const auto *Field : SD->fields()) {
1939bca07a45SDimitry Andric // We're done once we hit the flexible array member or run out of
1940bca07a45SDimitry Andric // InitListExpr elements.
1941bca07a45SDimitry Andric if (Field->getType()->isIncompleteArrayType() ||
1942bca07a45SDimitry Andric ILEElement == ILE->getNumInits())
1943bca07a45SDimitry Andric break;
1944ac9a064cSDimitry Andric if (Field->isUnnamedBitField())
1945bca07a45SDimitry Andric continue;
1946bca07a45SDimitry Andric
1947bca07a45SDimitry Andric const Expr *E = ILE->getInit(ILEElement++);
1948bca07a45SDimitry Andric
1949bca07a45SDimitry Andric // Reference values are always non-null and have the width of a pointer.
1950bca07a45SDimitry Andric if (Field->getType()->isReferenceType())
195101af97d3SDimitry Andric NumNonZeroBytes += CGF.getContext().toCharUnitsFromBits(
1952e3b55780SDimitry Andric CGF.getTarget().getPointerWidth(LangAS::Default));
1953bca07a45SDimitry Andric else
1954bca07a45SDimitry Andric NumNonZeroBytes += GetNumNonZeroBytesInInit(E, CGF);
1955bca07a45SDimitry Andric }
1956bca07a45SDimitry Andric
1957bca07a45SDimitry Andric return NumNonZeroBytes;
1958bca07a45SDimitry Andric }
1959bca07a45SDimitry Andric }
1960bca07a45SDimitry Andric
1961b60736ecSDimitry Andric // FIXME: This overestimates the number of non-zero bytes for bit-fields.
196201af97d3SDimitry Andric CharUnits NumNonZeroBytes = CharUnits::Zero();
1963bca07a45SDimitry Andric for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
1964bca07a45SDimitry Andric NumNonZeroBytes += GetNumNonZeroBytesInInit(ILE->getInit(i), CGF);
1965bca07a45SDimitry Andric return NumNonZeroBytes;
1966bca07a45SDimitry Andric }
1967bca07a45SDimitry Andric
1968bca07a45SDimitry Andric /// CheckAggExprForMemSetUse - If the initializer is large and has a lot of
1969bca07a45SDimitry Andric /// zeros in it, emit a memset and avoid storing the individual zeros.
1970bca07a45SDimitry Andric ///
CheckAggExprForMemSetUse(AggValueSlot & Slot,const Expr * E,CodeGenFunction & CGF)1971bca07a45SDimitry Andric static void CheckAggExprForMemSetUse(AggValueSlot &Slot, const Expr *E,
1972bca07a45SDimitry Andric CodeGenFunction &CGF) {
1973bca07a45SDimitry Andric // If the slot is already known to be zeroed, nothing to do. Don't mess with
1974bca07a45SDimitry Andric // volatile stores.
197545b53394SDimitry Andric if (Slot.isZeroed() || Slot.isVolatile() || !Slot.getAddress().isValid())
19769f4dbff6SDimitry Andric return;
1977bca07a45SDimitry Andric
197801af97d3SDimitry Andric // C++ objects with a user-declared constructor don't need zero'ing.
197913cc256eSDimitry Andric if (CGF.getLangOpts().CPlusPlus)
198001af97d3SDimitry Andric if (const RecordType *RT = CGF.getContext()
198101af97d3SDimitry Andric .getBaseElementType(E->getType())->getAs<RecordType>()) {
198201af97d3SDimitry Andric const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
198301af97d3SDimitry Andric if (RD->hasUserDeclaredConstructor())
198401af97d3SDimitry Andric return;
198501af97d3SDimitry Andric }
198601af97d3SDimitry Andric
1987bca07a45SDimitry Andric // If the type is 16-bytes or smaller, prefer individual stores over memset.
198848675466SDimitry Andric CharUnits Size = Slot.getPreferredSize(CGF.getContext(), E->getType());
198945b53394SDimitry Andric if (Size <= CharUnits::fromQuantity(16))
1990bca07a45SDimitry Andric return;
1991bca07a45SDimitry Andric
1992bca07a45SDimitry Andric // Check to see if over 3/4 of the initializer are known to be zero. If so,
1993bca07a45SDimitry Andric // we prefer to emit memset + individual stores for the rest.
199401af97d3SDimitry Andric CharUnits NumNonZeroBytes = GetNumNonZeroBytesInInit(E, CGF);
199545b53394SDimitry Andric if (NumNonZeroBytes*4 > Size)
1996bca07a45SDimitry Andric return;
1997bca07a45SDimitry Andric
1998bca07a45SDimitry Andric // Okay, it seems like a good idea to use an initial memset, emit the call.
199945b53394SDimitry Andric llvm::Constant *SizeVal = CGF.Builder.getInt64(Size.getQuantity());
2000bca07a45SDimitry Andric
20017fa27ce4SDimitry Andric Address Loc = Slot.getAddress().withElementType(CGF.Int8Ty);
200245b53394SDimitry Andric CGF.Builder.CreateMemSet(Loc, CGF.Builder.getInt8(0), SizeVal, false);
2003bca07a45SDimitry Andric
2004bca07a45SDimitry Andric // Tell the AggExprEmitter that the slot is known zero.
2005bca07a45SDimitry Andric Slot.setZeroed();
2006bca07a45SDimitry Andric }
2007bca07a45SDimitry Andric
2008bca07a45SDimitry Andric
2009bca07a45SDimitry Andric
2010bca07a45SDimitry Andric
2011ec2b103cSEd Schouten /// EmitAggExpr - Emit the computation of the specified expression of aggregate
2012ec2b103cSEd Schouten /// type. The result is computed into DestPtr. Note that if DestPtr is null,
2013ec2b103cSEd Schouten /// the value of the aggregate expression is not needed. If VolatileDest is
2014ec2b103cSEd Schouten /// true, DestPtr cannot be 0.
EmitAggExpr(const Expr * E,AggValueSlot Slot)201556d91b49SDimitry Andric void CodeGenFunction::EmitAggExpr(const Expr *E, AggValueSlot Slot) {
2016809500fcSDimitry Andric assert(E && hasAggregateEvaluationKind(E->getType()) &&
2017ec2b103cSEd Schouten "Invalid aggregate expression to emit");
201845b53394SDimitry Andric assert((Slot.getAddress().isValid() || Slot.isIgnored()) &&
2019bca07a45SDimitry Andric "slot has bits but no address");
2020ec2b103cSEd Schouten
2021bca07a45SDimitry Andric // Optimize the slot if possible.
2022bca07a45SDimitry Andric CheckAggExprForMemSetUse(Slot, E, *this);
2023bca07a45SDimitry Andric
2024798321d8SDimitry Andric AggExprEmitter(*this, Slot, Slot.isIgnored()).Visit(const_cast<Expr*>(E));
2025ec2b103cSEd Schouten }
2026ec2b103cSEd Schouten
EmitAggExprToLValue(const Expr * E)2027ecb7e5c8SRoman Divacky LValue CodeGenFunction::EmitAggExprToLValue(const Expr *E) {
2028809500fcSDimitry Andric assert(hasAggregateEvaluationKind(E->getType()) && "Invalid argument!");
202945b53394SDimitry Andric Address Temp = CreateMemTemp(E->getType());
20303d1dcd9bSDimitry Andric LValue LV = MakeAddrLValue(Temp, E->getType());
2031ac9a064cSDimitry Andric EmitAggExpr(E, AggValueSlot::forLValue(LV, AggValueSlot::IsNotDestructed,
203236981b17SDimitry Andric AggValueSlot::DoesNotNeedGCBarriers,
2033ac9a064cSDimitry Andric AggValueSlot::IsNotAliased,
2034ac9a064cSDimitry Andric AggValueSlot::DoesNotOverlap));
20353d1dcd9bSDimitry Andric return LV;
2036ecb7e5c8SRoman Divacky }
2037ecb7e5c8SRoman Divacky
EmitAggFinalDestCopy(QualType Type,AggValueSlot Dest,const LValue & Src,ExprValueKind SrcKind)2038ac9a064cSDimitry Andric void CodeGenFunction::EmitAggFinalDestCopy(QualType Type, AggValueSlot Dest,
2039ac9a064cSDimitry Andric const LValue &Src,
2040ac9a064cSDimitry Andric ExprValueKind SrcKind) {
2041ac9a064cSDimitry Andric return AggExprEmitter(*this, Dest, Dest.isIgnored())
2042ac9a064cSDimitry Andric .EmitFinalDestCopy(Type, Src, SrcKind);
2043ac9a064cSDimitry Andric }
2044ac9a064cSDimitry Andric
204522989816SDimitry Andric AggValueSlot::Overlap_t
getOverlapForFieldInit(const FieldDecl * FD)204622989816SDimitry Andric CodeGenFunction::getOverlapForFieldInit(const FieldDecl *FD) {
204722989816SDimitry Andric if (!FD->hasAttr<NoUniqueAddressAttr>() || !FD->getType()->isRecordType())
204848675466SDimitry Andric return AggValueSlot::DoesNotOverlap;
204948675466SDimitry Andric
20501de139fdSDimitry Andric // Empty fields can overlap earlier fields.
20511de139fdSDimitry Andric if (FD->getType()->getAsCXXRecordDecl()->isEmpty())
20521de139fdSDimitry Andric return AggValueSlot::MayOverlap;
20531de139fdSDimitry Andric
205422989816SDimitry Andric // If the field lies entirely within the enclosing class's nvsize, its tail
205522989816SDimitry Andric // padding cannot overlap any already-initialized object. (The only subobjects
205622989816SDimitry Andric // with greater addresses that might already be initialized are vbases.)
205722989816SDimitry Andric const RecordDecl *ClassRD = FD->getParent();
205822989816SDimitry Andric const ASTRecordLayout &Layout = getContext().getASTRecordLayout(ClassRD);
205922989816SDimitry Andric if (Layout.getFieldOffset(FD->getFieldIndex()) +
206022989816SDimitry Andric getContext().getTypeSize(FD->getType()) <=
206122989816SDimitry Andric (uint64_t)getContext().toBits(Layout.getNonVirtualSize()))
206222989816SDimitry Andric return AggValueSlot::DoesNotOverlap;
206322989816SDimitry Andric
206422989816SDimitry Andric // The tail padding may contain values we need to preserve.
206522989816SDimitry Andric return AggValueSlot::MayOverlap;
206622989816SDimitry Andric }
206722989816SDimitry Andric
getOverlapForBaseInit(const CXXRecordDecl * RD,const CXXRecordDecl * BaseRD,bool IsVirtual)206822989816SDimitry Andric AggValueSlot::Overlap_t CodeGenFunction::getOverlapForBaseInit(
206922989816SDimitry Andric const CXXRecordDecl *RD, const CXXRecordDecl *BaseRD, bool IsVirtual) {
207022989816SDimitry Andric // If the most-derived object is a field declared with [[no_unique_address]],
207122989816SDimitry Andric // the tail padding of any virtual base could be reused for other subobjects
207222989816SDimitry Andric // of that field's class.
207322989816SDimitry Andric if (IsVirtual)
207422989816SDimitry Andric return AggValueSlot::MayOverlap;
207522989816SDimitry Andric
20761de139fdSDimitry Andric // Empty bases can overlap earlier bases.
20771de139fdSDimitry Andric if (BaseRD->isEmpty())
20781de139fdSDimitry Andric return AggValueSlot::MayOverlap;
20791de139fdSDimitry Andric
208048675466SDimitry Andric // If the base class is laid out entirely within the nvsize of the derived
208148675466SDimitry Andric // class, its tail padding cannot yet be initialized, so we can issue
208248675466SDimitry Andric // stores at the full width of the base class.
208348675466SDimitry Andric const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
208448675466SDimitry Andric if (Layout.getBaseClassOffset(BaseRD) +
208548675466SDimitry Andric getContext().getASTRecordLayout(BaseRD).getSize() <=
208648675466SDimitry Andric Layout.getNonVirtualSize())
208748675466SDimitry Andric return AggValueSlot::DoesNotOverlap;
208848675466SDimitry Andric
208948675466SDimitry Andric // The tail padding may contain values we need to preserve.
209048675466SDimitry Andric return AggValueSlot::MayOverlap;
209148675466SDimitry Andric }
209248675466SDimitry Andric
EmitAggregateCopy(LValue Dest,LValue Src,QualType Ty,AggValueSlot::Overlap_t MayOverlap,bool isVolatile)209348675466SDimitry Andric void CodeGenFunction::EmitAggregateCopy(LValue Dest, LValue Src, QualType Ty,
209448675466SDimitry Andric AggValueSlot::Overlap_t MayOverlap,
209548675466SDimitry Andric bool isVolatile) {
2096ec2b103cSEd Schouten assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
2097ec2b103cSEd Schouten
2098ac9a064cSDimitry Andric Address DestPtr = Dest.getAddress();
2099ac9a064cSDimitry Andric Address SrcPtr = Src.getAddress();
210048675466SDimitry Andric
210113cc256eSDimitry Andric if (getLangOpts().CPlusPlus) {
21020883ccd9SRoman Divacky if (const RecordType *RT = Ty->getAs<RecordType>()) {
2103d7279c4cSRoman Divacky CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
2104d7279c4cSRoman Divacky assert((Record->hasTrivialCopyConstructor() ||
210536981b17SDimitry Andric Record->hasTrivialCopyAssignment() ||
210636981b17SDimitry Andric Record->hasTrivialMoveConstructor() ||
21075e20cdd8SDimitry Andric Record->hasTrivialMoveAssignment() ||
2108344a3780SDimitry Andric Record->hasAttr<TrivialABIAttr>() || Record->isUnion()) &&
2109809500fcSDimitry Andric "Trying to aggregate-copy a type without a trivial copy/move "
2110d7279c4cSRoman Divacky "constructor or assignment operator");
2111d7279c4cSRoman Divacky // Ignore empty classes in C++.
2112d7279c4cSRoman Divacky if (Record->isEmpty())
21130883ccd9SRoman Divacky return;
21140883ccd9SRoman Divacky }
21150883ccd9SRoman Divacky }
21160883ccd9SRoman Divacky
2117cfca06d7SDimitry Andric if (getLangOpts().CUDAIsDevice) {
2118cfca06d7SDimitry Andric if (Ty->isCUDADeviceBuiltinSurfaceType()) {
2119cfca06d7SDimitry Andric if (getTargetHooks().emitCUDADeviceBuiltinSurfaceDeviceCopy(*this, Dest,
2120cfca06d7SDimitry Andric Src))
2121cfca06d7SDimitry Andric return;
2122cfca06d7SDimitry Andric } else if (Ty->isCUDADeviceBuiltinTextureType()) {
2123cfca06d7SDimitry Andric if (getTargetHooks().emitCUDADeviceBuiltinTextureDeviceCopy(*this, Dest,
2124cfca06d7SDimitry Andric Src))
2125cfca06d7SDimitry Andric return;
2126cfca06d7SDimitry Andric }
2127cfca06d7SDimitry Andric }
2128cfca06d7SDimitry Andric
2129ec2b103cSEd Schouten // Aggregate assignment turns into llvm.memcpy. This is almost valid per
2130ec2b103cSEd Schouten // C99 6.5.16.1p3, which states "If the value being stored in an object is
2131ec2b103cSEd Schouten // read from another object that overlaps in anyway the storage of the first
2132ec2b103cSEd Schouten // object, then the overlap shall be exact and the two objects shall have
2133ec2b103cSEd Schouten // qualified or unqualified versions of a compatible type."
2134ec2b103cSEd Schouten //
2135ec2b103cSEd Schouten // memcpy is not defined if the source and destination pointers are exactly
2136ec2b103cSEd Schouten // equal, but other compilers do this optimization, and almost every memcpy
2137ec2b103cSEd Schouten // implementation handles this case safely. If there is a libc that does not
2138ec2b103cSEd Schouten // safely handle this, we can add a target hook.
2139ec2b103cSEd Schouten
214048675466SDimitry Andric // Get data size info for this aggregate. Don't copy the tail padding if this
214148675466SDimitry Andric // might be a potentially-overlapping subobject, since the tail padding might
214248675466SDimitry Andric // be occupied by a different object. Otherwise, copying it is fine.
2143b60736ecSDimitry Andric TypeInfoChars TypeInfo;
214448675466SDimitry Andric if (MayOverlap)
214513cc256eSDimitry Andric TypeInfo = getContext().getTypeInfoDataSizeInChars(Ty);
214613cc256eSDimitry Andric else
214713cc256eSDimitry Andric TypeInfo = getContext().getTypeInfoInChars(Ty);
2148ec2b103cSEd Schouten
21495e20cdd8SDimitry Andric llvm::Value *SizeVal = nullptr;
2150b60736ecSDimitry Andric if (TypeInfo.Width.isZero()) {
21515e20cdd8SDimitry Andric // But note that getTypeInfo returns 0 for a VLA.
21525e20cdd8SDimitry Andric if (auto *VAT = dyn_cast_or_null<VariableArrayType>(
21535e20cdd8SDimitry Andric getContext().getAsArrayType(Ty))) {
21545e20cdd8SDimitry Andric QualType BaseEltTy;
21555e20cdd8SDimitry Andric SizeVal = emitArrayLength(VAT, BaseEltTy, DestPtr);
215648675466SDimitry Andric TypeInfo = getContext().getTypeInfoInChars(BaseEltTy);
2157b60736ecSDimitry Andric assert(!TypeInfo.Width.isZero());
21585e20cdd8SDimitry Andric SizeVal = Builder.CreateNUWMul(
21595e20cdd8SDimitry Andric SizeVal,
2160b60736ecSDimitry Andric llvm::ConstantInt::get(SizeTy, TypeInfo.Width.getQuantity()));
21615e20cdd8SDimitry Andric }
21625e20cdd8SDimitry Andric }
21635e20cdd8SDimitry Andric if (!SizeVal) {
2164b60736ecSDimitry Andric SizeVal = llvm::ConstantInt::get(SizeTy, TypeInfo.Width.getQuantity());
21655e20cdd8SDimitry Andric }
2166ec2b103cSEd Schouten
2167ec2b103cSEd Schouten // FIXME: If we have a volatile struct, the optimizer can remove what might
2168ec2b103cSEd Schouten // appear to be `extra' memory ops:
2169ec2b103cSEd Schouten //
2170ec2b103cSEd Schouten // volatile struct { int i; } a, b;
2171ec2b103cSEd Schouten //
2172ec2b103cSEd Schouten // int main() {
2173ec2b103cSEd Schouten // a = b;
2174ec2b103cSEd Schouten // a = b;
2175ec2b103cSEd Schouten // }
2176ec2b103cSEd Schouten //
217760bfabcdSRoman Divacky // we need to use a different call here. We use isVolatile to indicate when
2178ec2b103cSEd Schouten // either the source or the destination is volatile.
217960bfabcdSRoman Divacky
21807fa27ce4SDimitry Andric DestPtr = DestPtr.withElementType(Int8Ty);
21817fa27ce4SDimitry Andric SrcPtr = SrcPtr.withElementType(Int8Ty);
218260bfabcdSRoman Divacky
2183180abc3dSDimitry Andric // Don't do any of the memmove_collectable tests if GC isn't set.
2184dbe13110SDimitry Andric if (CGM.getLangOpts().getGC() == LangOptions::NonGC) {
2185180abc3dSDimitry Andric // fall through
2186180abc3dSDimitry Andric } else if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
21874ba67500SRoman Divacky RecordDecl *Record = RecordTy->getDecl();
21884ba67500SRoman Divacky if (Record->hasObjectMember()) {
21894ba67500SRoman Divacky CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
21904ba67500SRoman Divacky SizeVal);
21914ba67500SRoman Divacky return;
21924ba67500SRoman Divacky }
2193180abc3dSDimitry Andric } else if (Ty->isArrayType()) {
21944ba67500SRoman Divacky QualType BaseType = getContext().getBaseElementType(Ty);
21954ba67500SRoman Divacky if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
21964ba67500SRoman Divacky if (RecordTy->getDecl()->hasObjectMember()) {
21974ba67500SRoman Divacky CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
21984ba67500SRoman Divacky SizeVal);
21994ba67500SRoman Divacky return;
22004ba67500SRoman Divacky }
22014ba67500SRoman Divacky }
22024ba67500SRoman Divacky }
22034ba67500SRoman Divacky
220445b53394SDimitry Andric auto Inst = Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, isVolatile);
220545b53394SDimitry Andric
220613cc256eSDimitry Andric // Determine the metadata to describe the position of any padding in this
220713cc256eSDimitry Andric // memcpy, as well as the TBAA tags for the members of the struct, in case
220813cc256eSDimitry Andric // the optimizer wishes to expand it in to scalar memory operations.
220945b53394SDimitry Andric if (llvm::MDNode *TBAAStructTag = CGM.getTBAAStructInfo(Ty))
221045b53394SDimitry Andric Inst->setMetadata(llvm::LLVMContext::MD_tbaa_struct, TBAAStructTag);
221148675466SDimitry Andric
221248675466SDimitry Andric if (CGM.getCodeGenOpts().NewStructPathTBAA) {
221348675466SDimitry Andric TBAAAccessInfo TBAAInfo = CGM.mergeTBAAInfoForMemoryTransfer(
221448675466SDimitry Andric Dest.getTBAAInfo(), Src.getTBAAInfo());
221548675466SDimitry Andric CGM.DecorateInstructionWithTBAA(Inst, TBAAInfo);
221648675466SDimitry Andric }
2217dbe13110SDimitry Andric }
2218