1 //===--- CGExprAgg.cpp - Emit LLVM Code from Aggregate Expressions --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This contains code to emit Aggregate Expr nodes as LLVM code.
12 //===----------------------------------------------------------------------===//
14 #include "CodeGenFunction.h"
15 #include "CodeGenModule.h"
16 #include "CGObjCRuntime.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/StmtVisitor.h"
20 #include "llvm/Constants.h"
21 #include "llvm/Function.h"
22 #include "llvm/GlobalVariable.h"
23 #include "llvm/Intrinsics.h"
24 using namespace clang;
25 using namespace CodeGen;
27 //===----------------------------------------------------------------------===//
28 // Aggregate Expression Emitter
29 //===----------------------------------------------------------------------===//
32 class AggExprEmitter : public StmtVisitor<AggExprEmitter> {
39 bool RequiresGCollection;
41 AggExprEmitter(CodeGenFunction &cgf, llvm::Value *destPtr, bool v,
42 bool ignore, bool isinit, bool requiresGCollection)
43 : CGF(cgf), Builder(CGF.Builder),
44 DestPtr(destPtr), VolatileDest(v), IgnoreResult(ignore),
45 IsInitializer(isinit), RequiresGCollection(requiresGCollection) {
48 //===--------------------------------------------------------------------===//
50 //===--------------------------------------------------------------------===//
52 /// EmitAggLoadOfLValue - Given an expression with aggregate type that
53 /// represents a value lvalue, this method emits the address of the lvalue,
54 /// then loads the result into DestPtr.
55 void EmitAggLoadOfLValue(const Expr *E);
57 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
58 void EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore = false);
59 void EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore = false);
61 //===--------------------------------------------------------------------===//
63 //===--------------------------------------------------------------------===//
65 void VisitStmt(Stmt *S) {
66 CGF.ErrorUnsupported(S, "aggregate expression");
68 void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); }
69 void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); }
72 void VisitDeclRefExpr(DeclRefExpr *DRE) { EmitAggLoadOfLValue(DRE); }
73 void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); }
74 void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); }
75 void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); }
76 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
77 EmitAggLoadOfLValue(E);
79 void VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
80 EmitAggLoadOfLValue(E);
82 void VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
83 EmitAggLoadOfLValue(E);
85 void VisitPredefinedExpr(const PredefinedExpr *E) {
86 EmitAggLoadOfLValue(E);
90 void VisitCastExpr(CastExpr *E);
91 void VisitCallExpr(const CallExpr *E);
92 void VisitStmtExpr(const StmtExpr *E);
93 void VisitBinaryOperator(const BinaryOperator *BO);
94 void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO);
95 void VisitBinAssign(const BinaryOperator *E);
96 void VisitBinComma(const BinaryOperator *E);
97 void VisitUnaryAddrOf(const UnaryOperator *E);
99 void VisitObjCMessageExpr(ObjCMessageExpr *E);
100 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
101 EmitAggLoadOfLValue(E);
103 void VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E);
104 void VisitObjCImplicitSetterGetterRefExpr(ObjCImplicitSetterGetterRefExpr *E);
106 void VisitConditionalOperator(const ConditionalOperator *CO);
107 void VisitChooseExpr(const ChooseExpr *CE);
108 void VisitInitListExpr(InitListExpr *E);
109 void VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
110 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
111 Visit(DAE->getExpr());
113 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
114 void VisitCXXConstructExpr(const CXXConstructExpr *E);
115 void VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E);
116 void VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E);
117 void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); }
119 void VisitVAArgExpr(VAArgExpr *E);
121 void EmitInitializationToLValue(Expr *E, LValue Address, QualType T);
122 void EmitNullInitializationToLValue(LValue Address, QualType T);
123 // case Expr::ChooseExprClass:
124 void VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); }
126 } // end anonymous namespace.
128 //===----------------------------------------------------------------------===//
130 //===----------------------------------------------------------------------===//
132 /// EmitAggLoadOfLValue - Given an expression with aggregate type that
133 /// represents a value lvalue, this method emits the address of the lvalue,
134 /// then loads the result into DestPtr.
135 void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) {
136 LValue LV = CGF.EmitLValue(E);
137 EmitFinalDestCopy(E, LV);
140 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
141 void AggExprEmitter::EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore) {
142 assert(Src.isAggregate() && "value must be aggregate value!");
144 // If the result is ignored, don't copy from the value.
146 if (!Src.isVolatileQualified() || (IgnoreResult && Ignore))
148 // If the source is volatile, we must read from it; to do that, we need
149 // some place to put it.
150 DestPtr = CGF.CreateMemTemp(E->getType(), "agg.tmp");
153 if (RequiresGCollection) {
154 CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF,
155 DestPtr, Src.getAggregateAddr(),
159 // If the result of the assignment is used, copy the LHS there also.
160 // FIXME: Pass VolatileDest as well. I think we also need to merge volatile
161 // from the source as well, as we can't eliminate it if either operand
162 // is volatile, unless copy has volatile for both source and destination..
163 CGF.EmitAggregateCopy(DestPtr, Src.getAggregateAddr(), E->getType(),
164 VolatileDest|Src.isVolatileQualified());
167 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
168 void AggExprEmitter::EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore) {
169 assert(Src.isSimple() && "Can't have aggregate bitfield, vector, etc");
171 EmitFinalDestCopy(E, RValue::getAggregate(Src.getAddress(),
172 Src.isVolatileQualified()),
176 //===----------------------------------------------------------------------===//
178 //===----------------------------------------------------------------------===//
180 void AggExprEmitter::VisitCastExpr(CastExpr *E) {
182 Visit(E->getSubExpr());
186 switch (E->getCastKind()) {
187 default: assert(0 && "Unhandled cast kind!");
189 case CastExpr::CK_ToUnion: {
190 // GCC union extension
192 CGF.getContext().getPointerType(E->getSubExpr()->getType());
193 llvm::Value *CastPtr = Builder.CreateBitCast(DestPtr,
194 CGF.ConvertType(PtrTy));
195 EmitInitializationToLValue(E->getSubExpr(),
196 LValue::MakeAddr(CastPtr, Qualifiers()),
197 E->getSubExpr()->getType());
201 // FIXME: Remove the CK_Unknown check here.
202 case CastExpr::CK_Unknown:
203 case CastExpr::CK_NoOp:
204 case CastExpr::CK_UserDefinedConversion:
205 case CastExpr::CK_ConstructorConversion:
206 assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(),
208 "Implicit cast types must be compatible");
209 Visit(E->getSubExpr());
212 case CastExpr::CK_NullToMemberPointer: {
213 // If the subexpression's type is the C++0x nullptr_t, emit the
214 // subexpression, which may have side effects.
215 if (E->getSubExpr()->getType()->isNullPtrType())
216 Visit(E->getSubExpr());
218 const llvm::Type *PtrDiffTy =
219 CGF.ConvertType(CGF.getContext().getPointerDiffType());
221 llvm::Value *NullValue = llvm::Constant::getNullValue(PtrDiffTy);
222 llvm::Value *Ptr = Builder.CreateStructGEP(DestPtr, 0, "ptr");
223 Builder.CreateStore(NullValue, Ptr, VolatileDest);
225 llvm::Value *Adj = Builder.CreateStructGEP(DestPtr, 1, "adj");
226 Builder.CreateStore(NullValue, Adj, VolatileDest);
231 case CastExpr::CK_BitCast: {
232 // This must be a member function pointer cast.
233 Visit(E->getSubExpr());
237 case CastExpr::CK_DerivedToBaseMemberPointer:
238 case CastExpr::CK_BaseToDerivedMemberPointer: {
239 QualType SrcType = E->getSubExpr()->getType();
241 llvm::Value *Src = CGF.CreateMemTemp(SrcType, "tmp");
242 CGF.EmitAggExpr(E->getSubExpr(), Src, SrcType.isVolatileQualified());
244 llvm::Value *SrcPtr = Builder.CreateStructGEP(Src, 0, "src.ptr");
245 SrcPtr = Builder.CreateLoad(SrcPtr);
247 llvm::Value *SrcAdj = Builder.CreateStructGEP(Src, 1, "src.adj");
248 SrcAdj = Builder.CreateLoad(SrcAdj);
250 llvm::Value *DstPtr = Builder.CreateStructGEP(DestPtr, 0, "dst.ptr");
251 Builder.CreateStore(SrcPtr, DstPtr, VolatileDest);
253 llvm::Value *DstAdj = Builder.CreateStructGEP(DestPtr, 1, "dst.adj");
255 // Now See if we need to update the adjustment.
256 const CXXRecordDecl *BaseDecl =
257 cast<CXXRecordDecl>(SrcType->getAs<MemberPointerType>()->
258 getClass()->getAs<RecordType>()->getDecl());
259 const CXXRecordDecl *DerivedDecl =
260 cast<CXXRecordDecl>(E->getType()->getAs<MemberPointerType>()->
261 getClass()->getAs<RecordType>()->getDecl());
262 if (E->getCastKind() == CastExpr::CK_DerivedToBaseMemberPointer)
263 std::swap(DerivedDecl, BaseDecl);
265 if (llvm::Constant *Adj =
266 CGF.CGM.GetNonVirtualBaseClassOffset(DerivedDecl, BaseDecl)) {
267 if (E->getCastKind() == CastExpr::CK_DerivedToBaseMemberPointer)
268 SrcAdj = Builder.CreateSub(SrcAdj, Adj, "adj");
270 SrcAdj = Builder.CreateAdd(SrcAdj, Adj, "adj");
273 Builder.CreateStore(SrcAdj, DstAdj, VolatileDest);
279 void AggExprEmitter::VisitCallExpr(const CallExpr *E) {
280 if (E->getCallReturnType()->isReferenceType()) {
281 EmitAggLoadOfLValue(E);
285 // If the struct doesn't require GC, we can just pass the destination
286 // directly to EmitCall.
287 if (!RequiresGCollection) {
288 CGF.EmitCallExpr(E, ReturnValueSlot(DestPtr, VolatileDest));
292 RValue RV = CGF.EmitCallExpr(E);
293 EmitFinalDestCopy(E, RV);
296 void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
297 RValue RV = CGF.EmitObjCMessageExpr(E);
298 EmitFinalDestCopy(E, RV);
301 void AggExprEmitter::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
302 RValue RV = CGF.EmitObjCPropertyGet(E);
303 EmitFinalDestCopy(E, RV);
306 void AggExprEmitter::VisitObjCImplicitSetterGetterRefExpr(
307 ObjCImplicitSetterGetterRefExpr *E) {
308 RValue RV = CGF.EmitObjCPropertyGet(E);
309 EmitFinalDestCopy(E, RV);
312 void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {
313 CGF.EmitAnyExpr(E->getLHS(), 0, false, true);
314 CGF.EmitAggExpr(E->getRHS(), DestPtr, VolatileDest,
315 /*IgnoreResult=*/false, IsInitializer);
318 void AggExprEmitter::VisitUnaryAddrOf(const UnaryOperator *E) {
319 // We have a member function pointer.
320 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
322 assert(MPT->getPointeeType()->isFunctionProtoType() &&
323 "Unexpected member pointer type!");
325 const DeclRefExpr *DRE = cast<DeclRefExpr>(E->getSubExpr());
326 const CXXMethodDecl *MD =
327 cast<CXXMethodDecl>(DRE->getDecl())->getCanonicalDecl();
329 const llvm::Type *PtrDiffTy =
330 CGF.ConvertType(CGF.getContext().getPointerDiffType());
332 llvm::Value *DstPtr = Builder.CreateStructGEP(DestPtr, 0, "dst.ptr");
333 llvm::Value *FuncPtr;
335 if (MD->isVirtual()) {
337 CGF.CGM.getVtableInfo().getMethodVtableIndex(MD);
339 // Itanium C++ ABI 2.3:
340 // For a non-virtual function, this field is a simple function pointer.
341 // For a virtual function, it is 1 plus the virtual table offset
342 // (in bytes) of the function, represented as a ptrdiff_t.
343 FuncPtr = llvm::ConstantInt::get(PtrDiffTy, (Index * 8) + 1);
345 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
346 const llvm::Type *Ty =
347 CGF.CGM.getTypes().GetFunctionType(CGF.CGM.getTypes().getFunctionInfo(MD),
349 llvm::Constant *Fn = CGF.CGM.GetAddrOfFunction(MD, Ty);
350 FuncPtr = llvm::ConstantExpr::getPtrToInt(Fn, PtrDiffTy);
352 Builder.CreateStore(FuncPtr, DstPtr, VolatileDest);
354 llvm::Value *AdjPtr = Builder.CreateStructGEP(DestPtr, 1, "dst.adj");
356 // The adjustment will always be 0.
357 Builder.CreateStore(llvm::ConstantInt::get(PtrDiffTy, 0), AdjPtr,
361 void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
362 CGF.EmitCompoundStmt(*E->getSubStmt(), true, DestPtr, VolatileDest);
365 void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
366 if (E->getOpcode() == BinaryOperator::PtrMemD ||
367 E->getOpcode() == BinaryOperator::PtrMemI)
368 VisitPointerToDataMemberBinaryOperator(E);
370 CGF.ErrorUnsupported(E, "aggregate binary expression");
373 void AggExprEmitter::VisitPointerToDataMemberBinaryOperator(
374 const BinaryOperator *E) {
375 LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E);
376 EmitFinalDestCopy(E, LV);
379 void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
380 // For an assignment to work, the value on the right has
381 // to be compatible with the value on the left.
382 assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
383 E->getRHS()->getType())
384 && "Invalid assignment");
385 LValue LHS = CGF.EmitLValue(E->getLHS());
387 // We have to special case property setters, otherwise we must have
388 // a simple lvalue (no aggregates inside vectors, bitfields).
389 if (LHS.isPropertyRef()) {
390 llvm::Value *AggLoc = DestPtr;
392 AggLoc = CGF.CreateMemTemp(E->getRHS()->getType());
393 CGF.EmitAggExpr(E->getRHS(), AggLoc, VolatileDest);
394 CGF.EmitObjCPropertySet(LHS.getPropertyRefExpr(),
395 RValue::getAggregate(AggLoc, VolatileDest));
396 } else if (LHS.isKVCRef()) {
397 llvm::Value *AggLoc = DestPtr;
399 AggLoc = CGF.CreateMemTemp(E->getRHS()->getType());
400 CGF.EmitAggExpr(E->getRHS(), AggLoc, VolatileDest);
401 CGF.EmitObjCPropertySet(LHS.getKVCRefExpr(),
402 RValue::getAggregate(AggLoc, VolatileDest));
404 bool RequiresGCollection = false;
405 if (CGF.getContext().getLangOptions().NeXTRuntime) {
406 QualType LHSTy = E->getLHS()->getType();
407 if (const RecordType *FDTTy = LHSTy.getTypePtr()->getAs<RecordType>())
408 RequiresGCollection = FDTTy->getDecl()->hasObjectMember();
410 // Codegen the RHS so that it stores directly into the LHS.
411 CGF.EmitAggExpr(E->getRHS(), LHS.getAddress(), LHS.isVolatileQualified(),
412 false, false, RequiresGCollection);
413 EmitFinalDestCopy(E, LHS, true);
417 void AggExprEmitter::VisitConditionalOperator(const ConditionalOperator *E) {
419 CGF.ErrorUnsupported(E, "conditional operator with missing LHS");
423 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
424 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
425 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
427 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
429 CGF.BeginConditionalBranch();
430 CGF.EmitBlock(LHSBlock);
432 // Handle the GNU extension for missing LHS.
433 assert(E->getLHS() && "Must have LHS for aggregate value");
436 CGF.EndConditionalBranch();
437 CGF.EmitBranch(ContBlock);
439 CGF.BeginConditionalBranch();
440 CGF.EmitBlock(RHSBlock);
443 CGF.EndConditionalBranch();
444 CGF.EmitBranch(ContBlock);
446 CGF.EmitBlock(ContBlock);
449 void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) {
450 Visit(CE->getChosenSubExpr(CGF.getContext()));
453 void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
454 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
455 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
458 CGF.ErrorUnsupported(VE, "aggregate va_arg expression");
462 EmitFinalDestCopy(VE, LValue::MakeAddr(ArgPtr, Qualifiers()));
465 void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
466 llvm::Value *Val = DestPtr;
469 // Create a temporary variable.
470 Val = CGF.CreateMemTemp(E->getType(), "tmp");
473 CGF.EmitAggExpr(E->getSubExpr(), Val, false);
475 Visit(E->getSubExpr());
477 // Don't make this a live temporary if we're emitting an initializer expr.
479 CGF.PushCXXTemporary(E->getTemporary(), Val);
483 AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) {
484 llvm::Value *Val = DestPtr;
487 // Create a temporary variable.
488 Val = CGF.CreateMemTemp(E->getType(), "tmp");
491 if (E->requiresZeroInitialization())
492 EmitNullInitializationToLValue(LValue::MakeAddr(Val,
493 // FIXME: Qualifiers()?
494 E->getType().getQualifiers()),
497 CGF.EmitCXXConstructExpr(Val, E);
500 void AggExprEmitter::VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E) {
501 llvm::Value *Val = DestPtr;
504 // Create a temporary variable.
505 Val = CGF.CreateMemTemp(E->getType(), "tmp");
507 CGF.EmitCXXExprWithTemporaries(E, Val, VolatileDest, IsInitializer);
510 void AggExprEmitter::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E) {
511 llvm::Value *Val = DestPtr;
514 // Create a temporary variable.
515 Val = CGF.CreateMemTemp(E->getType(), "tmp");
517 LValue LV = LValue::MakeAddr(Val, Qualifiers());
518 EmitNullInitializationToLValue(LV, E->getType());
521 void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
522 llvm::Value *Val = DestPtr;
525 // Create a temporary variable.
526 Val = CGF.CreateMemTemp(E->getType(), "tmp");
528 LValue LV = LValue::MakeAddr(Val, Qualifiers());
529 EmitNullInitializationToLValue(LV, E->getType());
533 AggExprEmitter::EmitInitializationToLValue(Expr* E, LValue LV, QualType T) {
534 // FIXME: Ignore result?
535 // FIXME: Are initializers affected by volatile?
536 if (isa<ImplicitValueInitExpr>(E)) {
537 EmitNullInitializationToLValue(LV, T);
538 } else if (T->isReferenceType()) {
539 RValue RV = CGF.EmitReferenceBindingToExpr(E, /*IsInitializer=*/false);
540 CGF.EmitStoreThroughLValue(RV, LV, T);
541 } else if (T->isAnyComplexType()) {
542 CGF.EmitComplexExprIntoAddr(E, LV.getAddress(), false);
543 } else if (CGF.hasAggregateLLVMType(T)) {
544 CGF.EmitAnyExpr(E, LV.getAddress(), false);
546 CGF.EmitStoreThroughLValue(CGF.EmitAnyExpr(E), LV, T);
550 void AggExprEmitter::EmitNullInitializationToLValue(LValue LV, QualType T) {
551 if (!CGF.hasAggregateLLVMType(T)) {
552 // For non-aggregates, we can store zero
553 llvm::Value *Null = llvm::Constant::getNullValue(CGF.ConvertType(T));
554 CGF.EmitStoreThroughLValue(RValue::get(Null), LV, T);
556 // Otherwise, just memset the whole thing to zero. This is legal
557 // because in LLVM, all default initializers are guaranteed to have a
558 // bit pattern of all zeros.
559 // FIXME: That isn't true for member pointers!
560 // There's a potential optimization opportunity in combining
561 // memsets; that would be easy for arrays, but relatively
562 // difficult for structures with the current code.
563 CGF.EmitMemSetToZero(LV.getAddress(), T);
567 void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
569 // FIXME: Assess perf here? Figure out what cases are worth optimizing here
570 // (Length of globals? Chunks of zeroed-out space?).
572 // If we can, prefer a copy from a global; this is a lot less code for long
573 // globals, and it's easier for the current optimizers to analyze.
574 if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) {
575 llvm::GlobalVariable* GV =
576 new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true,
577 llvm::GlobalValue::InternalLinkage, C, "");
578 EmitFinalDestCopy(E, LValue::MakeAddr(GV, Qualifiers()));
582 if (E->hadArrayRangeDesignator()) {
583 CGF.ErrorUnsupported(E, "GNU array range designator extension");
586 // Handle initialization of an array.
587 if (E->getType()->isArrayType()) {
588 const llvm::PointerType *APType =
589 cast<llvm::PointerType>(DestPtr->getType());
590 const llvm::ArrayType *AType =
591 cast<llvm::ArrayType>(APType->getElementType());
593 uint64_t NumInitElements = E->getNumInits();
595 if (E->getNumInits() > 0) {
596 QualType T1 = E->getType();
597 QualType T2 = E->getInit(0)->getType();
598 if (CGF.getContext().hasSameUnqualifiedType(T1, T2)) {
599 EmitAggLoadOfLValue(E->getInit(0));
604 uint64_t NumArrayElements = AType->getNumElements();
605 QualType ElementType = CGF.getContext().getCanonicalType(E->getType());
606 ElementType = CGF.getContext().getAsArrayType(ElementType)->getElementType();
608 // FIXME: were we intentionally ignoring address spaces and GC attributes?
609 Qualifiers Quals = CGF.MakeQualifiers(ElementType);
611 for (uint64_t i = 0; i != NumArrayElements; ++i) {
612 llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array");
613 if (i < NumInitElements)
614 EmitInitializationToLValue(E->getInit(i),
615 LValue::MakeAddr(NextVal, Quals),
618 EmitNullInitializationToLValue(LValue::MakeAddr(NextVal, Quals),
624 assert(E->getType()->isRecordType() && "Only support structs/unions here!");
626 // Do struct initialization; this code just sets each individual member
627 // to the approprate value. This makes bitfield support automatic;
628 // the disadvantage is that the generated code is more difficult for
629 // the optimizer, especially with bitfields.
630 unsigned NumInitElements = E->getNumInits();
631 RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl();
632 unsigned CurInitVal = 0;
634 if (E->getType()->isUnionType()) {
635 // Only initialize one field of a union. The field itself is
636 // specified by the initializer list.
637 if (!E->getInitializedFieldInUnion()) {
638 // Empty union; we have nothing to do.
641 // Make sure that it's really an empty and not a failure of
642 // semantic analysis.
643 for (RecordDecl::field_iterator Field = SD->field_begin(),
644 FieldEnd = SD->field_end();
645 Field != FieldEnd; ++Field)
646 assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed");
652 FieldDecl *Field = E->getInitializedFieldInUnion();
653 LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestPtr, Field, 0);
655 if (NumInitElements) {
656 // Store the initializer into the field
657 EmitInitializationToLValue(E->getInit(0), FieldLoc, Field->getType());
659 // Default-initialize to null
660 EmitNullInitializationToLValue(FieldLoc, Field->getType());
666 // If we're initializing the whole aggregate, just do it in place.
667 // FIXME: This is a hack around an AST bug (PR6537).
668 if (NumInitElements == 1 && E->getType() == E->getInit(0)->getType()) {
669 EmitInitializationToLValue(E->getInit(0),
670 LValue::MakeAddr(DestPtr, Qualifiers()),
676 // Here we iterate over the fields; this makes it simpler to both
677 // default-initialize fields and skip over unnamed fields.
678 for (RecordDecl::field_iterator Field = SD->field_begin(),
679 FieldEnd = SD->field_end();
680 Field != FieldEnd; ++Field) {
681 // We're done once we hit the flexible array member
682 if (Field->getType()->isIncompleteArrayType())
685 if (Field->isUnnamedBitfield())
689 LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestPtr, *Field, 0);
690 // We never generate write-barries for initialized fields.
691 LValue::SetObjCNonGC(FieldLoc, true);
692 if (CurInitVal < NumInitElements) {
693 // Store the initializer into the field.
694 EmitInitializationToLValue(E->getInit(CurInitVal++), FieldLoc,
697 // We're out of initalizers; default-initialize to null
698 EmitNullInitializationToLValue(FieldLoc, Field->getType());
703 //===----------------------------------------------------------------------===//
704 // Entry Points into this File
705 //===----------------------------------------------------------------------===//
707 /// EmitAggExpr - Emit the computation of the specified expression of aggregate
708 /// type. The result is computed into DestPtr. Note that if DestPtr is null,
709 /// the value of the aggregate expression is not needed. If VolatileDest is
710 /// true, DestPtr cannot be 0.
712 // FIXME: Take Qualifiers object.
713 void CodeGenFunction::EmitAggExpr(const Expr *E, llvm::Value *DestPtr,
714 bool VolatileDest, bool IgnoreResult,
716 bool RequiresGCollection) {
717 assert(E && hasAggregateLLVMType(E->getType()) &&
718 "Invalid aggregate expression to emit");
719 assert ((DestPtr != 0 || VolatileDest == false)
720 && "volatile aggregate can't be 0");
722 AggExprEmitter(*this, DestPtr, VolatileDest, IgnoreResult, IsInitializer,
724 .Visit(const_cast<Expr*>(E));
727 LValue CodeGenFunction::EmitAggExprToLValue(const Expr *E) {
728 assert(hasAggregateLLVMType(E->getType()) && "Invalid argument!");
729 Qualifiers Q = MakeQualifiers(E->getType());
730 llvm::Value *Temp = CreateMemTemp(E->getType());
731 EmitAggExpr(E, Temp, Q.hasVolatile());
732 return LValue::MakeAddr(Temp, Q);
735 void CodeGenFunction::EmitAggregateClear(llvm::Value *DestPtr, QualType Ty) {
736 assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
738 EmitMemSetToZero(DestPtr, Ty);
741 void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr,
742 llvm::Value *SrcPtr, QualType Ty,
744 assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
746 // Aggregate assignment turns into llvm.memcpy. This is almost valid per
747 // C99 6.5.16.1p3, which states "If the value being stored in an object is
748 // read from another object that overlaps in anyway the storage of the first
749 // object, then the overlap shall be exact and the two objects shall have
750 // qualified or unqualified versions of a compatible type."
752 // memcpy is not defined if the source and destination pointers are exactly
753 // equal, but other compilers do this optimization, and almost every memcpy
754 // implementation handles this case safely. If there is a libc that does not
755 // safely handle this, we can add a target hook.
756 const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
757 if (DestPtr->getType() != BP)
758 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
759 if (SrcPtr->getType() != BP)
760 SrcPtr = Builder.CreateBitCast(SrcPtr, BP, "tmp");
762 // Get size and alignment info for this aggregate.
763 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
765 // FIXME: Handle variable sized types.
766 const llvm::Type *IntPtr =
767 llvm::IntegerType::get(VMContext, LLVMPointerWidth);
769 // FIXME: If we have a volatile struct, the optimizer can remove what might
770 // appear to be `extra' memory ops:
772 // volatile struct { int i; } a, b;
779 // we need to use a differnt call here. We use isVolatile to indicate when
780 // either the source or the destination is volatile.
781 Builder.CreateCall4(CGM.getMemCpyFn(),
783 // TypeInfo.first describes size in bits.
784 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
785 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),