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 public:
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) {
46   }
47 
48   //===--------------------------------------------------------------------===//
49   //                               Utilities
50   //===--------------------------------------------------------------------===//
51 
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);
56 
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);
60 
61   //===--------------------------------------------------------------------===//
62   //                            Visitor Methods
63   //===--------------------------------------------------------------------===//
64 
65   void VisitStmt(Stmt *S) {
66     CGF.ErrorUnsupported(S, "aggregate expression");
67   }
68   void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); }
69   void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); }
70 
71   // l-values.
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);
78   }
79   void VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
80     EmitAggLoadOfLValue(E);
81   }
82   void VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
83     EmitAggLoadOfLValue(E);
84   }
85   void VisitPredefinedExpr(const PredefinedExpr *E) {
86     EmitAggLoadOfLValue(E);
87   }
88 
89   // Operators.
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);
98 
99   void VisitObjCMessageExpr(ObjCMessageExpr *E);
100   void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
101     EmitAggLoadOfLValue(E);
102   }
103   void VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E);
104   void VisitObjCImplicitSetterGetterRefExpr(ObjCImplicitSetterGetterRefExpr *E);
105 
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());
112   }
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); }
118 
119   void VisitVAArgExpr(VAArgExpr *E);
120 
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); }
125 };
126 }  // end anonymous namespace.
127 
128 //===----------------------------------------------------------------------===//
129 //                                Utilities
130 //===----------------------------------------------------------------------===//
131 
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);
138 }
139 
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!");
143 
144   // If the result is ignored, don't copy from the value.
145   if (DestPtr == 0) {
146     if (!Src.isVolatileQualified() || (IgnoreResult && Ignore))
147       return;
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.CreateTempAlloca(CGF.ConvertType(E->getType()), "agg.tmp");
151   }
152 
153   if (RequiresGCollection) {
154     CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF,
155                                               DestPtr, Src.getAggregateAddr(),
156                                               E->getType());
157     return;
158   }
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());
165 }
166 
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");
170 
171   EmitFinalDestCopy(E, RValue::getAggregate(Src.getAddress(),
172                                             Src.isVolatileQualified()),
173                     Ignore);
174 }
175 
176 //===----------------------------------------------------------------------===//
177 //                            Visitor Methods
178 //===----------------------------------------------------------------------===//
179 
180 void AggExprEmitter::VisitCastExpr(CastExpr *E) {
181   switch (E->getCastKind()) {
182   default: assert(0 && "Unhandled cast kind!");
183 
184   case CastExpr::CK_ToUnion: {
185     // GCC union extension
186     QualType PtrTy =
187     CGF.getContext().getPointerType(E->getSubExpr()->getType());
188     llvm::Value *CastPtr = Builder.CreateBitCast(DestPtr,
189                                                  CGF.ConvertType(PtrTy));
190     EmitInitializationToLValue(E->getSubExpr(),
191                                LValue::MakeAddr(CastPtr, Qualifiers()),
192                                E->getType());
193     break;
194   }
195 
196   // FIXME: Remove the CK_Unknown check here.
197   case CastExpr::CK_Unknown:
198   case CastExpr::CK_NoOp:
199   case CastExpr::CK_UserDefinedConversion:
200   case CastExpr::CK_ConstructorConversion:
201     assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(),
202                                                    E->getType()) &&
203            "Implicit cast types must be compatible");
204     Visit(E->getSubExpr());
205     break;
206 
207   case CastExpr::CK_NullToMemberPointer: {
208     const llvm::Type *PtrDiffTy =
209       CGF.ConvertType(CGF.getContext().getPointerDiffType());
210 
211     llvm::Value *NullValue = llvm::Constant::getNullValue(PtrDiffTy);
212     llvm::Value *Ptr = Builder.CreateStructGEP(DestPtr, 0, "ptr");
213     Builder.CreateStore(NullValue, Ptr, VolatileDest);
214 
215     llvm::Value *Adj = Builder.CreateStructGEP(DestPtr, 1, "adj");
216     Builder.CreateStore(NullValue, Adj, VolatileDest);
217 
218     break;
219   }
220 
221   case CastExpr::CK_BitCast: {
222     // This must be a member function pointer cast.
223     Visit(E->getSubExpr());
224     break;
225   }
226 
227   case CastExpr::CK_DerivedToBaseMemberPointer:
228   case CastExpr::CK_BaseToDerivedMemberPointer: {
229     QualType SrcType = E->getSubExpr()->getType();
230 
231     llvm::Value *Src = CGF.CreateTempAlloca(CGF.ConvertTypeForMem(SrcType),
232                                             "tmp");
233     CGF.EmitAggExpr(E->getSubExpr(), Src, SrcType.isVolatileQualified());
234 
235     llvm::Value *SrcPtr = Builder.CreateStructGEP(Src, 0, "src.ptr");
236     SrcPtr = Builder.CreateLoad(SrcPtr);
237 
238     llvm::Value *SrcAdj = Builder.CreateStructGEP(Src, 1, "src.adj");
239     SrcAdj = Builder.CreateLoad(SrcAdj);
240 
241     llvm::Value *DstPtr = Builder.CreateStructGEP(DestPtr, 0, "dst.ptr");
242     Builder.CreateStore(SrcPtr, DstPtr, VolatileDest);
243 
244     llvm::Value *DstAdj = Builder.CreateStructGEP(DestPtr, 1, "dst.adj");
245 
246     // Now See if we need to update the adjustment.
247     const CXXRecordDecl *BaseDecl =
248       cast<CXXRecordDecl>(SrcType->getAs<MemberPointerType>()->
249                           getClass()->getAs<RecordType>()->getDecl());
250     const CXXRecordDecl *DerivedDecl =
251       cast<CXXRecordDecl>(E->getType()->getAs<MemberPointerType>()->
252                           getClass()->getAs<RecordType>()->getDecl());
253     if (E->getCastKind() == CastExpr::CK_DerivedToBaseMemberPointer)
254       std::swap(DerivedDecl, BaseDecl);
255 
256     if (llvm::Constant *Adj =
257           CGF.CGM.GetNonVirtualBaseClassOffset(DerivedDecl, BaseDecl)) {
258       if (E->getCastKind() == CastExpr::CK_DerivedToBaseMemberPointer)
259         SrcAdj = Builder.CreateSub(SrcAdj, Adj, "adj");
260       else
261         SrcAdj = Builder.CreateAdd(SrcAdj, Adj, "adj");
262     }
263 
264     Builder.CreateStore(SrcAdj, DstAdj, VolatileDest);
265     break;
266   }
267   }
268 }
269 
270 void AggExprEmitter::VisitCallExpr(const CallExpr *E) {
271   if (E->getCallReturnType()->isReferenceType()) {
272     EmitAggLoadOfLValue(E);
273     return;
274   }
275 
276   // If the struct doesn't require GC, we can just pass the destination
277   // directly to EmitCall.
278   if (!RequiresGCollection) {
279     CGF.EmitCallExpr(E, ReturnValueSlot(DestPtr, VolatileDest));
280     return;
281   }
282 
283   RValue RV = CGF.EmitCallExpr(E);
284   EmitFinalDestCopy(E, RV);
285 }
286 
287 void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
288   RValue RV = CGF.EmitObjCMessageExpr(E);
289   EmitFinalDestCopy(E, RV);
290 }
291 
292 void AggExprEmitter::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
293   RValue RV = CGF.EmitObjCPropertyGet(E);
294   EmitFinalDestCopy(E, RV);
295 }
296 
297 void AggExprEmitter::VisitObjCImplicitSetterGetterRefExpr(
298                                    ObjCImplicitSetterGetterRefExpr *E) {
299   RValue RV = CGF.EmitObjCPropertyGet(E);
300   EmitFinalDestCopy(E, RV);
301 }
302 
303 void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {
304   CGF.EmitAnyExpr(E->getLHS(), 0, false, true);
305   CGF.EmitAggExpr(E->getRHS(), DestPtr, VolatileDest,
306                   /*IgnoreResult=*/false, IsInitializer);
307 }
308 
309 void AggExprEmitter::VisitUnaryAddrOf(const UnaryOperator *E) {
310   // We have a member function pointer.
311   const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
312   (void) MPT;
313   assert(MPT->getPointeeType()->isFunctionProtoType() &&
314          "Unexpected member pointer type!");
315 
316   const DeclRefExpr *DRE = cast<DeclRefExpr>(E->getSubExpr());
317   const CXXMethodDecl *MD =
318     cast<CXXMethodDecl>(DRE->getDecl())->getCanonicalDecl();
319 
320   const llvm::Type *PtrDiffTy =
321     CGF.ConvertType(CGF.getContext().getPointerDiffType());
322 
323   llvm::Value *DstPtr = Builder.CreateStructGEP(DestPtr, 0, "dst.ptr");
324   llvm::Value *FuncPtr;
325 
326   if (MD->isVirtual()) {
327     int64_t Index =
328       CGF.CGM.getVtableInfo().getMethodVtableIndex(MD);
329 
330     FuncPtr = llvm::ConstantInt::get(PtrDiffTy, Index + 1);
331   } else {
332     FuncPtr = llvm::ConstantExpr::getPtrToInt(CGF.CGM.GetAddrOfFunction(MD),
333                                               PtrDiffTy);
334   }
335   Builder.CreateStore(FuncPtr, DstPtr, VolatileDest);
336 
337   llvm::Value *AdjPtr = Builder.CreateStructGEP(DestPtr, 1, "dst.adj");
338 
339   // The adjustment will always be 0.
340   Builder.CreateStore(llvm::ConstantInt::get(PtrDiffTy, 0), AdjPtr,
341                       VolatileDest);
342 }
343 
344 void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
345   CGF.EmitCompoundStmt(*E->getSubStmt(), true, DestPtr, VolatileDest);
346 }
347 
348 void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
349   if (E->getOpcode() == BinaryOperator::PtrMemD ||
350       E->getOpcode() == BinaryOperator::PtrMemI)
351     VisitPointerToDataMemberBinaryOperator(E);
352   else
353     CGF.ErrorUnsupported(E, "aggregate binary expression");
354 }
355 
356 void AggExprEmitter::VisitPointerToDataMemberBinaryOperator(
357                                                     const BinaryOperator *E) {
358   LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E);
359   EmitFinalDestCopy(E, LV);
360 }
361 
362 void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
363   // For an assignment to work, the value on the right has
364   // to be compatible with the value on the left.
365   assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
366                                                  E->getRHS()->getType())
367          && "Invalid assignment");
368   LValue LHS = CGF.EmitLValue(E->getLHS());
369 
370   // We have to special case property setters, otherwise we must have
371   // a simple lvalue (no aggregates inside vectors, bitfields).
372   if (LHS.isPropertyRef()) {
373     llvm::Value *AggLoc = DestPtr;
374     if (!AggLoc)
375       AggLoc = CGF.CreateTempAlloca(CGF.ConvertType(E->getRHS()->getType()));
376     CGF.EmitAggExpr(E->getRHS(), AggLoc, VolatileDest);
377     CGF.EmitObjCPropertySet(LHS.getPropertyRefExpr(),
378                             RValue::getAggregate(AggLoc, VolatileDest));
379   } else if (LHS.isKVCRef()) {
380     llvm::Value *AggLoc = DestPtr;
381     if (!AggLoc)
382       AggLoc = CGF.CreateTempAlloca(CGF.ConvertType(E->getRHS()->getType()));
383     CGF.EmitAggExpr(E->getRHS(), AggLoc, VolatileDest);
384     CGF.EmitObjCPropertySet(LHS.getKVCRefExpr(),
385                             RValue::getAggregate(AggLoc, VolatileDest));
386   } else {
387     bool RequiresGCollection = false;
388     if (CGF.getContext().getLangOptions().NeXTRuntime) {
389       QualType LHSTy = E->getLHS()->getType();
390       if (const RecordType *FDTTy = LHSTy.getTypePtr()->getAs<RecordType>())
391         RequiresGCollection = FDTTy->getDecl()->hasObjectMember();
392     }
393     // Codegen the RHS so that it stores directly into the LHS.
394     CGF.EmitAggExpr(E->getRHS(), LHS.getAddress(), LHS.isVolatileQualified(),
395                     false, false, RequiresGCollection);
396     EmitFinalDestCopy(E, LHS, true);
397   }
398 }
399 
400 void AggExprEmitter::VisitConditionalOperator(const ConditionalOperator *E) {
401   if (!E->getLHS()) {
402     CGF.ErrorUnsupported(E, "conditional operator with missing LHS");
403     return;
404   }
405 
406   llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
407   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
408   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
409 
410   CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
411 
412   CGF.StartConditionalBranch();
413   CGF.EmitBlock(LHSBlock);
414 
415   // Handle the GNU extension for missing LHS.
416   assert(E->getLHS() && "Must have LHS for aggregate value");
417 
418   Visit(E->getLHS());
419   CGF.FinishConditionalBranch();
420   CGF.EmitBranch(ContBlock);
421 
422   CGF.StartConditionalBranch();
423   CGF.EmitBlock(RHSBlock);
424 
425   Visit(E->getRHS());
426   CGF.FinishConditionalBranch();
427   CGF.EmitBranch(ContBlock);
428 
429   CGF.EmitBlock(ContBlock);
430 }
431 
432 void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) {
433   Visit(CE->getChosenSubExpr(CGF.getContext()));
434 }
435 
436 void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
437   llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
438   llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
439 
440   if (!ArgPtr) {
441     CGF.ErrorUnsupported(VE, "aggregate va_arg expression");
442     return;
443   }
444 
445   EmitFinalDestCopy(VE, LValue::MakeAddr(ArgPtr, Qualifiers()));
446 }
447 
448 void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
449   llvm::Value *Val = DestPtr;
450 
451   if (!Val) {
452     // Create a temporary variable.
453     Val = CGF.CreateTempAlloca(CGF.ConvertTypeForMem(E->getType()), "tmp");
454 
455     // FIXME: volatile
456     CGF.EmitAggExpr(E->getSubExpr(), Val, false);
457   } else
458     Visit(E->getSubExpr());
459 
460   // Don't make this a live temporary if we're emitting an initializer expr.
461   if (!IsInitializer)
462     CGF.PushCXXTemporary(E->getTemporary(), Val);
463 }
464 
465 void
466 AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) {
467   llvm::Value *Val = DestPtr;
468 
469   if (!Val) {
470     // Create a temporary variable.
471     Val = CGF.CreateTempAlloca(CGF.ConvertTypeForMem(E->getType()), "tmp");
472   }
473 
474   if (E->requiresZeroInitialization())
475     EmitNullInitializationToLValue(LValue::MakeAddr(Val,
476                                                     // FIXME: Qualifiers()?
477                                                  E->getType().getQualifiers()),
478                                    E->getType());
479 
480   CGF.EmitCXXConstructExpr(Val, E);
481 }
482 
483 void AggExprEmitter::VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E) {
484   llvm::Value *Val = DestPtr;
485 
486   if (!Val) {
487     // Create a temporary variable.
488     Val = CGF.CreateTempAlloca(CGF.ConvertTypeForMem(E->getType()), "tmp");
489   }
490   CGF.EmitCXXExprWithTemporaries(E, Val, VolatileDest, IsInitializer);
491 }
492 
493 void AggExprEmitter::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E) {
494   llvm::Value *Val = DestPtr;
495 
496   if (!Val) {
497     // Create a temporary variable.
498     Val = CGF.CreateTempAlloca(CGF.ConvertTypeForMem(E->getType()), "tmp");
499   }
500   LValue LV = LValue::MakeAddr(Val, Qualifiers());
501   EmitNullInitializationToLValue(LV, E->getType());
502 }
503 
504 void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
505   llvm::Value *Val = DestPtr;
506 
507   if (!Val) {
508     // Create a temporary variable.
509     Val = CGF.CreateTempAlloca(CGF.ConvertTypeForMem(E->getType()), "tmp");
510   }
511   LValue LV = LValue::MakeAddr(Val, Qualifiers());
512   EmitNullInitializationToLValue(LV, E->getType());
513 }
514 
515 void
516 AggExprEmitter::EmitInitializationToLValue(Expr* E, LValue LV, QualType T) {
517   // FIXME: Remove this.
518   T = E->getType();
519 
520   // FIXME: Ignore result?
521   // FIXME: Are initializers affected by volatile?
522   if (isa<ImplicitValueInitExpr>(E)) {
523     EmitNullInitializationToLValue(LV, T);
524   } else if (T->isAnyComplexType()) {
525     CGF.EmitComplexExprIntoAddr(E, LV.getAddress(), false);
526   } else if (CGF.hasAggregateLLVMType(T)) {
527     CGF.EmitAnyExpr(E, LV.getAddress(), false);
528   } else {
529     CGF.EmitStoreThroughLValue(CGF.EmitAnyExpr(E), LV, T);
530   }
531 }
532 
533 void AggExprEmitter::EmitNullInitializationToLValue(LValue LV, QualType T) {
534   if (!CGF.hasAggregateLLVMType(T)) {
535     // For non-aggregates, we can store zero
536     llvm::Value *Null = llvm::Constant::getNullValue(CGF.ConvertType(T));
537     CGF.EmitStoreThroughLValue(RValue::get(Null), LV, T);
538   } else {
539     // Otherwise, just memset the whole thing to zero.  This is legal
540     // because in LLVM, all default initializers are guaranteed to have a
541     // bit pattern of all zeros.
542     // FIXME: That isn't true for member pointers!
543     // There's a potential optimization opportunity in combining
544     // memsets; that would be easy for arrays, but relatively
545     // difficult for structures with the current code.
546     CGF.EmitMemSetToZero(LV.getAddress(), T);
547   }
548 }
549 
550 void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
551 #if 0
552   // FIXME: Assess perf here?  Figure out what cases are worth optimizing here
553   // (Length of globals? Chunks of zeroed-out space?).
554   //
555   // If we can, prefer a copy from a global; this is a lot less code for long
556   // globals, and it's easier for the current optimizers to analyze.
557   if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) {
558     llvm::GlobalVariable* GV =
559     new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true,
560                              llvm::GlobalValue::InternalLinkage, C, "");
561     EmitFinalDestCopy(E, LValue::MakeAddr(GV, Qualifiers()));
562     return;
563   }
564 #endif
565   if (E->hadArrayRangeDesignator()) {
566     CGF.ErrorUnsupported(E, "GNU array range designator extension");
567   }
568 
569   // Handle initialization of an array.
570   if (E->getType()->isArrayType()) {
571     const llvm::PointerType *APType =
572       cast<llvm::PointerType>(DestPtr->getType());
573     const llvm::ArrayType *AType =
574       cast<llvm::ArrayType>(APType->getElementType());
575 
576     uint64_t NumInitElements = E->getNumInits();
577 
578     if (E->getNumInits() > 0) {
579       QualType T1 = E->getType();
580       QualType T2 = E->getInit(0)->getType();
581       if (CGF.getContext().hasSameUnqualifiedType(T1, T2)) {
582         EmitAggLoadOfLValue(E->getInit(0));
583         return;
584       }
585     }
586 
587     uint64_t NumArrayElements = AType->getNumElements();
588     QualType ElementType = CGF.getContext().getCanonicalType(E->getType());
589     ElementType = CGF.getContext().getAsArrayType(ElementType)->getElementType();
590 
591     // FIXME: were we intentionally ignoring address spaces and GC attributes?
592     Qualifiers Quals = CGF.MakeQualifiers(ElementType);
593 
594     for (uint64_t i = 0; i != NumArrayElements; ++i) {
595       llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array");
596       if (i < NumInitElements)
597         EmitInitializationToLValue(E->getInit(i),
598                                    LValue::MakeAddr(NextVal, Quals),
599                                    ElementType);
600       else
601         EmitNullInitializationToLValue(LValue::MakeAddr(NextVal, Quals),
602                                        ElementType);
603     }
604     return;
605   }
606 
607   assert(E->getType()->isRecordType() && "Only support structs/unions here!");
608 
609   // Do struct initialization; this code just sets each individual member
610   // to the approprate value.  This makes bitfield support automatic;
611   // the disadvantage is that the generated code is more difficult for
612   // the optimizer, especially with bitfields.
613   unsigned NumInitElements = E->getNumInits();
614   RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl();
615   unsigned CurInitVal = 0;
616 
617   if (E->getType()->isUnionType()) {
618     // Only initialize one field of a union. The field itself is
619     // specified by the initializer list.
620     if (!E->getInitializedFieldInUnion()) {
621       // Empty union; we have nothing to do.
622 
623 #ifndef NDEBUG
624       // Make sure that it's really an empty and not a failure of
625       // semantic analysis.
626       for (RecordDecl::field_iterator Field = SD->field_begin(),
627                                    FieldEnd = SD->field_end();
628            Field != FieldEnd; ++Field)
629         assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed");
630 #endif
631       return;
632     }
633 
634     // FIXME: volatility
635     FieldDecl *Field = E->getInitializedFieldInUnion();
636     LValue FieldLoc = CGF.EmitLValueForField(DestPtr, Field, 0);
637 
638     if (NumInitElements) {
639       // Store the initializer into the field
640       EmitInitializationToLValue(E->getInit(0), FieldLoc, Field->getType());
641     } else {
642       // Default-initialize to null
643       EmitNullInitializationToLValue(FieldLoc, Field->getType());
644     }
645 
646     return;
647   }
648 
649   // Here we iterate over the fields; this makes it simpler to both
650   // default-initialize fields and skip over unnamed fields.
651   for (RecordDecl::field_iterator Field = SD->field_begin(),
652                                FieldEnd = SD->field_end();
653        Field != FieldEnd; ++Field) {
654     // We're done once we hit the flexible array member
655     if (Field->getType()->isIncompleteArrayType())
656       break;
657 
658     if (Field->isUnnamedBitfield())
659       continue;
660 
661     // FIXME: volatility
662     LValue FieldLoc = CGF.EmitLValueForField(DestPtr, *Field, 0);
663     // We never generate write-barries for initialized fields.
664     LValue::SetObjCNonGC(FieldLoc, true);
665     if (CurInitVal < NumInitElements) {
666       // Store the initializer into the field
667       EmitInitializationToLValue(E->getInit(CurInitVal++), FieldLoc,
668                                  Field->getType());
669     } else {
670       // We're out of initalizers; default-initialize to null
671       EmitNullInitializationToLValue(FieldLoc, Field->getType());
672     }
673   }
674 }
675 
676 //===----------------------------------------------------------------------===//
677 //                        Entry Points into this File
678 //===----------------------------------------------------------------------===//
679 
680 /// EmitAggExpr - Emit the computation of the specified expression of aggregate
681 /// type.  The result is computed into DestPtr.  Note that if DestPtr is null,
682 /// the value of the aggregate expression is not needed.  If VolatileDest is
683 /// true, DestPtr cannot be 0.
684 void CodeGenFunction::EmitAggExpr(const Expr *E, llvm::Value *DestPtr,
685                                   bool VolatileDest, bool IgnoreResult,
686                                   bool IsInitializer,
687                                   bool RequiresGCollection) {
688   assert(E && hasAggregateLLVMType(E->getType()) &&
689          "Invalid aggregate expression to emit");
690   assert ((DestPtr != 0 || VolatileDest == false)
691           && "volatile aggregate can't be 0");
692 
693   AggExprEmitter(*this, DestPtr, VolatileDest, IgnoreResult, IsInitializer,
694                  RequiresGCollection)
695     .Visit(const_cast<Expr*>(E));
696 }
697 
698 void CodeGenFunction::EmitAggregateClear(llvm::Value *DestPtr, QualType Ty) {
699   assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
700 
701   EmitMemSetToZero(DestPtr, Ty);
702 }
703 
704 void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr,
705                                         llvm::Value *SrcPtr, QualType Ty,
706                                         bool isVolatile) {
707   assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
708 
709   // Aggregate assignment turns into llvm.memcpy.  This is almost valid per
710   // C99 6.5.16.1p3, which states "If the value being stored in an object is
711   // read from another object that overlaps in anyway the storage of the first
712   // object, then the overlap shall be exact and the two objects shall have
713   // qualified or unqualified versions of a compatible type."
714   //
715   // memcpy is not defined if the source and destination pointers are exactly
716   // equal, but other compilers do this optimization, and almost every memcpy
717   // implementation handles this case safely.  If there is a libc that does not
718   // safely handle this, we can add a target hook.
719   const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
720   if (DestPtr->getType() != BP)
721     DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
722   if (SrcPtr->getType() != BP)
723     SrcPtr = Builder.CreateBitCast(SrcPtr, BP, "tmp");
724 
725   // Get size and alignment info for this aggregate.
726   std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
727 
728   // FIXME: Handle variable sized types.
729   const llvm::Type *IntPtr =
730           llvm::IntegerType::get(VMContext, LLVMPointerWidth);
731 
732   // FIXME: If we have a volatile struct, the optimizer can remove what might
733   // appear to be `extra' memory ops:
734   //
735   // volatile struct { int i; } a, b;
736   //
737   // int main() {
738   //   a = b;
739   //   a = b;
740   // }
741   //
742   // we need to use a differnt call here.  We use isVolatile to indicate when
743   // either the source or the destination is volatile.
744   Builder.CreateCall4(CGM.getMemCpyFn(),
745                       DestPtr, SrcPtr,
746                       // TypeInfo.first describes size in bits.
747                       llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
748                       llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
749                                              TypeInfo.second/8));
750 }
751