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 "clang/AST/ASTContext.h"
17 #include "clang/AST/StmtVisitor.h"
18 #include "llvm/Constants.h"
19 #include "llvm/Function.h"
20 #include "llvm/GlobalVariable.h"
21 #include "llvm/Support/Compiler.h"
22 #include "llvm/Intrinsics.h"
23 using namespace clang;
24 using namespace CodeGen;
25 
26 //===----------------------------------------------------------------------===//
27 //                        Aggregate Expression Emitter
28 //===----------------------------------------------------------------------===//
29 
30 namespace  {
31 class VISIBILITY_HIDDEN AggExprEmitter : public StmtVisitor<AggExprEmitter> {
32   CodeGenFunction &CGF;
33   CGBuilderTy &Builder;
34   llvm::Value *DestPtr;
35   bool VolatileDest;
36 public:
37   AggExprEmitter(CodeGenFunction &cgf, llvm::Value *destPtr, bool volatileDest)
38     : CGF(cgf), Builder(CGF.Builder),
39       DestPtr(destPtr), VolatileDest(volatileDest) {
40   }
41 
42   //===--------------------------------------------------------------------===//
43   //                               Utilities
44   //===--------------------------------------------------------------------===//
45 
46   /// EmitAggLoadOfLValue - Given an expression with aggregate type that
47   /// represents a value lvalue, this method emits the address of the lvalue,
48   /// then loads the result into DestPtr.
49   void EmitAggLoadOfLValue(const Expr *E);
50 
51   void EmitNonConstInit(InitListExpr *E);
52 
53   //===--------------------------------------------------------------------===//
54   //                            Visitor Methods
55   //===--------------------------------------------------------------------===//
56 
57   void VisitStmt(Stmt *S) {
58     CGF.ErrorUnsupported(S, "aggregate expression");
59   }
60   void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); }
61 
62   // l-values.
63   void VisitDeclRefExpr(DeclRefExpr *DRE) { EmitAggLoadOfLValue(DRE); }
64   void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); }
65   void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); }
66   void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); }
67   void VisitCompoundLiteralExpr(CompoundLiteralExpr *E)
68       { EmitAggLoadOfLValue(E); }
69 
70   void VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
71     EmitAggLoadOfLValue(E);
72   }
73 
74   // Operators.
75   //  case Expr::UnaryOperatorClass:
76   //  case Expr::CastExprClass:
77   void VisitImplicitCastExpr(ImplicitCastExpr *E);
78   void VisitCallExpr(const CallExpr *E);
79   void VisitStmtExpr(const StmtExpr *E);
80   void VisitBinaryOperator(const BinaryOperator *BO);
81   void VisitBinAssign(const BinaryOperator *E);
82   void VisitOverloadExpr(const OverloadExpr *E);
83   void VisitBinComma(const BinaryOperator *E);
84 
85   void VisitObjCMessageExpr(ObjCMessageExpr *E);
86   void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
87     EmitAggLoadOfLValue(E);
88   }
89   void VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E);
90 
91   void VisitConditionalOperator(const ConditionalOperator *CO);
92   void VisitInitListExpr(InitListExpr *E);
93   void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
94     Visit(DAE->getExpr());
95   }
96   void VisitVAArgExpr(VAArgExpr *E);
97 
98   void EmitInitializationToLValue(Expr *E, LValue Address);
99   void EmitNullInitializationToLValue(LValue Address, QualType T);
100   //  case Expr::ChooseExprClass:
101 
102 };
103 }  // end anonymous namespace.
104 
105 //===----------------------------------------------------------------------===//
106 //                                Utilities
107 //===----------------------------------------------------------------------===//
108 
109 /// EmitAggLoadOfLValue - Given an expression with aggregate type that
110 /// represents a value lvalue, this method emits the address of the lvalue,
111 /// then loads the result into DestPtr.
112 void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) {
113   LValue LV = CGF.EmitLValue(E);
114   assert(LV.isSimple() && "Can't have aggregate bitfield, vector, etc");
115   llvm::Value *SrcPtr = LV.getAddress();
116 
117   // If the result is ignored, don't copy from the value.
118   if (DestPtr == 0)
119     // FIXME: If the source is volatile, we must read from it.
120     return;
121 
122   CGF.EmitAggregateCopy(DestPtr, SrcPtr, E->getType());
123 }
124 
125 //===----------------------------------------------------------------------===//
126 //                            Visitor Methods
127 //===----------------------------------------------------------------------===//
128 
129 void AggExprEmitter::VisitImplicitCastExpr(ImplicitCastExpr *E) {
130   assert(CGF.getContext().typesAreCompatible(
131                           E->getSubExpr()->getType().getUnqualifiedType(),
132                           E->getType().getUnqualifiedType()) &&
133          "Implicit cast types must be compatible");
134   Visit(E->getSubExpr());
135 }
136 
137 void AggExprEmitter::VisitCallExpr(const CallExpr *E) {
138   RValue RV = CGF.EmitCallExpr(E);
139   assert(RV.isAggregate() && "Return value must be aggregate value!");
140 
141   // If the result is ignored, don't copy from the value.
142   if (DestPtr == 0)
143     // FIXME: If the source is volatile, we must read from it.
144     return;
145 
146   CGF.EmitAggregateCopy(DestPtr, RV.getAggregateAddr(), E->getType());
147 }
148 
149 void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
150   RValue RV = CGF.EmitObjCMessageExpr(E);
151   assert(RV.isAggregate() && "Return value must be aggregate value!");
152 
153   // If the result is ignored, don't copy from the value.
154   if (DestPtr == 0)
155     // FIXME: If the source is volatile, we must read from it.
156     return;
157 
158   CGF.EmitAggregateCopy(DestPtr, RV.getAggregateAddr(), E->getType());
159 }
160 
161 void AggExprEmitter::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
162   RValue RV = CGF.EmitObjCPropertyGet(E);
163   assert(RV.isAggregate() && "Return value must be aggregate value!");
164 
165   // If the result is ignored, don't copy from the value.
166   if (DestPtr == 0)
167     // FIXME: If the source is volatile, we must read from it.
168     return;
169 
170   CGF.EmitAggregateCopy(DestPtr, RV.getAggregateAddr(), E->getType());
171 }
172 
173 void AggExprEmitter::VisitOverloadExpr(const OverloadExpr *E) {
174   RValue RV = CGF.EmitCallExpr(E->getFn(), E->arg_begin(),
175                                E->arg_end(CGF.getContext()));
176 
177   assert(RV.isAggregate() && "Return value must be aggregate value!");
178 
179   // If the result is ignored, don't copy from the value.
180   if (DestPtr == 0)
181     // FIXME: If the source is volatile, we must read from it.
182     return;
183 
184   CGF.EmitAggregateCopy(DestPtr, RV.getAggregateAddr(), E->getType());
185 }
186 
187 void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {
188   CGF.EmitAnyExpr(E->getLHS());
189   CGF.EmitAggExpr(E->getRHS(), DestPtr, false);
190 }
191 
192 void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
193   CGF.EmitCompoundStmt(*E->getSubStmt(), true, DestPtr, VolatileDest);
194 }
195 
196 void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
197   CGF.ErrorUnsupported(E, "aggregate binary expression");
198 }
199 
200 void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
201   // For an assignment to work, the value on the right has
202   // to be compatible with the value on the left.
203   assert(CGF.getContext().typesAreCompatible(
204              E->getLHS()->getType().getUnqualifiedType(),
205              E->getRHS()->getType().getUnqualifiedType())
206          && "Invalid assignment");
207   LValue LHS = CGF.EmitLValue(E->getLHS());
208 
209   // We have to special case property setters, otherwise we must have
210   // a simple lvalue (no aggregates inside vectors, bitfields).
211   if (LHS.isPropertyRef()) {
212     // FIXME: Volatility?
213     llvm::Value *AggLoc = DestPtr;
214     if (!AggLoc)
215       AggLoc = CGF.CreateTempAlloca(CGF.ConvertType(E->getRHS()->getType()));
216     CGF.EmitAggExpr(E->getRHS(), AggLoc, false);
217     CGF.EmitObjCPropertySet(LHS.getPropertyRefExpr(),
218                             RValue::getAggregate(AggLoc));
219   } else {
220     // Codegen the RHS so that it stores directly into the LHS.
221     CGF.EmitAggExpr(E->getRHS(), LHS.getAddress(), false /*FIXME: VOLATILE LHS*/);
222 
223     if (DestPtr == 0)
224       return;
225 
226     // If the result of the assignment is used, copy the RHS there also.
227     CGF.EmitAggregateCopy(DestPtr, LHS.getAddress(), E->getType());
228   }
229 }
230 
231 void AggExprEmitter::VisitConditionalOperator(const ConditionalOperator *E) {
232   llvm::BasicBlock *LHSBlock = llvm::BasicBlock::Create("cond.?");
233   llvm::BasicBlock *RHSBlock = llvm::BasicBlock::Create("cond.:");
234   llvm::BasicBlock *ContBlock = llvm::BasicBlock::Create("cond.cont");
235 
236   llvm::Value *Cond = CGF.EvaluateExprAsBool(E->getCond());
237   Builder.CreateCondBr(Cond, LHSBlock, RHSBlock);
238 
239   CGF.EmitBlock(LHSBlock);
240 
241   // Handle the GNU extension for missing LHS.
242   assert(E->getLHS() && "Must have LHS for aggregate value");
243 
244   Visit(E->getLHS());
245   Builder.CreateBr(ContBlock);
246   LHSBlock = Builder.GetInsertBlock();
247 
248   CGF.EmitBlock(RHSBlock);
249 
250   Visit(E->getRHS());
251   Builder.CreateBr(ContBlock);
252   RHSBlock = Builder.GetInsertBlock();
253 
254   CGF.EmitBlock(ContBlock);
255 }
256 
257 void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
258   llvm::Value *ArgValue = CGF.EmitLValue(VE->getSubExpr()).getAddress();
259   llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
260 
261   if (!ArgPtr)
262     CGF.ErrorUnsupported(VE, "aggregate va_arg expression");
263 
264   if (DestPtr)
265     // FIXME: volatility
266     CGF.EmitAggregateCopy(DestPtr, ArgPtr, VE->getType());
267 }
268 
269 void AggExprEmitter::EmitNonConstInit(InitListExpr *E) {
270   if (E->hadDesignators()) {
271     CGF.ErrorUnsupported(E, "initializer list with designators");
272     return;
273   }
274 
275   const llvm::PointerType *APType =
276     cast<llvm::PointerType>(DestPtr->getType());
277   const llvm::Type *DestType = APType->getElementType();
278 
279   if (const llvm::ArrayType *AType = dyn_cast<llvm::ArrayType>(DestType)) {
280     unsigned NumInitElements = E->getNumInits();
281 
282     unsigned i;
283     for (i = 0; i != NumInitElements; ++i) {
284       llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array");
285       Expr *Init = E->getInit(i);
286       if (isa<InitListExpr>(Init))
287         CGF.EmitAggExpr(Init, NextVal, VolatileDest);
288       else
289         // FIXME: volatility
290         Builder.CreateStore(CGF.EmitScalarExpr(Init), NextVal);
291     }
292 
293     // Emit remaining default initializers
294     unsigned NumArrayElements = AType->getNumElements();
295     QualType QType = E->getInit(0)->getType();
296     const llvm::Type *EType = AType->getElementType();
297     for (/*Do not initialize i*/; i < NumArrayElements; ++i) {
298       llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array");
299       if (EType->isSingleValueType())
300         // FIXME: volatility
301         Builder.CreateStore(llvm::Constant::getNullValue(EType), NextVal);
302       else
303         CGF.EmitAggregateClear(NextVal, QType);
304     }
305   } else
306     assert(false && "Invalid initializer");
307 }
308 
309 void AggExprEmitter::EmitInitializationToLValue(Expr* E, LValue LV) {
310   // FIXME: Are initializers affected by volatile?
311   if (E->getType()->isComplexType()) {
312     CGF.EmitComplexExprIntoAddr(E, LV.getAddress(), false);
313   } else if (CGF.hasAggregateLLVMType(E->getType())) {
314     CGF.EmitAnyExpr(E, LV.getAddress(), false);
315   } else {
316     CGF.EmitStoreThroughLValue(CGF.EmitAnyExpr(E), LV, E->getType());
317   }
318 }
319 
320 void AggExprEmitter::EmitNullInitializationToLValue(LValue LV, QualType T) {
321   if (!CGF.hasAggregateLLVMType(T)) {
322     // For non-aggregates, we can store zero
323     llvm::Value *Null = llvm::Constant::getNullValue(CGF.ConvertType(T));
324     CGF.EmitStoreThroughLValue(RValue::get(Null), LV, T);
325   } else {
326     // Otherwise, just memset the whole thing to zero.  This is legal
327     // because in LLVM, all default initializers are guaranteed to have a
328     // bit pattern of all zeros.
329     // There's a potential optimization opportunity in combining
330     // memsets; that would be easy for arrays, but relatively
331     // difficult for structures with the current code.
332     llvm::Value *MemSet = CGF.CGM.getIntrinsic(llvm::Intrinsic::memset_i64);
333     uint64_t Size = CGF.getContext().getTypeSize(T);
334 
335     const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
336     llvm::Value* DestPtr = Builder.CreateBitCast(LV.getAddress(), BP, "tmp");
337     Builder.CreateCall4(MemSet, DestPtr,
338                         llvm::ConstantInt::get(llvm::Type::Int8Ty, 0),
339                         llvm::ConstantInt::get(llvm::Type::Int64Ty, Size/8),
340                         llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
341   }
342 }
343 
344 void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
345   if (E->hadDesignators()) {
346     CGF.ErrorUnsupported(E, "initializer list with designators");
347     return;
348   }
349 
350   // FIXME: For constant expressions, call into const expr emitter so
351   // that we can emit a memcpy instead of storing the individual
352   // members.  This is purely for perf; both codepaths lead to
353   // equivalent (although not necessarily identical) code.  It's worth
354   // noting that LLVM keeps on getting smarter, though, so it might
355   // not be worth bothering.
356 
357   // Handle initialization of an array.
358   if (E->getType()->isArrayType()) {
359     const llvm::PointerType *APType =
360       cast<llvm::PointerType>(DestPtr->getType());
361     const llvm::ArrayType *AType =
362       cast<llvm::ArrayType>(APType->getElementType());
363 
364     uint64_t NumInitElements = E->getNumInits();
365 
366     if (E->getNumInits() > 0) {
367       QualType T1 = E->getType();
368       QualType T2 = E->getInit(0)->getType();
369       if (CGF.getContext().getCanonicalType(T1).getUnqualifiedType() ==
370           CGF.getContext().getCanonicalType(T2).getUnqualifiedType()) {
371         EmitAggLoadOfLValue(E->getInit(0));
372         return;
373       }
374     }
375 
376     uint64_t NumArrayElements = AType->getNumElements();
377     QualType ElementType = CGF.getContext().getCanonicalType(E->getType());
378     ElementType =CGF.getContext().getAsArrayType(ElementType)->getElementType();
379 
380     unsigned CVRqualifier = ElementType.getCVRQualifiers();
381 
382     for (uint64_t i = 0; i != NumArrayElements; ++i) {
383       llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array");
384       if (i < NumInitElements)
385         EmitInitializationToLValue(E->getInit(i),
386                                    LValue::MakeAddr(NextVal, CVRqualifier));
387       else
388         EmitNullInitializationToLValue(LValue::MakeAddr(NextVal, CVRqualifier),
389                                        ElementType);
390     }
391     return;
392   }
393 
394   assert(E->getType()->isRecordType() && "Only support structs/unions here!");
395 
396   // Do struct initialization; this code just sets each individual member
397   // to the approprate value.  This makes bitfield support automatic;
398   // the disadvantage is that the generated code is more difficult for
399   // the optimizer, especially with bitfields.
400   unsigned NumInitElements = E->getNumInits();
401   RecordDecl *SD = E->getType()->getAsRecordType()->getDecl();
402   unsigned NumMembers = SD->getNumMembers() - SD->hasFlexibleArrayMember();
403   unsigned CurInitVal = 0;
404   bool isUnion = E->getType()->isUnionType();
405 
406   // Here we iterate over the fields; this makes it simpler to both
407   // default-initialize fields and skip over unnamed fields.
408   for (unsigned CurFieldNo = 0; CurFieldNo != NumMembers; ++CurFieldNo) {
409     FieldDecl *CurField = SD->getMember(CurFieldNo);
410     if (CurField->getIdentifier() == 0) {
411       // Initializers can't initialize unnamed fields, e.g. "int : 20;"
412       continue;
413     }
414     // FIXME: volatility
415     LValue FieldLoc = CGF.EmitLValueForField(DestPtr, CurField, isUnion,0);
416     if (CurInitVal < NumInitElements) {
417       // Store the initializer into the field
418       // This will probably have to get a bit smarter when we support
419       // designators in initializers
420       EmitInitializationToLValue(E->getInit(CurInitVal++), FieldLoc);
421     } else {
422       // We're out of initalizers; default-initialize to null
423       EmitNullInitializationToLValue(FieldLoc, CurField->getType());
424     }
425 
426     // Unions only initialize one field.
427     // (things can get weird with designators, but they aren't
428     // supported yet.)
429     if (E->getType()->isUnionType())
430       break;
431   }
432 }
433 
434 //===----------------------------------------------------------------------===//
435 //                        Entry Points into this File
436 //===----------------------------------------------------------------------===//
437 
438 /// EmitAggExpr - Emit the computation of the specified expression of
439 /// aggregate type.  The result is computed into DestPtr.  Note that if
440 /// DestPtr is null, the value of the aggregate expression is not needed.
441 void CodeGenFunction::EmitAggExpr(const Expr *E, llvm::Value *DestPtr,
442                                   bool VolatileDest) {
443   assert(E && hasAggregateLLVMType(E->getType()) &&
444          "Invalid aggregate expression to emit");
445 
446   AggExprEmitter(*this, DestPtr, VolatileDest).Visit(const_cast<Expr*>(E));
447 }
448 
449 void CodeGenFunction::EmitAggregateClear(llvm::Value *DestPtr, QualType Ty) {
450   assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
451 
452   EmitMemSetToZero(DestPtr, Ty);
453 }
454 
455 void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr,
456                                         llvm::Value *SrcPtr, QualType Ty) {
457   assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
458 
459   // Aggregate assignment turns into llvm.memmove.
460   const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
461   if (DestPtr->getType() != BP)
462     DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
463   if (SrcPtr->getType() != BP)
464     SrcPtr = Builder.CreateBitCast(SrcPtr, BP, "tmp");
465 
466   // Get size and alignment info for this aggregate.
467   std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
468 
469   // FIXME: Handle variable sized types.
470   const llvm::Type *IntPtr = llvm::IntegerType::get(LLVMPointerWidth);
471 
472   Builder.CreateCall4(CGM.getMemMoveFn(),
473                       DestPtr, SrcPtr,
474                       // TypeInfo.first describes size in bits.
475                       llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
476                       llvm::ConstantInt::get(llvm::Type::Int32Ty,
477                                              TypeInfo.second/8));
478 }
479