1 //===--- CGExprAgg.cpp - Emit LLVM Code from Aggregate Expressions --------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This contains code to emit Aggregate Expr nodes as LLVM code.
11 //
12 //===----------------------------------------------------------------------===//
13 
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;
26 
27 //===----------------------------------------------------------------------===//
28 //                        Aggregate Expression Emitter
29 //===----------------------------------------------------------------------===//
30 
31 namespace  {
32 class AggExprEmitter : public StmtVisitor<AggExprEmitter> {
33   CodeGenFunction &CGF;
34   CGBuilderTy &Builder;
35   llvm::Value *DestPtr;
36   bool VolatileDest;
37   bool IgnoreResult;
38   bool IsInitializer;
39   bool RequiresGCollection;
40 
41   ReturnValueSlot getReturnValueSlot() const {
42     return ReturnValueSlot(DestPtr, VolatileDest);
43   }
44 public:
45   AggExprEmitter(CodeGenFunction &cgf, llvm::Value *destPtr, bool v,
46                  bool ignore, bool isinit, bool requiresGCollection)
47     : CGF(cgf), Builder(CGF.Builder),
48       DestPtr(destPtr), VolatileDest(v), IgnoreResult(ignore),
49       IsInitializer(isinit), RequiresGCollection(requiresGCollection) {
50   }
51 
52   //===--------------------------------------------------------------------===//
53   //                               Utilities
54   //===--------------------------------------------------------------------===//
55 
56   /// EmitAggLoadOfLValue - Given an expression with aggregate type that
57   /// represents a value lvalue, this method emits the address of the lvalue,
58   /// then loads the result into DestPtr.
59   void EmitAggLoadOfLValue(const Expr *E);
60 
61   /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
62   void EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore = false);
63   void EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore = false);
64 
65   //===--------------------------------------------------------------------===//
66   //                            Visitor Methods
67   //===--------------------------------------------------------------------===//
68 
69   void VisitStmt(Stmt *S) {
70     CGF.ErrorUnsupported(S, "aggregate expression");
71   }
72   void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); }
73   void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); }
74 
75   // l-values.
76   void VisitDeclRefExpr(DeclRefExpr *DRE) { EmitAggLoadOfLValue(DRE); }
77   void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); }
78   void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); }
79   void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); }
80   void VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
81     EmitAggLoadOfLValue(E);
82   }
83   void VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
84     EmitAggLoadOfLValue(E);
85   }
86   void VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
87     EmitAggLoadOfLValue(E);
88   }
89   void VisitPredefinedExpr(const PredefinedExpr *E) {
90     EmitAggLoadOfLValue(E);
91   }
92 
93   // Operators.
94   void VisitCastExpr(CastExpr *E);
95   void VisitCallExpr(const CallExpr *E);
96   void VisitStmtExpr(const StmtExpr *E);
97   void VisitBinaryOperator(const BinaryOperator *BO);
98   void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO);
99   void VisitBinAssign(const BinaryOperator *E);
100   void VisitBinComma(const BinaryOperator *E);
101   void VisitUnaryAddrOf(const UnaryOperator *E);
102 
103   void VisitObjCMessageExpr(ObjCMessageExpr *E);
104   void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
105     EmitAggLoadOfLValue(E);
106   }
107   void VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E);
108   void VisitObjCImplicitSetterGetterRefExpr(ObjCImplicitSetterGetterRefExpr *E);
109 
110   void VisitConditionalOperator(const ConditionalOperator *CO);
111   void VisitChooseExpr(const ChooseExpr *CE);
112   void VisitInitListExpr(InitListExpr *E);
113   void VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
114   void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
115     Visit(DAE->getExpr());
116   }
117   void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
118   void VisitCXXConstructExpr(const CXXConstructExpr *E);
119   void VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E);
120   void VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E);
121   void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); }
122 
123   void VisitVAArgExpr(VAArgExpr *E);
124 
125   void EmitInitializationToLValue(Expr *E, LValue Address, QualType T);
126   void EmitNullInitializationToLValue(LValue Address, QualType T);
127   //  case Expr::ChooseExprClass:
128   void VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); }
129 };
130 }  // end anonymous namespace.
131 
132 //===----------------------------------------------------------------------===//
133 //                                Utilities
134 //===----------------------------------------------------------------------===//
135 
136 /// EmitAggLoadOfLValue - Given an expression with aggregate type that
137 /// represents a value lvalue, this method emits the address of the lvalue,
138 /// then loads the result into DestPtr.
139 void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) {
140   LValue LV = CGF.EmitLValue(E);
141   EmitFinalDestCopy(E, LV);
142 }
143 
144 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
145 void AggExprEmitter::EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore) {
146   assert(Src.isAggregate() && "value must be aggregate value!");
147 
148   // If the result is ignored, don't copy from the value.
149   if (DestPtr == 0) {
150     if (!Src.isVolatileQualified() || (IgnoreResult && Ignore))
151       return;
152     // If the source is volatile, we must read from it; to do that, we need
153     // some place to put it.
154     DestPtr = CGF.CreateMemTemp(E->getType(), "agg.tmp");
155   }
156 
157   if (RequiresGCollection) {
158     CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF,
159                                               DestPtr, Src.getAggregateAddr(),
160                                               E->getType());
161     return;
162   }
163   // If the result of the assignment is used, copy the LHS there also.
164   // FIXME: Pass VolatileDest as well.  I think we also need to merge volatile
165   // from the source as well, as we can't eliminate it if either operand
166   // is volatile, unless copy has volatile for both source and destination..
167   CGF.EmitAggregateCopy(DestPtr, Src.getAggregateAddr(), E->getType(),
168                         VolatileDest|Src.isVolatileQualified());
169 }
170 
171 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
172 void AggExprEmitter::EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore) {
173   assert(Src.isSimple() && "Can't have aggregate bitfield, vector, etc");
174 
175   EmitFinalDestCopy(E, RValue::getAggregate(Src.getAddress(),
176                                             Src.isVolatileQualified()),
177                     Ignore);
178 }
179 
180 //===----------------------------------------------------------------------===//
181 //                            Visitor Methods
182 //===----------------------------------------------------------------------===//
183 
184 void AggExprEmitter::VisitCastExpr(CastExpr *E) {
185   if (!DestPtr && E->getCastKind() != CastExpr::CK_Dynamic) {
186     Visit(E->getSubExpr());
187     return;
188   }
189 
190   switch (E->getCastKind()) {
191   default: assert(0 && "Unhandled cast kind!");
192 
193   case CastExpr::CK_Dynamic: {
194     assert(isa<CXXDynamicCastExpr>(E) && "CK_Dynamic without a dynamic_cast?");
195     LValue LV = CGF.EmitCheckedLValue(E->getSubExpr());
196     // FIXME: Do we also need to handle property references here?
197     if (LV.isSimple())
198       CGF.EmitDynamicCast(LV.getAddress(), cast<CXXDynamicCastExpr>(E));
199     else
200       CGF.CGM.ErrorUnsupported(E, "non-simple lvalue dynamic_cast");
201 
202     if (DestPtr)
203       CGF.CGM.ErrorUnsupported(E, "lvalue dynamic_cast with a destination");
204     break;
205   }
206 
207   case CastExpr::CK_ToUnion: {
208     // GCC union extension
209     QualType PtrTy =
210     CGF.getContext().getPointerType(E->getSubExpr()->getType());
211     llvm::Value *CastPtr = Builder.CreateBitCast(DestPtr,
212                                                  CGF.ConvertType(PtrTy));
213     EmitInitializationToLValue(E->getSubExpr(),
214                                LValue::MakeAddr(CastPtr, Qualifiers()),
215                                E->getSubExpr()->getType());
216     break;
217   }
218 
219   case CastExpr::CK_DerivedToBase:
220   case CastExpr::CK_BaseToDerived:
221   case CastExpr::CK_UncheckedDerivedToBase: {
222     assert(0 && "cannot perform hierarchy conversion in EmitAggExpr: "
223                 "should have been unpacked before we got here");
224     break;
225   }
226 
227   // FIXME: Remove the CK_Unknown check here.
228   case CastExpr::CK_Unknown:
229   case CastExpr::CK_NoOp:
230   case CastExpr::CK_UserDefinedConversion:
231   case CastExpr::CK_ConstructorConversion:
232     assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(),
233                                                    E->getType()) &&
234            "Implicit cast types must be compatible");
235     Visit(E->getSubExpr());
236     break;
237 
238   case CastExpr::CK_NullToMemberPointer: {
239     // If the subexpression's type is the C++0x nullptr_t, emit the
240     // subexpression, which may have side effects.
241     if (E->getSubExpr()->getType()->isNullPtrType())
242       Visit(E->getSubExpr());
243 
244     const llvm::Type *PtrDiffTy =
245       CGF.ConvertType(CGF.getContext().getPointerDiffType());
246 
247     llvm::Value *NullValue = llvm::Constant::getNullValue(PtrDiffTy);
248     llvm::Value *Ptr = Builder.CreateStructGEP(DestPtr, 0, "ptr");
249     Builder.CreateStore(NullValue, Ptr, VolatileDest);
250 
251     llvm::Value *Adj = Builder.CreateStructGEP(DestPtr, 1, "adj");
252     Builder.CreateStore(NullValue, Adj, VolatileDest);
253 
254     break;
255   }
256 
257   case CastExpr::CK_BitCast: {
258     // This must be a member function pointer cast.
259     Visit(E->getSubExpr());
260     break;
261   }
262 
263   case CastExpr::CK_DerivedToBaseMemberPointer:
264   case CastExpr::CK_BaseToDerivedMemberPointer: {
265     QualType SrcType = E->getSubExpr()->getType();
266 
267     llvm::Value *Src = CGF.CreateMemTemp(SrcType, "tmp");
268     CGF.EmitAggExpr(E->getSubExpr(), Src, SrcType.isVolatileQualified());
269 
270     llvm::Value *SrcPtr = Builder.CreateStructGEP(Src, 0, "src.ptr");
271     SrcPtr = Builder.CreateLoad(SrcPtr);
272 
273     llvm::Value *SrcAdj = Builder.CreateStructGEP(Src, 1, "src.adj");
274     SrcAdj = Builder.CreateLoad(SrcAdj);
275 
276     llvm::Value *DstPtr = Builder.CreateStructGEP(DestPtr, 0, "dst.ptr");
277     Builder.CreateStore(SrcPtr, DstPtr, VolatileDest);
278 
279     llvm::Value *DstAdj = Builder.CreateStructGEP(DestPtr, 1, "dst.adj");
280 
281     // Now See if we need to update the adjustment.
282     const CXXRecordDecl *BaseDecl =
283       cast<CXXRecordDecl>(SrcType->getAs<MemberPointerType>()->
284                           getClass()->getAs<RecordType>()->getDecl());
285     const CXXRecordDecl *DerivedDecl =
286       cast<CXXRecordDecl>(E->getType()->getAs<MemberPointerType>()->
287                           getClass()->getAs<RecordType>()->getDecl());
288     if (E->getCastKind() == CastExpr::CK_DerivedToBaseMemberPointer)
289       std::swap(DerivedDecl, BaseDecl);
290 
291     if (llvm::Constant *Adj =
292           CGF.CGM.GetNonVirtualBaseClassOffset(DerivedDecl, E->getBasePath())) {
293       if (E->getCastKind() == CastExpr::CK_DerivedToBaseMemberPointer)
294         SrcAdj = Builder.CreateSub(SrcAdj, Adj, "adj");
295       else
296         SrcAdj = Builder.CreateAdd(SrcAdj, Adj, "adj");
297     }
298 
299     Builder.CreateStore(SrcAdj, DstAdj, VolatileDest);
300     break;
301   }
302   }
303 }
304 
305 void AggExprEmitter::VisitCallExpr(const CallExpr *E) {
306   if (E->getCallReturnType()->isReferenceType()) {
307     EmitAggLoadOfLValue(E);
308     return;
309   }
310 
311   // If the struct doesn't require GC, we can just pass the destination
312   // directly to EmitCall.
313   if (!RequiresGCollection) {
314     CGF.EmitCallExpr(E, getReturnValueSlot());
315     return;
316   }
317 
318   RValue RV = CGF.EmitCallExpr(E);
319   EmitFinalDestCopy(E, RV);
320 }
321 
322 void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
323   CGF.EmitObjCMessageExpr(E, getReturnValueSlot());
324 }
325 
326 void AggExprEmitter::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
327   CGF.EmitObjCPropertyGet(E, getReturnValueSlot());
328 }
329 
330 void AggExprEmitter::VisitObjCImplicitSetterGetterRefExpr(
331                                    ObjCImplicitSetterGetterRefExpr *E) {
332   CGF.EmitObjCPropertyGet(E, getReturnValueSlot());
333 }
334 
335 void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {
336   CGF.EmitAnyExpr(E->getLHS(), 0, false, true);
337   CGF.EmitAggExpr(E->getRHS(), DestPtr, VolatileDest,
338                   /*IgnoreResult=*/false, IsInitializer);
339 }
340 
341 void AggExprEmitter::VisitUnaryAddrOf(const UnaryOperator *E) {
342   // We have a member function pointer.
343   const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
344   (void) MPT;
345   assert(MPT->getPointeeType()->isFunctionProtoType() &&
346          "Unexpected member pointer type!");
347 
348   // The creation of member function pointers has no side effects; if
349   // there is no destination pointer, we have nothing to do.
350   if (!DestPtr)
351     return;
352 
353   const DeclRefExpr *DRE = cast<DeclRefExpr>(E->getSubExpr());
354   const CXXMethodDecl *MD =
355     cast<CXXMethodDecl>(DRE->getDecl())->getCanonicalDecl();
356 
357   const llvm::Type *PtrDiffTy =
358     CGF.ConvertType(CGF.getContext().getPointerDiffType());
359 
360 
361   llvm::Value *DstPtr = Builder.CreateStructGEP(DestPtr, 0, "dst.ptr");
362   llvm::Value *FuncPtr;
363 
364   if (MD->isVirtual()) {
365     int64_t Index = CGF.CGM.getVTables().getMethodVTableIndex(MD);
366 
367     // FIXME: We shouldn't use / 8 here.
368     uint64_t PointerWidthInBytes =
369       CGF.CGM.getContext().Target.getPointerWidth(0) / 8;
370 
371     // Itanium C++ ABI 2.3:
372     //   For a non-virtual function, this field is a simple function pointer.
373     //   For a virtual function, it is 1 plus the virtual table offset
374     //   (in bytes) of the function, represented as a ptrdiff_t.
375     FuncPtr = llvm::ConstantInt::get(PtrDiffTy,
376                                      (Index * PointerWidthInBytes) + 1);
377   } else {
378     const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
379     const llvm::Type *Ty =
380       CGF.CGM.getTypes().GetFunctionType(CGF.CGM.getTypes().getFunctionInfo(MD),
381                                          FPT->isVariadic());
382     llvm::Constant *Fn = CGF.CGM.GetAddrOfFunction(MD, Ty);
383     FuncPtr = llvm::ConstantExpr::getPtrToInt(Fn, PtrDiffTy);
384   }
385   Builder.CreateStore(FuncPtr, DstPtr, VolatileDest);
386 
387   llvm::Value *AdjPtr = Builder.CreateStructGEP(DestPtr, 1, "dst.adj");
388 
389   // The adjustment will always be 0.
390   Builder.CreateStore(llvm::ConstantInt::get(PtrDiffTy, 0), AdjPtr,
391                       VolatileDest);
392 }
393 
394 void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
395   CGF.EmitCompoundStmt(*E->getSubStmt(), true, DestPtr, VolatileDest);
396 }
397 
398 void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
399   if (E->getOpcode() == BinaryOperator::PtrMemD ||
400       E->getOpcode() == BinaryOperator::PtrMemI)
401     VisitPointerToDataMemberBinaryOperator(E);
402   else
403     CGF.ErrorUnsupported(E, "aggregate binary expression");
404 }
405 
406 void AggExprEmitter::VisitPointerToDataMemberBinaryOperator(
407                                                     const BinaryOperator *E) {
408   LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E);
409   EmitFinalDestCopy(E, LV);
410 }
411 
412 void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
413   // For an assignment to work, the value on the right has
414   // to be compatible with the value on the left.
415   assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
416                                                  E->getRHS()->getType())
417          && "Invalid assignment");
418   LValue LHS = CGF.EmitLValue(E->getLHS());
419 
420   // We have to special case property setters, otherwise we must have
421   // a simple lvalue (no aggregates inside vectors, bitfields).
422   if (LHS.isPropertyRef()) {
423     llvm::Value *AggLoc = DestPtr;
424     if (!AggLoc)
425       AggLoc = CGF.CreateMemTemp(E->getRHS()->getType());
426     CGF.EmitAggExpr(E->getRHS(), AggLoc, VolatileDest);
427     CGF.EmitObjCPropertySet(LHS.getPropertyRefExpr(),
428                             RValue::getAggregate(AggLoc, VolatileDest));
429   } else if (LHS.isKVCRef()) {
430     llvm::Value *AggLoc = DestPtr;
431     if (!AggLoc)
432       AggLoc = CGF.CreateMemTemp(E->getRHS()->getType());
433     CGF.EmitAggExpr(E->getRHS(), AggLoc, VolatileDest);
434     CGF.EmitObjCPropertySet(LHS.getKVCRefExpr(),
435                             RValue::getAggregate(AggLoc, VolatileDest));
436   } else {
437     bool RequiresGCollection = false;
438     if (CGF.getContext().getLangOptions().NeXTRuntime) {
439       QualType LHSTy = E->getLHS()->getType();
440       if (const RecordType *FDTTy = LHSTy.getTypePtr()->getAs<RecordType>())
441         RequiresGCollection = FDTTy->getDecl()->hasObjectMember();
442     }
443     // Codegen the RHS so that it stores directly into the LHS.
444     CGF.EmitAggExpr(E->getRHS(), LHS.getAddress(), LHS.isVolatileQualified(),
445                     false, false, RequiresGCollection);
446     EmitFinalDestCopy(E, LHS, true);
447   }
448 }
449 
450 void AggExprEmitter::VisitConditionalOperator(const ConditionalOperator *E) {
451   if (!E->getLHS()) {
452     CGF.ErrorUnsupported(E, "conditional operator with missing LHS");
453     return;
454   }
455 
456   llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
457   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
458   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
459 
460   CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
461 
462   CGF.BeginConditionalBranch();
463   CGF.EmitBlock(LHSBlock);
464 
465   // Handle the GNU extension for missing LHS.
466   assert(E->getLHS() && "Must have LHS for aggregate value");
467 
468   Visit(E->getLHS());
469   CGF.EndConditionalBranch();
470   CGF.EmitBranch(ContBlock);
471 
472   CGF.BeginConditionalBranch();
473   CGF.EmitBlock(RHSBlock);
474 
475   Visit(E->getRHS());
476   CGF.EndConditionalBranch();
477   CGF.EmitBranch(ContBlock);
478 
479   CGF.EmitBlock(ContBlock);
480 }
481 
482 void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) {
483   Visit(CE->getChosenSubExpr(CGF.getContext()));
484 }
485 
486 void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
487   llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
488   llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
489 
490   if (!ArgPtr) {
491     CGF.ErrorUnsupported(VE, "aggregate va_arg expression");
492     return;
493   }
494 
495   EmitFinalDestCopy(VE, LValue::MakeAddr(ArgPtr, Qualifiers()));
496 }
497 
498 void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
499   llvm::Value *Val = DestPtr;
500 
501   if (!Val) {
502     // Create a temporary variable.
503     Val = CGF.CreateMemTemp(E->getType(), "tmp");
504 
505     // FIXME: volatile
506     CGF.EmitAggExpr(E->getSubExpr(), Val, false);
507   } else
508     Visit(E->getSubExpr());
509 
510   // Don't make this a live temporary if we're emitting an initializer expr.
511   if (!IsInitializer)
512     CGF.PushCXXTemporary(E->getTemporary(), Val);
513 }
514 
515 void
516 AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) {
517   llvm::Value *Val = DestPtr;
518 
519   if (!Val) {
520     // Create a temporary variable.
521     Val = CGF.CreateMemTemp(E->getType(), "tmp");
522   }
523 
524   if (E->requiresZeroInitialization())
525     EmitNullInitializationToLValue(LValue::MakeAddr(Val,
526                                                     // FIXME: Qualifiers()?
527                                                  E->getType().getQualifiers()),
528                                    E->getType());
529 
530   CGF.EmitCXXConstructExpr(Val, E);
531 }
532 
533 void AggExprEmitter::VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E) {
534   llvm::Value *Val = DestPtr;
535 
536   CGF.EmitCXXExprWithTemporaries(E, Val, VolatileDest, IsInitializer);
537 }
538 
539 void AggExprEmitter::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E) {
540   llvm::Value *Val = DestPtr;
541 
542   if (!Val) {
543     // Create a temporary variable.
544     Val = CGF.CreateMemTemp(E->getType(), "tmp");
545   }
546   LValue LV = LValue::MakeAddr(Val, Qualifiers());
547   EmitNullInitializationToLValue(LV, E->getType());
548 }
549 
550 void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
551   llvm::Value *Val = DestPtr;
552 
553   if (!Val) {
554     // Create a temporary variable.
555     Val = CGF.CreateMemTemp(E->getType(), "tmp");
556   }
557   LValue LV = LValue::MakeAddr(Val, Qualifiers());
558   EmitNullInitializationToLValue(LV, E->getType());
559 }
560 
561 void
562 AggExprEmitter::EmitInitializationToLValue(Expr* E, LValue LV, QualType T) {
563   // FIXME: Ignore result?
564   // FIXME: Are initializers affected by volatile?
565   if (isa<ImplicitValueInitExpr>(E)) {
566     EmitNullInitializationToLValue(LV, T);
567   } else if (T->isReferenceType()) {
568     RValue RV = CGF.EmitReferenceBindingToExpr(E, /*IsInitializer=*/false);
569     CGF.EmitStoreThroughLValue(RV, LV, T);
570   } else if (T->isAnyComplexType()) {
571     CGF.EmitComplexExprIntoAddr(E, LV.getAddress(), false);
572   } else if (CGF.hasAggregateLLVMType(T)) {
573     CGF.EmitAnyExpr(E, LV.getAddress(), false);
574   } else {
575     CGF.EmitStoreThroughLValue(CGF.EmitAnyExpr(E), LV, T);
576   }
577 }
578 
579 void AggExprEmitter::EmitNullInitializationToLValue(LValue LV, QualType T) {
580   if (!CGF.hasAggregateLLVMType(T)) {
581     // For non-aggregates, we can store zero
582     llvm::Value *Null = llvm::Constant::getNullValue(CGF.ConvertType(T));
583     CGF.EmitStoreThroughLValue(RValue::get(Null), LV, T);
584   } else {
585     // Otherwise, just memset the whole thing to zero.  This is legal
586     // because in LLVM, all default initializers are guaranteed to have a
587     // bit pattern of all zeros.
588     // FIXME: That isn't true for member pointers!
589     // There's a potential optimization opportunity in combining
590     // memsets; that would be easy for arrays, but relatively
591     // difficult for structures with the current code.
592     CGF.EmitMemSetToZero(LV.getAddress(), T);
593   }
594 }
595 
596 void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
597 #if 0
598   // FIXME: Assess perf here?  Figure out what cases are worth optimizing here
599   // (Length of globals? Chunks of zeroed-out space?).
600   //
601   // If we can, prefer a copy from a global; this is a lot less code for long
602   // globals, and it's easier for the current optimizers to analyze.
603   if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) {
604     llvm::GlobalVariable* GV =
605     new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true,
606                              llvm::GlobalValue::InternalLinkage, C, "");
607     EmitFinalDestCopy(E, LValue::MakeAddr(GV, Qualifiers()));
608     return;
609   }
610 #endif
611   if (E->hadArrayRangeDesignator()) {
612     CGF.ErrorUnsupported(E, "GNU array range designator extension");
613   }
614 
615   // Handle initialization of an array.
616   if (E->getType()->isArrayType()) {
617     const llvm::PointerType *APType =
618       cast<llvm::PointerType>(DestPtr->getType());
619     const llvm::ArrayType *AType =
620       cast<llvm::ArrayType>(APType->getElementType());
621 
622     uint64_t NumInitElements = E->getNumInits();
623 
624     if (E->getNumInits() > 0) {
625       QualType T1 = E->getType();
626       QualType T2 = E->getInit(0)->getType();
627       if (CGF.getContext().hasSameUnqualifiedType(T1, T2)) {
628         EmitAggLoadOfLValue(E->getInit(0));
629         return;
630       }
631     }
632 
633     uint64_t NumArrayElements = AType->getNumElements();
634     QualType ElementType = CGF.getContext().getCanonicalType(E->getType());
635     ElementType = CGF.getContext().getAsArrayType(ElementType)->getElementType();
636 
637     // FIXME: were we intentionally ignoring address spaces and GC attributes?
638     Qualifiers Quals = CGF.MakeQualifiers(ElementType);
639 
640     for (uint64_t i = 0; i != NumArrayElements; ++i) {
641       llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array");
642       if (i < NumInitElements)
643         EmitInitializationToLValue(E->getInit(i),
644                                    LValue::MakeAddr(NextVal, Quals),
645                                    ElementType);
646       else
647         EmitNullInitializationToLValue(LValue::MakeAddr(NextVal, Quals),
648                                        ElementType);
649     }
650     return;
651   }
652 
653   assert(E->getType()->isRecordType() && "Only support structs/unions here!");
654 
655   // Do struct initialization; this code just sets each individual member
656   // to the approprate value.  This makes bitfield support automatic;
657   // the disadvantage is that the generated code is more difficult for
658   // the optimizer, especially with bitfields.
659   unsigned NumInitElements = E->getNumInits();
660   RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl();
661   unsigned CurInitVal = 0;
662 
663   if (E->getType()->isUnionType()) {
664     // Only initialize one field of a union. The field itself is
665     // specified by the initializer list.
666     if (!E->getInitializedFieldInUnion()) {
667       // Empty union; we have nothing to do.
668 
669 #ifndef NDEBUG
670       // Make sure that it's really an empty and not a failure of
671       // semantic analysis.
672       for (RecordDecl::field_iterator Field = SD->field_begin(),
673                                    FieldEnd = SD->field_end();
674            Field != FieldEnd; ++Field)
675         assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed");
676 #endif
677       return;
678     }
679 
680     // FIXME: volatility
681     FieldDecl *Field = E->getInitializedFieldInUnion();
682     LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestPtr, Field, 0);
683 
684     if (NumInitElements) {
685       // Store the initializer into the field
686       EmitInitializationToLValue(E->getInit(0), FieldLoc, Field->getType());
687     } else {
688       // Default-initialize to null
689       EmitNullInitializationToLValue(FieldLoc, Field->getType());
690     }
691 
692     return;
693   }
694 
695   // If we're initializing the whole aggregate, just do it in place.
696   // FIXME: This is a hack around an AST bug (PR6537).
697   if (NumInitElements == 1 && E->getType() == E->getInit(0)->getType()) {
698     EmitInitializationToLValue(E->getInit(0),
699                                LValue::MakeAddr(DestPtr, Qualifiers()),
700                                E->getType());
701     return;
702   }
703 
704 
705   // Here we iterate over the fields; this makes it simpler to both
706   // default-initialize fields and skip over unnamed fields.
707   for (RecordDecl::field_iterator Field = SD->field_begin(),
708                                FieldEnd = SD->field_end();
709        Field != FieldEnd; ++Field) {
710     // We're done once we hit the flexible array member
711     if (Field->getType()->isIncompleteArrayType())
712       break;
713 
714     if (Field->isUnnamedBitfield())
715       continue;
716 
717     // FIXME: volatility
718     LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestPtr, *Field, 0);
719     // We never generate write-barries for initialized fields.
720     LValue::SetObjCNonGC(FieldLoc, true);
721     if (CurInitVal < NumInitElements) {
722       // Store the initializer into the field.
723       EmitInitializationToLValue(E->getInit(CurInitVal++), FieldLoc,
724                                  Field->getType());
725     } else {
726       // We're out of initalizers; default-initialize to null
727       EmitNullInitializationToLValue(FieldLoc, Field->getType());
728     }
729   }
730 }
731 
732 //===----------------------------------------------------------------------===//
733 //                        Entry Points into this File
734 //===----------------------------------------------------------------------===//
735 
736 /// EmitAggExpr - Emit the computation of the specified expression of aggregate
737 /// type.  The result is computed into DestPtr.  Note that if DestPtr is null,
738 /// the value of the aggregate expression is not needed.  If VolatileDest is
739 /// true, DestPtr cannot be 0.
740 //
741 // FIXME: Take Qualifiers object.
742 void CodeGenFunction::EmitAggExpr(const Expr *E, llvm::Value *DestPtr,
743                                   bool VolatileDest, bool IgnoreResult,
744                                   bool IsInitializer,
745                                   bool RequiresGCollection) {
746   assert(E && hasAggregateLLVMType(E->getType()) &&
747          "Invalid aggregate expression to emit");
748   assert ((DestPtr != 0 || VolatileDest == false)
749           && "volatile aggregate can't be 0");
750 
751   AggExprEmitter(*this, DestPtr, VolatileDest, IgnoreResult, IsInitializer,
752                  RequiresGCollection)
753     .Visit(const_cast<Expr*>(E));
754 }
755 
756 LValue CodeGenFunction::EmitAggExprToLValue(const Expr *E) {
757   assert(hasAggregateLLVMType(E->getType()) && "Invalid argument!");
758   Qualifiers Q = MakeQualifiers(E->getType());
759   llvm::Value *Temp = CreateMemTemp(E->getType());
760   EmitAggExpr(E, Temp, Q.hasVolatile());
761   return LValue::MakeAddr(Temp, Q);
762 }
763 
764 void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr,
765                                         llvm::Value *SrcPtr, QualType Ty,
766                                         bool isVolatile) {
767   assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
768 
769   if (getContext().getLangOptions().CPlusPlus) {
770     if (const RecordType *RT = Ty->getAs<RecordType>()) {
771       CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
772       assert((Record->hasTrivialCopyConstructor() ||
773               Record->hasTrivialCopyAssignment()) &&
774              "Trying to aggregate-copy a type without a trivial copy "
775              "constructor or assignment operator");
776       // Ignore empty classes in C++.
777       if (Record->isEmpty())
778         return;
779     }
780   }
781 
782   // Aggregate assignment turns into llvm.memcpy.  This is almost valid per
783   // C99 6.5.16.1p3, which states "If the value being stored in an object is
784   // read from another object that overlaps in anyway the storage of the first
785   // object, then the overlap shall be exact and the two objects shall have
786   // qualified or unqualified versions of a compatible type."
787   //
788   // memcpy is not defined if the source and destination pointers are exactly
789   // equal, but other compilers do this optimization, and almost every memcpy
790   // implementation handles this case safely.  If there is a libc that does not
791   // safely handle this, we can add a target hook.
792   const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
793   if (DestPtr->getType() != BP)
794     DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
795   if (SrcPtr->getType() != BP)
796     SrcPtr = Builder.CreateBitCast(SrcPtr, BP, "tmp");
797 
798   // Get size and alignment info for this aggregate.
799   std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
800 
801   // FIXME: Handle variable sized types.
802   const llvm::Type *IntPtr =
803           llvm::IntegerType::get(VMContext, LLVMPointerWidth);
804 
805   // FIXME: If we have a volatile struct, the optimizer can remove what might
806   // appear to be `extra' memory ops:
807   //
808   // volatile struct { int i; } a, b;
809   //
810   // int main() {
811   //   a = b;
812   //   a = b;
813   // }
814   //
815   // we need to use a different call here.  We use isVolatile to indicate when
816   // either the source or the destination is volatile.
817   const llvm::Type *I1Ty = llvm::Type::getInt1Ty(VMContext);
818   const llvm::Type *I8Ty = llvm::Type::getInt8Ty(VMContext);
819   const llvm::Type *I32Ty = llvm::Type::getInt32Ty(VMContext);
820 
821   const llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType());
822   const llvm::Type *DBP = llvm::PointerType::get(I8Ty, DPT->getAddressSpace());
823   if (DestPtr->getType() != DBP)
824     DestPtr = Builder.CreateBitCast(DestPtr, DBP, "tmp");
825 
826   const llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType());
827   const llvm::Type *SBP = llvm::PointerType::get(I8Ty, SPT->getAddressSpace());
828   if (SrcPtr->getType() != SBP)
829     SrcPtr = Builder.CreateBitCast(SrcPtr, SBP, "tmp");
830 
831   Builder.CreateCall5(CGM.getMemCpyFn(DestPtr->getType(), SrcPtr->getType(),
832                                       IntPtr),
833                       DestPtr, SrcPtr,
834                       // TypeInfo.first describes size in bits.
835                       llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
836                       llvm::ConstantInt::get(I32Ty,  TypeInfo.second/8),
837                       llvm::ConstantInt::get(I1Ty,  isVolatile));
838 }
839