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