1 //===--- CGExprAgg.cpp - Emit LLVM Code from Aggregate Expressions --------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This contains code to emit Aggregate Expr nodes as LLVM code.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CodeGenFunction.h"
15 #include "CodeGenModule.h"
16 #include "CGObjCRuntime.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/StmtVisitor.h"
20 #include "llvm/Constants.h"
21 #include "llvm/Function.h"
22 #include "llvm/GlobalVariable.h"
23 #include "llvm/Intrinsics.h"
24 using namespace clang;
25 using namespace CodeGen;
26 
27 //===----------------------------------------------------------------------===//
28 //                        Aggregate Expression Emitter
29 //===----------------------------------------------------------------------===//
30 
31 namespace  {
32 class AggExprEmitter : public StmtVisitor<AggExprEmitter> {
33   CodeGenFunction &CGF;
34   CGBuilderTy &Builder;
35   AggValueSlot Dest;
36   bool IgnoreResult;
37 
38   ReturnValueSlot getReturnValueSlot() const {
39     // If the destination slot requires garbage collection, we can't
40     // use the real return value slot, because we have to use the GC
41     // API.
42     if (Dest.requiresGCollection()) return ReturnValueSlot();
43 
44     return ReturnValueSlot(Dest.getAddr(), Dest.isVolatile());
45   }
46 
47   AggValueSlot EnsureSlot(QualType T) {
48     if (!Dest.isIgnored()) return Dest;
49     return CGF.CreateAggTemp(T, "agg.tmp.ensured");
50   }
51 
52 public:
53   AggExprEmitter(CodeGenFunction &cgf, AggValueSlot Dest,
54                  bool ignore)
55     : CGF(cgf), Builder(CGF.Builder), Dest(Dest),
56       IgnoreResult(ignore) {
57   }
58 
59   //===--------------------------------------------------------------------===//
60   //                               Utilities
61   //===--------------------------------------------------------------------===//
62 
63   /// EmitAggLoadOfLValue - Given an expression with aggregate type that
64   /// represents a value lvalue, this method emits the address of the lvalue,
65   /// then loads the result into DestPtr.
66   void EmitAggLoadOfLValue(const Expr *E);
67 
68   /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
69   void EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore = false);
70   void EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore = false);
71 
72   void EmitGCMove(const Expr *E, RValue Src);
73 
74   bool TypeRequiresGCollection(QualType T);
75 
76   //===--------------------------------------------------------------------===//
77   //                            Visitor Methods
78   //===--------------------------------------------------------------------===//
79 
80   void VisitStmt(Stmt *S) {
81     CGF.ErrorUnsupported(S, "aggregate expression");
82   }
83   void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); }
84   void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); }
85 
86   // l-values.
87   void VisitDeclRefExpr(DeclRefExpr *DRE) { EmitAggLoadOfLValue(DRE); }
88   void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); }
89   void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); }
90   void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); }
91   void VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
92     EmitAggLoadOfLValue(E);
93   }
94   void VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
95     EmitAggLoadOfLValue(E);
96   }
97   void VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
98     EmitAggLoadOfLValue(E);
99   }
100   void VisitPredefinedExpr(const PredefinedExpr *E) {
101     EmitAggLoadOfLValue(E);
102   }
103 
104   // Operators.
105   void VisitCastExpr(CastExpr *E);
106   void VisitCallExpr(const CallExpr *E);
107   void VisitStmtExpr(const StmtExpr *E);
108   void VisitBinaryOperator(const BinaryOperator *BO);
109   void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO);
110   void VisitBinAssign(const BinaryOperator *E);
111   void VisitBinComma(const BinaryOperator *E);
112 
113   void VisitObjCMessageExpr(ObjCMessageExpr *E);
114   void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
115     EmitAggLoadOfLValue(E);
116   }
117   void VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E);
118   void VisitObjCImplicitSetterGetterRefExpr(ObjCImplicitSetterGetterRefExpr *E);
119 
120   void VisitConditionalOperator(const ConditionalOperator *CO);
121   void VisitChooseExpr(const ChooseExpr *CE);
122   void VisitInitListExpr(InitListExpr *E);
123   void VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
124   void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
125     Visit(DAE->getExpr());
126   }
127   void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
128   void VisitCXXConstructExpr(const CXXConstructExpr *E);
129   void VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E);
130   void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
131   void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); }
132 
133   void VisitVAArgExpr(VAArgExpr *E);
134 
135   void EmitInitializationToLValue(Expr *E, LValue Address, QualType T);
136   void EmitNullInitializationToLValue(LValue Address, QualType T);
137   //  case Expr::ChooseExprClass:
138   void VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); }
139 };
140 }  // end anonymous namespace.
141 
142 //===----------------------------------------------------------------------===//
143 //                                Utilities
144 //===----------------------------------------------------------------------===//
145 
146 /// EmitAggLoadOfLValue - Given an expression with aggregate type that
147 /// represents a value lvalue, this method emits the address of the lvalue,
148 /// then loads the result into DestPtr.
149 void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) {
150   if (CGF.getContext().getLangOptions().CPlusPlus) {
151     if (const CXXConstructExpr *CE = Dest.getCtorExpr()) {
152       // Perform copy initialization of Src into Dest.
153       const CXXConstructorDecl *CD = CE->getConstructor();
154       CXXCtorType Type =
155         (CE->getConstructionKind() == CXXConstructExpr::CK_Complete)
156         ? Ctor_Complete : Ctor_Base;
157       bool ForVirtualBase =
158         CE->getConstructionKind() == CXXConstructExpr::CK_VirtualBase;
159       // Call the constructor.
160       const Stmt * S = dyn_cast<Stmt>(E);
161       clang::ConstExprIterator BegExp(&S);
162       CGF.EmitCXXConstructorCall(CD, Type, ForVirtualBase, Dest.getAddr(),
163                                  BegExp, (BegExp+1));
164       return;
165     }
166   }
167   LValue LV = CGF.EmitLValue(E);
168   EmitFinalDestCopy(E, LV);
169 }
170 
171 /// \brief True if the given aggregate type requires special GC API calls.
172 bool AggExprEmitter::TypeRequiresGCollection(QualType T) {
173   // Only record types have members that might require garbage collection.
174   const RecordType *RecordTy = T->getAs<RecordType>();
175   if (!RecordTy) return false;
176 
177   // Don't mess with non-trivial C++ types.
178   RecordDecl *Record = RecordTy->getDecl();
179   if (isa<CXXRecordDecl>(Record) &&
180       (!cast<CXXRecordDecl>(Record)->hasTrivialCopyConstructor() ||
181        !cast<CXXRecordDecl>(Record)->hasTrivialDestructor()))
182     return false;
183 
184   // Check whether the type has an object member.
185   return Record->hasObjectMember();
186 }
187 
188 /// \brief Perform the final move to DestPtr if RequiresGCollection is set.
189 ///
190 /// The idea is that you do something like this:
191 ///   RValue Result = EmitSomething(..., getReturnValueSlot());
192 ///   EmitGCMove(E, Result);
193 /// If GC doesn't interfere, this will cause the result to be emitted
194 /// directly into the return value slot.  If GC does interfere, a final
195 /// move will be performed.
196 void AggExprEmitter::EmitGCMove(const Expr *E, RValue Src) {
197   if (Dest.requiresGCollection()) {
198     std::pair<uint64_t, unsigned> TypeInfo =
199       CGF.getContext().getTypeInfo(E->getType());
200     unsigned long size = TypeInfo.first/8;
201     const llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType());
202     llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size);
203     CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF, Dest.getAddr(),
204                                                     Src.getAggregateAddr(),
205                                                     SizeVal);
206   }
207 }
208 
209 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
210 void AggExprEmitter::EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore) {
211   assert(Src.isAggregate() && "value must be aggregate value!");
212 
213   // If Dest is ignored, then we're evaluating an aggregate expression
214   // in a context (like an expression statement) that doesn't care
215   // about the result.  C says that an lvalue-to-rvalue conversion is
216   // performed in these cases; C++ says that it is not.  In either
217   // case, we don't actually need to do anything unless the value is
218   // volatile.
219   if (Dest.isIgnored()) {
220     if (!Src.isVolatileQualified() ||
221         CGF.CGM.getLangOptions().CPlusPlus ||
222         (IgnoreResult && Ignore))
223       return;
224     // If the source is volatile, we must read from it; to do that, we need
225     // some place to put it.
226     Dest = CGF.CreateAggTemp(E->getType(), "agg.tmp");
227   }
228 
229   if (Dest.requiresGCollection()) {
230     std::pair<uint64_t, unsigned> TypeInfo =
231     CGF.getContext().getTypeInfo(E->getType());
232     unsigned long size = TypeInfo.first/8;
233     const llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType());
234     llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size);
235     CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF,
236                                                       Dest.getAddr(),
237                                                       Src.getAggregateAddr(),
238                                                       SizeVal);
239     return;
240   }
241 
242   // If the result of the assignment is used, copy the LHS there also.
243   // FIXME: Pass VolatileDest as well.  I think we also need to merge volatile
244   // from the source as well, as we can't eliminate it if either operand
245   // is volatile, unless copy has volatile for both source and destination..
246   CGF.EmitAggregateCopy(Dest.getAddr(), Src.getAggregateAddr(), E->getType(),
247                         Dest.isVolatile()|Src.isVolatileQualified());
248 }
249 
250 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
251 void AggExprEmitter::EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore) {
252   assert(Src.isSimple() && "Can't have aggregate bitfield, vector, etc");
253 
254   EmitFinalDestCopy(E, RValue::getAggregate(Src.getAddress(),
255                                             Src.isVolatileQualified()),
256                     Ignore);
257 }
258 
259 //===----------------------------------------------------------------------===//
260 //                            Visitor Methods
261 //===----------------------------------------------------------------------===//
262 
263 void AggExprEmitter::VisitCastExpr(CastExpr *E) {
264   if (Dest.isIgnored() && E->getCastKind() != CK_Dynamic) {
265     Visit(E->getSubExpr());
266     return;
267   }
268 
269   switch (E->getCastKind()) {
270   default: assert(0 && "Unhandled cast kind!");
271 
272   case CK_Dynamic: {
273     assert(isa<CXXDynamicCastExpr>(E) && "CK_Dynamic without a dynamic_cast?");
274     LValue LV = CGF.EmitCheckedLValue(E->getSubExpr());
275     // FIXME: Do we also need to handle property references here?
276     if (LV.isSimple())
277       CGF.EmitDynamicCast(LV.getAddress(), cast<CXXDynamicCastExpr>(E));
278     else
279       CGF.CGM.ErrorUnsupported(E, "non-simple lvalue dynamic_cast");
280 
281     if (!Dest.isIgnored())
282       CGF.CGM.ErrorUnsupported(E, "lvalue dynamic_cast with a destination");
283     break;
284   }
285 
286   case CK_ToUnion: {
287     // GCC union extension
288     QualType Ty = E->getSubExpr()->getType();
289     QualType PtrTy = CGF.getContext().getPointerType(Ty);
290     llvm::Value *CastPtr = Builder.CreateBitCast(Dest.getAddr(),
291                                                  CGF.ConvertType(PtrTy));
292     EmitInitializationToLValue(E->getSubExpr(), CGF.MakeAddrLValue(CastPtr, Ty),
293                                Ty);
294     break;
295   }
296 
297   case CK_DerivedToBase:
298   case CK_BaseToDerived:
299   case CK_UncheckedDerivedToBase: {
300     assert(0 && "cannot perform hierarchy conversion in EmitAggExpr: "
301                 "should have been unpacked before we got here");
302     break;
303   }
304 
305   // FIXME: Remove the CK_Unknown check here.
306   case CK_Unknown:
307   case CK_NoOp:
308   case CK_UserDefinedConversion:
309   case CK_ConstructorConversion:
310     assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(),
311                                                    E->getType()) &&
312            "Implicit cast types must be compatible");
313     Visit(E->getSubExpr());
314     break;
315 
316   case CK_LValueBitCast:
317     llvm_unreachable("there are no lvalue bit-casts on aggregates");
318     break;
319   }
320 }
321 
322 void AggExprEmitter::VisitCallExpr(const CallExpr *E) {
323   if (E->getCallReturnType()->isReferenceType()) {
324     EmitAggLoadOfLValue(E);
325     return;
326   }
327 
328   RValue RV = CGF.EmitCallExpr(E, getReturnValueSlot());
329   EmitGCMove(E, RV);
330 }
331 
332 void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
333   RValue RV = CGF.EmitObjCMessageExpr(E, getReturnValueSlot());
334   EmitGCMove(E, RV);
335 }
336 
337 void AggExprEmitter::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
338   RValue RV = CGF.EmitObjCPropertyGet(E, getReturnValueSlot());
339   EmitGCMove(E, RV);
340 }
341 
342 void AggExprEmitter::VisitObjCImplicitSetterGetterRefExpr(
343                                    ObjCImplicitSetterGetterRefExpr *E) {
344   RValue RV = CGF.EmitObjCPropertyGet(E, getReturnValueSlot());
345   EmitGCMove(E, RV);
346 }
347 
348 void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {
349   CGF.EmitAnyExpr(E->getLHS(), AggValueSlot::ignored(), true);
350   Visit(E->getRHS());
351 }
352 
353 void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
354   CGF.EmitCompoundStmt(*E->getSubStmt(), true, Dest);
355 }
356 
357 void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
358   if (E->getOpcode() == BO_PtrMemD || E->getOpcode() == BO_PtrMemI)
359     VisitPointerToDataMemberBinaryOperator(E);
360   else
361     CGF.ErrorUnsupported(E, "aggregate binary expression");
362 }
363 
364 void AggExprEmitter::VisitPointerToDataMemberBinaryOperator(
365                                                     const BinaryOperator *E) {
366   LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E);
367   EmitFinalDestCopy(E, LV);
368 }
369 
370 void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
371   // For an assignment to work, the value on the right has
372   // to be compatible with the value on the left.
373   assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
374                                                  E->getRHS()->getType())
375          && "Invalid assignment");
376   LValue LHS = CGF.EmitLValue(E->getLHS());
377 
378   // We have to special case property setters, otherwise we must have
379   // a simple lvalue (no aggregates inside vectors, bitfields).
380   if (LHS.isPropertyRef()) {
381     AggValueSlot Slot = EnsureSlot(E->getRHS()->getType());
382     CGF.EmitAggExpr(E->getRHS(), Slot);
383     CGF.EmitObjCPropertySet(LHS.getPropertyRefExpr(), Slot.asRValue());
384   } else if (LHS.isKVCRef()) {
385     AggValueSlot Slot = EnsureSlot(E->getRHS()->getType());
386     CGF.EmitAggExpr(E->getRHS(), Slot);
387     CGF.EmitObjCPropertySet(LHS.getKVCRefExpr(), Slot.asRValue());
388   } else {
389     bool GCollection = false;
390     if (CGF.getContext().getLangOptions().getGCMode())
391       GCollection = TypeRequiresGCollection(E->getLHS()->getType());
392 
393     // Codegen the RHS so that it stores directly into the LHS.
394     AggValueSlot LHSSlot = AggValueSlot::forLValue(LHS, true,
395                                                    GCollection);
396     CGF.EmitAggExpr(E->getRHS(), LHSSlot, false);
397     EmitFinalDestCopy(E, LHS, true);
398   }
399 }
400 
401 void AggExprEmitter::VisitConditionalOperator(const ConditionalOperator *E) {
402   if (!E->getLHS()) {
403     CGF.ErrorUnsupported(E, "conditional operator with missing LHS");
404     return;
405   }
406 
407   llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
408   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
409   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
410 
411   CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
412 
413   CGF.BeginConditionalBranch();
414   CGF.EmitBlock(LHSBlock);
415 
416   // Handle the GNU extension for missing LHS.
417   assert(E->getLHS() && "Must have LHS for aggregate value");
418 
419   Visit(E->getLHS());
420   CGF.EndConditionalBranch();
421   CGF.EmitBranch(ContBlock);
422 
423   CGF.BeginConditionalBranch();
424   CGF.EmitBlock(RHSBlock);
425 
426   Visit(E->getRHS());
427   CGF.EndConditionalBranch();
428   CGF.EmitBranch(ContBlock);
429 
430   CGF.EmitBlock(ContBlock);
431 }
432 
433 void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) {
434   Visit(CE->getChosenSubExpr(CGF.getContext()));
435 }
436 
437 void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
438   llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
439   llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
440 
441   if (!ArgPtr) {
442     CGF.ErrorUnsupported(VE, "aggregate va_arg expression");
443     return;
444   }
445 
446   EmitFinalDestCopy(VE, CGF.MakeAddrLValue(ArgPtr, VE->getType()));
447 }
448 
449 void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
450   // Ensure that we have a slot, but if we already do, remember
451   // whether its lifetime was externally managed.
452   bool WasManaged = Dest.isLifetimeExternallyManaged();
453   Dest = EnsureSlot(E->getType());
454   Dest.setLifetimeExternallyManaged();
455 
456   Visit(E->getSubExpr());
457 
458   // Set up the temporary's destructor if its lifetime wasn't already
459   // being managed.
460   if (!WasManaged)
461     CGF.EmitCXXTemporary(E->getTemporary(), Dest.getAddr());
462 }
463 
464 void
465 AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) {
466   AggValueSlot Slot = EnsureSlot(E->getType());
467   CGF.EmitCXXConstructExpr(E, Slot);
468 }
469 
470 void AggExprEmitter::VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E) {
471   CGF.EmitCXXExprWithTemporaries(E, Dest);
472 }
473 
474 void AggExprEmitter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
475   QualType T = E->getType();
476   AggValueSlot Slot = EnsureSlot(T);
477   EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T), T);
478 }
479 
480 void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
481   QualType T = E->getType();
482   AggValueSlot Slot = EnsureSlot(T);
483   EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T), T);
484 }
485 
486 void
487 AggExprEmitter::EmitInitializationToLValue(Expr* E, LValue LV, QualType T) {
488   // FIXME: Ignore result?
489   // FIXME: Are initializers affected by volatile?
490   if (isa<ImplicitValueInitExpr>(E)) {
491     EmitNullInitializationToLValue(LV, T);
492   } else if (T->isReferenceType()) {
493     RValue RV = CGF.EmitReferenceBindingToExpr(E, /*InitializedDecl=*/0);
494     CGF.EmitStoreThroughLValue(RV, LV, T);
495   } else if (T->isAnyComplexType()) {
496     CGF.EmitComplexExprIntoAddr(E, LV.getAddress(), false);
497   } else if (CGF.hasAggregateLLVMType(T)) {
498     CGF.EmitAggExpr(E, AggValueSlot::forAddr(LV.getAddress(), false, true));
499   } else {
500     CGF.EmitStoreThroughLValue(CGF.EmitAnyExpr(E), LV, T);
501   }
502 }
503 
504 void AggExprEmitter::EmitNullInitializationToLValue(LValue LV, QualType T) {
505   if (!CGF.hasAggregateLLVMType(T)) {
506     // For non-aggregates, we can store zero
507     llvm::Value *Null = llvm::Constant::getNullValue(CGF.ConvertType(T));
508     CGF.EmitStoreThroughLValue(RValue::get(Null), LV, T);
509   } else {
510     // There's a potential optimization opportunity in combining
511     // memsets; that would be easy for arrays, but relatively
512     // difficult for structures with the current code.
513     CGF.EmitNullInitialization(LV.getAddress(), T);
514   }
515 }
516 
517 void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
518 #if 0
519   // FIXME: Assess perf here?  Figure out what cases are worth optimizing here
520   // (Length of globals? Chunks of zeroed-out space?).
521   //
522   // If we can, prefer a copy from a global; this is a lot less code for long
523   // globals, and it's easier for the current optimizers to analyze.
524   if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) {
525     llvm::GlobalVariable* GV =
526     new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true,
527                              llvm::GlobalValue::InternalLinkage, C, "");
528     EmitFinalDestCopy(E, CGF.MakeAddrLValue(GV, E->getType()));
529     return;
530   }
531 #endif
532   if (E->hadArrayRangeDesignator())
533     CGF.ErrorUnsupported(E, "GNU array range designator extension");
534 
535   llvm::Value *DestPtr = Dest.getAddr();
536 
537   // Handle initialization of an array.
538   if (E->getType()->isArrayType()) {
539     const llvm::PointerType *APType =
540       cast<llvm::PointerType>(DestPtr->getType());
541     const llvm::ArrayType *AType =
542       cast<llvm::ArrayType>(APType->getElementType());
543 
544     uint64_t NumInitElements = E->getNumInits();
545 
546     if (E->getNumInits() > 0) {
547       QualType T1 = E->getType();
548       QualType T2 = E->getInit(0)->getType();
549       if (CGF.getContext().hasSameUnqualifiedType(T1, T2)) {
550         EmitAggLoadOfLValue(E->getInit(0));
551         return;
552       }
553     }
554 
555     uint64_t NumArrayElements = AType->getNumElements();
556     QualType ElementType = CGF.getContext().getCanonicalType(E->getType());
557     ElementType = CGF.getContext().getAsArrayType(ElementType)->getElementType();
558 
559     // FIXME: were we intentionally ignoring address spaces and GC attributes?
560 
561     for (uint64_t i = 0; i != NumArrayElements; ++i) {
562       llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array");
563       LValue LV = CGF.MakeAddrLValue(NextVal, ElementType);
564       if (i < NumInitElements)
565         EmitInitializationToLValue(E->getInit(i), LV, ElementType);
566 
567       else
568         EmitNullInitializationToLValue(LV, ElementType);
569     }
570     return;
571   }
572 
573   assert(E->getType()->isRecordType() && "Only support structs/unions here!");
574 
575   // Do struct initialization; this code just sets each individual member
576   // to the approprate value.  This makes bitfield support automatic;
577   // the disadvantage is that the generated code is more difficult for
578   // the optimizer, especially with bitfields.
579   unsigned NumInitElements = E->getNumInits();
580   RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl();
581 
582   if (E->getType()->isUnionType()) {
583     // Only initialize one field of a union. The field itself is
584     // specified by the initializer list.
585     if (!E->getInitializedFieldInUnion()) {
586       // Empty union; we have nothing to do.
587 
588 #ifndef NDEBUG
589       // Make sure that it's really an empty and not a failure of
590       // semantic analysis.
591       for (RecordDecl::field_iterator Field = SD->field_begin(),
592                                    FieldEnd = SD->field_end();
593            Field != FieldEnd; ++Field)
594         assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed");
595 #endif
596       return;
597     }
598 
599     // FIXME: volatility
600     FieldDecl *Field = E->getInitializedFieldInUnion();
601     LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestPtr, Field, 0);
602 
603     if (NumInitElements) {
604       // Store the initializer into the field
605       EmitInitializationToLValue(E->getInit(0), FieldLoc, Field->getType());
606     } else {
607       // Default-initialize to null
608       EmitNullInitializationToLValue(FieldLoc, Field->getType());
609     }
610 
611     return;
612   }
613 
614   // Here we iterate over the fields; this makes it simpler to both
615   // default-initialize fields and skip over unnamed fields.
616   unsigned CurInitVal = 0;
617   for (RecordDecl::field_iterator Field = SD->field_begin(),
618                                FieldEnd = SD->field_end();
619        Field != FieldEnd; ++Field) {
620     // We're done once we hit the flexible array member
621     if (Field->getType()->isIncompleteArrayType())
622       break;
623 
624     if (Field->isUnnamedBitfield())
625       continue;
626 
627     // FIXME: volatility
628     LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestPtr, *Field, 0);
629     // We never generate write-barries for initialized fields.
630     FieldLoc.setNonGC(true);
631     if (CurInitVal < NumInitElements) {
632       // Store the initializer into the field.
633       EmitInitializationToLValue(E->getInit(CurInitVal++), FieldLoc,
634                                  Field->getType());
635     } else {
636       // We're out of initalizers; default-initialize to null
637       EmitNullInitializationToLValue(FieldLoc, Field->getType());
638     }
639   }
640 }
641 
642 //===----------------------------------------------------------------------===//
643 //                        Entry Points into this File
644 //===----------------------------------------------------------------------===//
645 
646 /// EmitAggExpr - Emit the computation of the specified expression of aggregate
647 /// type.  The result is computed into DestPtr.  Note that if DestPtr is null,
648 /// the value of the aggregate expression is not needed.  If VolatileDest is
649 /// true, DestPtr cannot be 0.
650 ///
651 /// \param IsInitializer - true if this evaluation is initializing an
652 /// object whose lifetime is already being managed.
653 //
654 // FIXME: Take Qualifiers object.
655 void CodeGenFunction::EmitAggExpr(const Expr *E, AggValueSlot Slot,
656                                   bool IgnoreResult) {
657   assert(E && hasAggregateLLVMType(E->getType()) &&
658          "Invalid aggregate expression to emit");
659   assert((Slot.getAddr() != 0 || Slot.isIgnored())
660          && "slot has bits but no address");
661 
662   AggExprEmitter(*this, Slot, IgnoreResult)
663     .Visit(const_cast<Expr*>(E));
664 }
665 
666 LValue CodeGenFunction::EmitAggExprToLValue(const Expr *E) {
667   assert(hasAggregateLLVMType(E->getType()) && "Invalid argument!");
668   llvm::Value *Temp = CreateMemTemp(E->getType());
669   LValue LV = MakeAddrLValue(Temp, E->getType());
670   AggValueSlot Slot
671     = AggValueSlot::forAddr(Temp, LV.isVolatileQualified(), false);
672   EmitAggExpr(E, Slot);
673   return LV;
674 }
675 
676 void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr,
677                                         llvm::Value *SrcPtr, QualType Ty,
678                                         bool isVolatile) {
679   assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
680 
681   if (getContext().getLangOptions().CPlusPlus) {
682     if (const RecordType *RT = Ty->getAs<RecordType>()) {
683       CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
684       assert((Record->hasTrivialCopyConstructor() ||
685               Record->hasTrivialCopyAssignment()) &&
686              "Trying to aggregate-copy a type without a trivial copy "
687              "constructor or assignment operator");
688       // Ignore empty classes in C++.
689       if (Record->isEmpty())
690         return;
691     }
692   }
693 
694   // Aggregate assignment turns into llvm.memcpy.  This is almost valid per
695   // C99 6.5.16.1p3, which states "If the value being stored in an object is
696   // read from another object that overlaps in anyway the storage of the first
697   // object, then the overlap shall be exact and the two objects shall have
698   // qualified or unqualified versions of a compatible type."
699   //
700   // memcpy is not defined if the source and destination pointers are exactly
701   // equal, but other compilers do this optimization, and almost every memcpy
702   // implementation handles this case safely.  If there is a libc that does not
703   // safely handle this, we can add a target hook.
704 
705   // Get size and alignment info for this aggregate.
706   std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
707 
708   // FIXME: Handle variable sized types.
709 
710   // FIXME: If we have a volatile struct, the optimizer can remove what might
711   // appear to be `extra' memory ops:
712   //
713   // volatile struct { int i; } a, b;
714   //
715   // int main() {
716   //   a = b;
717   //   a = b;
718   // }
719   //
720   // we need to use a different call here.  We use isVolatile to indicate when
721   // either the source or the destination is volatile.
722 
723   const llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType());
724   const llvm::Type *DBP =
725     llvm::Type::getInt8PtrTy(VMContext, DPT->getAddressSpace());
726   DestPtr = Builder.CreateBitCast(DestPtr, DBP, "tmp");
727 
728   const llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType());
729   const llvm::Type *SBP =
730     llvm::Type::getInt8PtrTy(VMContext, SPT->getAddressSpace());
731   SrcPtr = Builder.CreateBitCast(SrcPtr, SBP, "tmp");
732 
733   if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
734     RecordDecl *Record = RecordTy->getDecl();
735     if (Record->hasObjectMember()) {
736       unsigned long size = TypeInfo.first/8;
737       const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
738       llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size);
739       CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
740                                                     SizeVal);
741       return;
742     }
743   } else if (getContext().getAsArrayType(Ty)) {
744     QualType BaseType = getContext().getBaseElementType(Ty);
745     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
746       if (RecordTy->getDecl()->hasObjectMember()) {
747         unsigned long size = TypeInfo.first/8;
748         const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
749         llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size);
750         CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
751                                                       SizeVal);
752         return;
753       }
754     }
755   }
756 
757   Builder.CreateCall5(CGM.getMemCpyFn(DestPtr->getType(), SrcPtr->getType(),
758                                       IntPtrTy),
759                       DestPtr, SrcPtr,
760                       // TypeInfo.first describes size in bits.
761                       llvm::ConstantInt::get(IntPtrTy, TypeInfo.first/8),
762                       Builder.getInt32(TypeInfo.second/8),
763                       Builder.getInt1(isVolatile));
764 }
765