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