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