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