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