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