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