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