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