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