CGExprAgg.cpp revision 208600
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"
24using namespace clang;
25using namespace CodeGen;
26
27//===----------------------------------------------------------------------===//
28//                        Aggregate Expression Emitter
29//===----------------------------------------------------------------------===//
30
31namespace  {
32class AggExprEmitter : public StmtVisitor<AggExprEmitter> {
33  CodeGenFunction &CGF;
34  CGBuilderTy &Builder;
35  llvm::Value *DestPtr;
36  bool VolatileDest;
37  bool IgnoreResult;
38  bool IsInitializer;
39  bool RequiresGCollection;
40
41  ReturnValueSlot getReturnValueSlot() const {
42    // If the destination slot requires garbage collection, we can't
43    // use the real return value slot, because we have to use the GC
44    // API.
45    if (RequiresGCollection) return ReturnValueSlot();
46
47    return ReturnValueSlot(DestPtr, VolatileDest);
48  }
49
50public:
51  AggExprEmitter(CodeGenFunction &cgf, llvm::Value *destPtr, bool v,
52                 bool ignore, bool isinit, bool requiresGCollection)
53    : CGF(cgf), Builder(CGF.Builder),
54      DestPtr(destPtr), VolatileDest(v), IgnoreResult(ignore),
55      IsInitializer(isinit), RequiresGCollection(requiresGCollection) {
56  }
57
58  //===--------------------------------------------------------------------===//
59  //                               Utilities
60  //===--------------------------------------------------------------------===//
61
62  /// EmitAggLoadOfLValue - Given an expression with aggregate type that
63  /// represents a value lvalue, this method emits the address of the lvalue,
64  /// then loads the result into DestPtr.
65  void EmitAggLoadOfLValue(const Expr *E);
66
67  /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
68  void EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore = false);
69  void EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore = false);
70
71  void EmitGCMove(const Expr *E, RValue Src);
72
73  bool TypeRequiresGCollection(QualType T);
74
75  //===--------------------------------------------------------------------===//
76  //                            Visitor Methods
77  //===--------------------------------------------------------------------===//
78
79  void VisitStmt(Stmt *S) {
80    CGF.ErrorUnsupported(S, "aggregate expression");
81  }
82  void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); }
83  void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); }
84
85  // l-values.
86  void VisitDeclRefExpr(DeclRefExpr *DRE) { EmitAggLoadOfLValue(DRE); }
87  void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); }
88  void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); }
89  void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); }
90  void VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
91    EmitAggLoadOfLValue(E);
92  }
93  void VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
94    EmitAggLoadOfLValue(E);
95  }
96  void VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
97    EmitAggLoadOfLValue(E);
98  }
99  void VisitPredefinedExpr(const PredefinedExpr *E) {
100    EmitAggLoadOfLValue(E);
101  }
102
103  // Operators.
104  void VisitCastExpr(CastExpr *E);
105  void VisitCallExpr(const CallExpr *E);
106  void VisitStmtExpr(const StmtExpr *E);
107  void VisitBinaryOperator(const BinaryOperator *BO);
108  void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO);
109  void VisitBinAssign(const BinaryOperator *E);
110  void VisitBinComma(const BinaryOperator *E);
111  void VisitUnaryAddrOf(const UnaryOperator *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 VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *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.
149void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) {
150  LValue LV = CGF.EmitLValue(E);
151  EmitFinalDestCopy(E, LV);
152}
153
154/// \brief True if the given aggregate type requires special GC API calls.
155bool AggExprEmitter::TypeRequiresGCollection(QualType T) {
156  // Only record types have members that might require garbage collection.
157  const RecordType *RecordTy = T->getAs<RecordType>();
158  if (!RecordTy) return false;
159
160  // Don't mess with non-trivial C++ types.
161  RecordDecl *Record = RecordTy->getDecl();
162  if (isa<CXXRecordDecl>(Record) &&
163      (!cast<CXXRecordDecl>(Record)->hasTrivialCopyConstructor() ||
164       !cast<CXXRecordDecl>(Record)->hasTrivialDestructor()))
165    return false;
166
167  // Check whether the type has an object member.
168  return Record->hasObjectMember();
169}
170
171/// \brief Perform the final move to DestPtr if RequiresGCollection is set.
172///
173/// The idea is that you do something like this:
174///   RValue Result = EmitSomething(..., getReturnValueSlot());
175///   EmitGCMove(E, Result);
176/// If GC doesn't interfere, this will cause the result to be emitted
177/// directly into the return value slot.  If GC does interfere, a final
178/// move will be performed.
179void AggExprEmitter::EmitGCMove(const Expr *E, RValue Src) {
180  if (!RequiresGCollection) return;
181
182  CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF, DestPtr,
183                                                    Src.getAggregateAddr(),
184                                                    E->getType());
185}
186
187/// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
188void AggExprEmitter::EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore) {
189  assert(Src.isAggregate() && "value must be aggregate value!");
190
191  // If the result is ignored, don't copy from the value.
192  if (DestPtr == 0) {
193    if (!Src.isVolatileQualified() || (IgnoreResult && Ignore))
194      return;
195    // If the source is volatile, we must read from it; to do that, we need
196    // some place to put it.
197    DestPtr = CGF.CreateMemTemp(E->getType(), "agg.tmp");
198  }
199
200  if (RequiresGCollection) {
201    CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF,
202                                              DestPtr, Src.getAggregateAddr(),
203                                              E->getType());
204    return;
205  }
206  // If the result of the assignment is used, copy the LHS there also.
207  // FIXME: Pass VolatileDest as well.  I think we also need to merge volatile
208  // from the source as well, as we can't eliminate it if either operand
209  // is volatile, unless copy has volatile for both source and destination..
210  CGF.EmitAggregateCopy(DestPtr, Src.getAggregateAddr(), E->getType(),
211                        VolatileDest|Src.isVolatileQualified());
212}
213
214/// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
215void AggExprEmitter::EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore) {
216  assert(Src.isSimple() && "Can't have aggregate bitfield, vector, etc");
217
218  EmitFinalDestCopy(E, RValue::getAggregate(Src.getAddress(),
219                                            Src.isVolatileQualified()),
220                    Ignore);
221}
222
223//===----------------------------------------------------------------------===//
224//                            Visitor Methods
225//===----------------------------------------------------------------------===//
226
227void AggExprEmitter::VisitCastExpr(CastExpr *E) {
228  if (!DestPtr && E->getCastKind() != CastExpr::CK_Dynamic) {
229    Visit(E->getSubExpr());
230    return;
231  }
232
233  switch (E->getCastKind()) {
234  default: assert(0 && "Unhandled cast kind!");
235
236  case CastExpr::CK_Dynamic: {
237    assert(isa<CXXDynamicCastExpr>(E) && "CK_Dynamic without a dynamic_cast?");
238    LValue LV = CGF.EmitCheckedLValue(E->getSubExpr());
239    // FIXME: Do we also need to handle property references here?
240    if (LV.isSimple())
241      CGF.EmitDynamicCast(LV.getAddress(), cast<CXXDynamicCastExpr>(E));
242    else
243      CGF.CGM.ErrorUnsupported(E, "non-simple lvalue dynamic_cast");
244
245    if (DestPtr)
246      CGF.CGM.ErrorUnsupported(E, "lvalue dynamic_cast with a destination");
247    break;
248  }
249
250  case CastExpr::CK_ToUnion: {
251    // GCC union extension
252    QualType PtrTy =
253    CGF.getContext().getPointerType(E->getSubExpr()->getType());
254    llvm::Value *CastPtr = Builder.CreateBitCast(DestPtr,
255                                                 CGF.ConvertType(PtrTy));
256    EmitInitializationToLValue(E->getSubExpr(),
257                               LValue::MakeAddr(CastPtr, Qualifiers()),
258                               E->getSubExpr()->getType());
259    break;
260  }
261
262  case CastExpr::CK_DerivedToBase:
263  case CastExpr::CK_BaseToDerived:
264  case CastExpr::CK_UncheckedDerivedToBase: {
265    assert(0 && "cannot perform hierarchy conversion in EmitAggExpr: "
266                "should have been unpacked before we got here");
267    break;
268  }
269
270  // FIXME: Remove the CK_Unknown check here.
271  case CastExpr::CK_Unknown:
272  case CastExpr::CK_NoOp:
273  case CastExpr::CK_UserDefinedConversion:
274  case CastExpr::CK_ConstructorConversion:
275    assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(),
276                                                   E->getType()) &&
277           "Implicit cast types must be compatible");
278    Visit(E->getSubExpr());
279    break;
280
281  case CastExpr::CK_NullToMemberPointer: {
282    // If the subexpression's type is the C++0x nullptr_t, emit the
283    // subexpression, which may have side effects.
284    if (E->getSubExpr()->getType()->isNullPtrType())
285      Visit(E->getSubExpr());
286
287    const llvm::Type *PtrDiffTy =
288      CGF.ConvertType(CGF.getContext().getPointerDiffType());
289
290    llvm::Value *NullValue = llvm::Constant::getNullValue(PtrDiffTy);
291    llvm::Value *Ptr = Builder.CreateStructGEP(DestPtr, 0, "ptr");
292    Builder.CreateStore(NullValue, Ptr, VolatileDest);
293
294    llvm::Value *Adj = Builder.CreateStructGEP(DestPtr, 1, "adj");
295    Builder.CreateStore(NullValue, Adj, VolatileDest);
296
297    break;
298  }
299
300  case CastExpr::CK_BitCast: {
301    // This must be a member function pointer cast.
302    Visit(E->getSubExpr());
303    break;
304  }
305
306  case CastExpr::CK_DerivedToBaseMemberPointer:
307  case CastExpr::CK_BaseToDerivedMemberPointer: {
308    QualType SrcType = E->getSubExpr()->getType();
309
310    llvm::Value *Src = CGF.CreateMemTemp(SrcType, "tmp");
311    CGF.EmitAggExpr(E->getSubExpr(), Src, SrcType.isVolatileQualified());
312
313    llvm::Value *SrcPtr = Builder.CreateStructGEP(Src, 0, "src.ptr");
314    SrcPtr = Builder.CreateLoad(SrcPtr);
315
316    llvm::Value *SrcAdj = Builder.CreateStructGEP(Src, 1, "src.adj");
317    SrcAdj = Builder.CreateLoad(SrcAdj);
318
319    llvm::Value *DstPtr = Builder.CreateStructGEP(DestPtr, 0, "dst.ptr");
320    Builder.CreateStore(SrcPtr, DstPtr, VolatileDest);
321
322    llvm::Value *DstAdj = Builder.CreateStructGEP(DestPtr, 1, "dst.adj");
323
324    // Now See if we need to update the adjustment.
325    const CXXRecordDecl *BaseDecl =
326      cast<CXXRecordDecl>(SrcType->getAs<MemberPointerType>()->
327                          getClass()->getAs<RecordType>()->getDecl());
328    const CXXRecordDecl *DerivedDecl =
329      cast<CXXRecordDecl>(E->getType()->getAs<MemberPointerType>()->
330                          getClass()->getAs<RecordType>()->getDecl());
331    if (E->getCastKind() == CastExpr::CK_DerivedToBaseMemberPointer)
332      std::swap(DerivedDecl, BaseDecl);
333
334    if (llvm::Constant *Adj =
335          CGF.CGM.GetNonVirtualBaseClassOffset(DerivedDecl, E->getBasePath())) {
336      if (E->getCastKind() == CastExpr::CK_DerivedToBaseMemberPointer)
337        SrcAdj = Builder.CreateSub(SrcAdj, Adj, "adj");
338      else
339        SrcAdj = Builder.CreateAdd(SrcAdj, Adj, "adj");
340    }
341
342    Builder.CreateStore(SrcAdj, DstAdj, VolatileDest);
343    break;
344  }
345  }
346}
347
348void AggExprEmitter::VisitCallExpr(const CallExpr *E) {
349  if (E->getCallReturnType()->isReferenceType()) {
350    EmitAggLoadOfLValue(E);
351    return;
352  }
353
354  RValue RV = CGF.EmitCallExpr(E, getReturnValueSlot());
355  EmitGCMove(E, RV);
356}
357
358void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
359  RValue RV = CGF.EmitObjCMessageExpr(E, getReturnValueSlot());
360  EmitGCMove(E, RV);
361}
362
363void AggExprEmitter::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
364  RValue RV = CGF.EmitObjCPropertyGet(E, getReturnValueSlot());
365  EmitGCMove(E, RV);
366}
367
368void AggExprEmitter::VisitObjCImplicitSetterGetterRefExpr(
369                                   ObjCImplicitSetterGetterRefExpr *E) {
370  RValue RV = CGF.EmitObjCPropertyGet(E, getReturnValueSlot());
371  EmitGCMove(E, RV);
372}
373
374void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {
375  CGF.EmitAnyExpr(E->getLHS(), 0, false, true);
376  CGF.EmitAggExpr(E->getRHS(), DestPtr, VolatileDest,
377                  /*IgnoreResult=*/false, IsInitializer);
378}
379
380void AggExprEmitter::VisitUnaryAddrOf(const UnaryOperator *E) {
381  // We have a member function pointer.
382  const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
383  (void) MPT;
384  assert(MPT->getPointeeType()->isFunctionProtoType() &&
385         "Unexpected member pointer type!");
386
387  // The creation of member function pointers has no side effects; if
388  // there is no destination pointer, we have nothing to do.
389  if (!DestPtr)
390    return;
391
392  const DeclRefExpr *DRE = cast<DeclRefExpr>(E->getSubExpr());
393  const CXXMethodDecl *MD =
394    cast<CXXMethodDecl>(DRE->getDecl())->getCanonicalDecl();
395
396  const llvm::Type *PtrDiffTy =
397    CGF.ConvertType(CGF.getContext().getPointerDiffType());
398
399
400  llvm::Value *DstPtr = Builder.CreateStructGEP(DestPtr, 0, "dst.ptr");
401  llvm::Value *FuncPtr;
402
403  if (MD->isVirtual()) {
404    int64_t Index = CGF.CGM.getVTables().getMethodVTableIndex(MD);
405
406    // FIXME: We shouldn't use / 8 here.
407    uint64_t PointerWidthInBytes =
408      CGF.CGM.getContext().Target.getPointerWidth(0) / 8;
409
410    // Itanium C++ ABI 2.3:
411    //   For a non-virtual function, this field is a simple function pointer.
412    //   For a virtual function, it is 1 plus the virtual table offset
413    //   (in bytes) of the function, represented as a ptrdiff_t.
414    FuncPtr = llvm::ConstantInt::get(PtrDiffTy,
415                                     (Index * PointerWidthInBytes) + 1);
416  } else {
417    const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
418    const llvm::Type *Ty =
419      CGF.CGM.getTypes().GetFunctionType(CGF.CGM.getTypes().getFunctionInfo(MD),
420                                         FPT->isVariadic());
421    llvm::Constant *Fn = CGF.CGM.GetAddrOfFunction(MD, Ty);
422    FuncPtr = llvm::ConstantExpr::getPtrToInt(Fn, PtrDiffTy);
423  }
424  Builder.CreateStore(FuncPtr, DstPtr, VolatileDest);
425
426  llvm::Value *AdjPtr = Builder.CreateStructGEP(DestPtr, 1, "dst.adj");
427
428  // The adjustment will always be 0.
429  Builder.CreateStore(llvm::ConstantInt::get(PtrDiffTy, 0), AdjPtr,
430                      VolatileDest);
431}
432
433void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
434  CGF.EmitCompoundStmt(*E->getSubStmt(), true, DestPtr, VolatileDest);
435}
436
437void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
438  if (E->getOpcode() == BinaryOperator::PtrMemD ||
439      E->getOpcode() == BinaryOperator::PtrMemI)
440    VisitPointerToDataMemberBinaryOperator(E);
441  else
442    CGF.ErrorUnsupported(E, "aggregate binary expression");
443}
444
445void AggExprEmitter::VisitPointerToDataMemberBinaryOperator(
446                                                    const BinaryOperator *E) {
447  LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E);
448  EmitFinalDestCopy(E, LV);
449}
450
451void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
452  // For an assignment to work, the value on the right has
453  // to be compatible with the value on the left.
454  assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
455                                                 E->getRHS()->getType())
456         && "Invalid assignment");
457  LValue LHS = CGF.EmitLValue(E->getLHS());
458
459  // We have to special case property setters, otherwise we must have
460  // a simple lvalue (no aggregates inside vectors, bitfields).
461  if (LHS.isPropertyRef()) {
462    llvm::Value *AggLoc = DestPtr;
463    if (!AggLoc)
464      AggLoc = CGF.CreateMemTemp(E->getRHS()->getType());
465    CGF.EmitAggExpr(E->getRHS(), AggLoc, VolatileDest);
466    CGF.EmitObjCPropertySet(LHS.getPropertyRefExpr(),
467                            RValue::getAggregate(AggLoc, VolatileDest));
468  } else if (LHS.isKVCRef()) {
469    llvm::Value *AggLoc = DestPtr;
470    if (!AggLoc)
471      AggLoc = CGF.CreateMemTemp(E->getRHS()->getType());
472    CGF.EmitAggExpr(E->getRHS(), AggLoc, VolatileDest);
473    CGF.EmitObjCPropertySet(LHS.getKVCRefExpr(),
474                            RValue::getAggregate(AggLoc, VolatileDest));
475  } else {
476    bool RequiresGCollection = false;
477    if (CGF.getContext().getLangOptions().getGCMode())
478      RequiresGCollection = TypeRequiresGCollection(E->getLHS()->getType());
479
480    // Codegen the RHS so that it stores directly into the LHS.
481    CGF.EmitAggExpr(E->getRHS(), LHS.getAddress(), LHS.isVolatileQualified(),
482                    false, false, RequiresGCollection);
483    EmitFinalDestCopy(E, LHS, true);
484  }
485}
486
487void AggExprEmitter::VisitConditionalOperator(const ConditionalOperator *E) {
488  if (!E->getLHS()) {
489    CGF.ErrorUnsupported(E, "conditional operator with missing LHS");
490    return;
491  }
492
493  llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
494  llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
495  llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
496
497  CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
498
499  CGF.BeginConditionalBranch();
500  CGF.EmitBlock(LHSBlock);
501
502  // Handle the GNU extension for missing LHS.
503  assert(E->getLHS() && "Must have LHS for aggregate value");
504
505  Visit(E->getLHS());
506  CGF.EndConditionalBranch();
507  CGF.EmitBranch(ContBlock);
508
509  CGF.BeginConditionalBranch();
510  CGF.EmitBlock(RHSBlock);
511
512  Visit(E->getRHS());
513  CGF.EndConditionalBranch();
514  CGF.EmitBranch(ContBlock);
515
516  CGF.EmitBlock(ContBlock);
517}
518
519void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) {
520  Visit(CE->getChosenSubExpr(CGF.getContext()));
521}
522
523void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
524  llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
525  llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
526
527  if (!ArgPtr) {
528    CGF.ErrorUnsupported(VE, "aggregate va_arg expression");
529    return;
530  }
531
532  EmitFinalDestCopy(VE, LValue::MakeAddr(ArgPtr, Qualifiers()));
533}
534
535void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
536  llvm::Value *Val = DestPtr;
537
538  if (!Val) {
539    // Create a temporary variable.
540    Val = CGF.CreateMemTemp(E->getType(), "tmp");
541
542    // FIXME: volatile
543    CGF.EmitAggExpr(E->getSubExpr(), Val, false);
544  } else
545    Visit(E->getSubExpr());
546
547  // Don't make this a live temporary if we're emitting an initializer expr.
548  if (!IsInitializer)
549    CGF.PushCXXTemporary(E->getTemporary(), Val);
550}
551
552void
553AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) {
554  llvm::Value *Val = DestPtr;
555
556  if (!Val) {
557    // Create a temporary variable.
558    Val = CGF.CreateMemTemp(E->getType(), "tmp");
559  }
560
561  if (E->requiresZeroInitialization())
562    EmitNullInitializationToLValue(LValue::MakeAddr(Val,
563                                                    // FIXME: Qualifiers()?
564                                                 E->getType().getQualifiers()),
565                                   E->getType());
566
567  CGF.EmitCXXConstructExpr(Val, E);
568}
569
570void AggExprEmitter::VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E) {
571  llvm::Value *Val = DestPtr;
572
573  CGF.EmitCXXExprWithTemporaries(E, Val, VolatileDest, IsInitializer);
574}
575
576void AggExprEmitter::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E) {
577  llvm::Value *Val = DestPtr;
578
579  if (!Val) {
580    // Create a temporary variable.
581    Val = CGF.CreateMemTemp(E->getType(), "tmp");
582  }
583  LValue LV = LValue::MakeAddr(Val, Qualifiers());
584  EmitNullInitializationToLValue(LV, E->getType());
585}
586
587void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
588  llvm::Value *Val = DestPtr;
589
590  if (!Val) {
591    // Create a temporary variable.
592    Val = CGF.CreateMemTemp(E->getType(), "tmp");
593  }
594  LValue LV = LValue::MakeAddr(Val, Qualifiers());
595  EmitNullInitializationToLValue(LV, E->getType());
596}
597
598void
599AggExprEmitter::EmitInitializationToLValue(Expr* E, LValue LV, QualType T) {
600  // FIXME: Ignore result?
601  // FIXME: Are initializers affected by volatile?
602  if (isa<ImplicitValueInitExpr>(E)) {
603    EmitNullInitializationToLValue(LV, T);
604  } else if (T->isReferenceType()) {
605    RValue RV = CGF.EmitReferenceBindingToExpr(E, /*IsInitializer=*/false);
606    CGF.EmitStoreThroughLValue(RV, LV, T);
607  } else if (T->isAnyComplexType()) {
608    CGF.EmitComplexExprIntoAddr(E, LV.getAddress(), false);
609  } else if (CGF.hasAggregateLLVMType(T)) {
610    CGF.EmitAnyExpr(E, LV.getAddress(), false);
611  } else {
612    CGF.EmitStoreThroughLValue(CGF.EmitAnyExpr(E), LV, T);
613  }
614}
615
616void AggExprEmitter::EmitNullInitializationToLValue(LValue LV, QualType T) {
617  if (!CGF.hasAggregateLLVMType(T)) {
618    // For non-aggregates, we can store zero
619    llvm::Value *Null = llvm::Constant::getNullValue(CGF.ConvertType(T));
620    CGF.EmitStoreThroughLValue(RValue::get(Null), LV, T);
621  } else {
622    // There's a potential optimization opportunity in combining
623    // memsets; that would be easy for arrays, but relatively
624    // difficult for structures with the current code.
625    CGF.EmitNullInitialization(LV.getAddress(), T);
626  }
627}
628
629void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
630#if 0
631  // FIXME: Assess perf here?  Figure out what cases are worth optimizing here
632  // (Length of globals? Chunks of zeroed-out space?).
633  //
634  // If we can, prefer a copy from a global; this is a lot less code for long
635  // globals, and it's easier for the current optimizers to analyze.
636  if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) {
637    llvm::GlobalVariable* GV =
638    new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true,
639                             llvm::GlobalValue::InternalLinkage, C, "");
640    EmitFinalDestCopy(E, LValue::MakeAddr(GV, Qualifiers()));
641    return;
642  }
643#endif
644  if (E->hadArrayRangeDesignator()) {
645    CGF.ErrorUnsupported(E, "GNU array range designator extension");
646  }
647
648  // Handle initialization of an array.
649  if (E->getType()->isArrayType()) {
650    const llvm::PointerType *APType =
651      cast<llvm::PointerType>(DestPtr->getType());
652    const llvm::ArrayType *AType =
653      cast<llvm::ArrayType>(APType->getElementType());
654
655    uint64_t NumInitElements = E->getNumInits();
656
657    if (E->getNumInits() > 0) {
658      QualType T1 = E->getType();
659      QualType T2 = E->getInit(0)->getType();
660      if (CGF.getContext().hasSameUnqualifiedType(T1, T2)) {
661        EmitAggLoadOfLValue(E->getInit(0));
662        return;
663      }
664    }
665
666    uint64_t NumArrayElements = AType->getNumElements();
667    QualType ElementType = CGF.getContext().getCanonicalType(E->getType());
668    ElementType = CGF.getContext().getAsArrayType(ElementType)->getElementType();
669
670    // FIXME: were we intentionally ignoring address spaces and GC attributes?
671    Qualifiers Quals = CGF.MakeQualifiers(ElementType);
672
673    for (uint64_t i = 0; i != NumArrayElements; ++i) {
674      llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array");
675      if (i < NumInitElements)
676        EmitInitializationToLValue(E->getInit(i),
677                                   LValue::MakeAddr(NextVal, Quals),
678                                   ElementType);
679      else
680        EmitNullInitializationToLValue(LValue::MakeAddr(NextVal, Quals),
681                                       ElementType);
682    }
683    return;
684  }
685
686  assert(E->getType()->isRecordType() && "Only support structs/unions here!");
687
688  // Do struct initialization; this code just sets each individual member
689  // to the approprate value.  This makes bitfield support automatic;
690  // the disadvantage is that the generated code is more difficult for
691  // the optimizer, especially with bitfields.
692  unsigned NumInitElements = E->getNumInits();
693  RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl();
694  unsigned CurInitVal = 0;
695
696  if (E->getType()->isUnionType()) {
697    // Only initialize one field of a union. The field itself is
698    // specified by the initializer list.
699    if (!E->getInitializedFieldInUnion()) {
700      // Empty union; we have nothing to do.
701
702#ifndef NDEBUG
703      // Make sure that it's really an empty and not a failure of
704      // semantic analysis.
705      for (RecordDecl::field_iterator Field = SD->field_begin(),
706                                   FieldEnd = SD->field_end();
707           Field != FieldEnd; ++Field)
708        assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed");
709#endif
710      return;
711    }
712
713    // FIXME: volatility
714    FieldDecl *Field = E->getInitializedFieldInUnion();
715    LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestPtr, Field, 0);
716
717    if (NumInitElements) {
718      // Store the initializer into the field
719      EmitInitializationToLValue(E->getInit(0), FieldLoc, Field->getType());
720    } else {
721      // Default-initialize to null
722      EmitNullInitializationToLValue(FieldLoc, Field->getType());
723    }
724
725    return;
726  }
727
728  // If we're initializing the whole aggregate, just do it in place.
729  // FIXME: This is a hack around an AST bug (PR6537).
730  if (NumInitElements == 1 && E->getType() == E->getInit(0)->getType()) {
731    EmitInitializationToLValue(E->getInit(0),
732                               LValue::MakeAddr(DestPtr, Qualifiers()),
733                               E->getType());
734    return;
735  }
736
737
738  // Here we iterate over the fields; this makes it simpler to both
739  // default-initialize fields and skip over unnamed fields.
740  for (RecordDecl::field_iterator Field = SD->field_begin(),
741                               FieldEnd = SD->field_end();
742       Field != FieldEnd; ++Field) {
743    // We're done once we hit the flexible array member
744    if (Field->getType()->isIncompleteArrayType())
745      break;
746
747    if (Field->isUnnamedBitfield())
748      continue;
749
750    // FIXME: volatility
751    LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestPtr, *Field, 0);
752    // We never generate write-barries for initialized fields.
753    LValue::SetObjCNonGC(FieldLoc, true);
754    if (CurInitVal < NumInitElements) {
755      // Store the initializer into the field.
756      EmitInitializationToLValue(E->getInit(CurInitVal++), FieldLoc,
757                                 Field->getType());
758    } else {
759      // We're out of initalizers; default-initialize to null
760      EmitNullInitializationToLValue(FieldLoc, Field->getType());
761    }
762  }
763}
764
765//===----------------------------------------------------------------------===//
766//                        Entry Points into this File
767//===----------------------------------------------------------------------===//
768
769/// EmitAggExpr - Emit the computation of the specified expression of aggregate
770/// type.  The result is computed into DestPtr.  Note that if DestPtr is null,
771/// the value of the aggregate expression is not needed.  If VolatileDest is
772/// true, DestPtr cannot be 0.
773//
774// FIXME: Take Qualifiers object.
775void CodeGenFunction::EmitAggExpr(const Expr *E, llvm::Value *DestPtr,
776                                  bool VolatileDest, bool IgnoreResult,
777                                  bool IsInitializer,
778                                  bool RequiresGCollection) {
779  assert(E && hasAggregateLLVMType(E->getType()) &&
780         "Invalid aggregate expression to emit");
781  assert ((DestPtr != 0 || VolatileDest == false)
782          && "volatile aggregate can't be 0");
783
784  AggExprEmitter(*this, DestPtr, VolatileDest, IgnoreResult, IsInitializer,
785                 RequiresGCollection)
786    .Visit(const_cast<Expr*>(E));
787}
788
789LValue CodeGenFunction::EmitAggExprToLValue(const Expr *E) {
790  assert(hasAggregateLLVMType(E->getType()) && "Invalid argument!");
791  Qualifiers Q = MakeQualifiers(E->getType());
792  llvm::Value *Temp = CreateMemTemp(E->getType());
793  EmitAggExpr(E, Temp, Q.hasVolatile());
794  return LValue::MakeAddr(Temp, Q);
795}
796
797void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr,
798                                        llvm::Value *SrcPtr, QualType Ty,
799                                        bool isVolatile) {
800  assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
801
802  if (getContext().getLangOptions().CPlusPlus) {
803    if (const RecordType *RT = Ty->getAs<RecordType>()) {
804      CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
805      assert((Record->hasTrivialCopyConstructor() ||
806              Record->hasTrivialCopyAssignment()) &&
807             "Trying to aggregate-copy a type without a trivial copy "
808             "constructor or assignment operator");
809      // Ignore empty classes in C++.
810      if (Record->isEmpty())
811        return;
812    }
813  }
814
815  // Aggregate assignment turns into llvm.memcpy.  This is almost valid per
816  // C99 6.5.16.1p3, which states "If the value being stored in an object is
817  // read from another object that overlaps in anyway the storage of the first
818  // object, then the overlap shall be exact and the two objects shall have
819  // qualified or unqualified versions of a compatible type."
820  //
821  // memcpy is not defined if the source and destination pointers are exactly
822  // equal, but other compilers do this optimization, and almost every memcpy
823  // implementation handles this case safely.  If there is a libc that does not
824  // safely handle this, we can add a target hook.
825  const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
826  if (DestPtr->getType() != BP)
827    DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
828  if (SrcPtr->getType() != BP)
829    SrcPtr = Builder.CreateBitCast(SrcPtr, BP, "tmp");
830
831  // Get size and alignment info for this aggregate.
832  std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
833
834  // FIXME: Handle variable sized types.
835  const llvm::Type *IntPtr =
836          llvm::IntegerType::get(VMContext, LLVMPointerWidth);
837
838  // FIXME: If we have a volatile struct, the optimizer can remove what might
839  // appear to be `extra' memory ops:
840  //
841  // volatile struct { int i; } a, b;
842  //
843  // int main() {
844  //   a = b;
845  //   a = b;
846  // }
847  //
848  // we need to use a different call here.  We use isVolatile to indicate when
849  // either the source or the destination is volatile.
850  const llvm::Type *I1Ty = llvm::Type::getInt1Ty(VMContext);
851  const llvm::Type *I8Ty = llvm::Type::getInt8Ty(VMContext);
852  const llvm::Type *I32Ty = llvm::Type::getInt32Ty(VMContext);
853
854  const llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType());
855  const llvm::Type *DBP = llvm::PointerType::get(I8Ty, DPT->getAddressSpace());
856  if (DestPtr->getType() != DBP)
857    DestPtr = Builder.CreateBitCast(DestPtr, DBP, "tmp");
858
859  const llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType());
860  const llvm::Type *SBP = llvm::PointerType::get(I8Ty, SPT->getAddressSpace());
861  if (SrcPtr->getType() != SBP)
862    SrcPtr = Builder.CreateBitCast(SrcPtr, SBP, "tmp");
863
864  Builder.CreateCall5(CGM.getMemCpyFn(DestPtr->getType(), SrcPtr->getType(),
865                                      IntPtr),
866                      DestPtr, SrcPtr,
867                      // TypeInfo.first describes size in bits.
868                      llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
869                      llvm::ConstantInt::get(I32Ty,  TypeInfo.second/8),
870                      llvm::ConstantInt::get(I1Ty,  isVolatile));
871}
872