1 //===--- CGExpr.cpp - Emit LLVM Code from 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 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/DerivedTypes.h"
19 #include "llvm/Function.h"
20 #include "llvm/GlobalVariable.h"
21 #include "llvm/Support/MathExtras.h"
22 using namespace clang;
23 using namespace CodeGen;
24 
25 //===--------------------------------------------------------------------===//
26 //                        Miscellaneous Helper Methods
27 //===--------------------------------------------------------------------===//
28 
29 /// CreateTempAlloca - This creates a alloca and inserts it into the entry
30 /// block.
31 llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(const llvm::Type *Ty,
32                                                     const char *Name) {
33   return new llvm::AllocaInst(Ty, 0, Name, AllocaInsertPt);
34 }
35 
36 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
37 /// expression and compare the result against zero, returning an Int1Ty value.
38 llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
39   QualType BoolTy = getContext().BoolTy;
40   if (!E->getType()->isAnyComplexType())
41     return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy);
42 
43   return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(),BoolTy);
44 }
45 
46 /// EmitAnyExpr - Emit code to compute the specified expression which can have
47 /// any type.  The result is returned as an RValue struct.  If this is an
48 /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
49 /// the result should be returned.
50 RValue CodeGenFunction::EmitAnyExpr(const Expr *E, llvm::Value *AggLoc,
51                                     bool isAggLocVolatile) {
52   if (!hasAggregateLLVMType(E->getType()))
53     return RValue::get(EmitScalarExpr(E));
54   else if (E->getType()->isAnyComplexType())
55     return RValue::getComplex(EmitComplexExpr(E));
56 
57   EmitAggExpr(E, AggLoc, isAggLocVolatile);
58   return RValue::getAggregate(AggLoc);
59 }
60 
61 
62 //===----------------------------------------------------------------------===//
63 //                         LValue Expression Emission
64 //===----------------------------------------------------------------------===//
65 
66 /// EmitLValue - Emit code to compute a designator that specifies the location
67 /// of the expression.
68 ///
69 /// This can return one of two things: a simple address or a bitfield
70 /// reference.  In either case, the LLVM Value* in the LValue structure is
71 /// guaranteed to be an LLVM pointer type.
72 ///
73 /// If this returns a bitfield reference, nothing about the pointee type of
74 /// the LLVM value is known: For example, it may not be a pointer to an
75 /// integer.
76 ///
77 /// If this returns a normal address, and if the lvalue's C type is fixed
78 /// size, this method guarantees that the returned pointer type will point to
79 /// an LLVM type of the same size of the lvalue's type.  If the lvalue has a
80 /// variable length type, this is not possible.
81 ///
82 LValue CodeGenFunction::EmitLValue(const Expr *E) {
83   switch (E->getStmtClass()) {
84   default: {
85     printf("Statement class: %d\n", E->getStmtClass());
86     WarnUnsupported(E, "l-value expression");
87     llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
88     return LValue::MakeAddr(llvm::UndefValue::get(Ty));
89   }
90 
91   case Expr::CallExprClass: return EmitCallExprLValue(cast<CallExpr>(E));
92   case Expr::DeclRefExprClass: return EmitDeclRefLValue(cast<DeclRefExpr>(E));
93   case Expr::ParenExprClass:return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
94   case Expr::PreDefinedExprClass:
95     return EmitPreDefinedLValue(cast<PreDefinedExpr>(E));
96   case Expr::StringLiteralClass:
97     return EmitStringLiteralLValue(cast<StringLiteral>(E));
98 
99   case Expr::ObjCIvarRefExprClass:
100     return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
101 
102   case Expr::UnaryOperatorClass:
103     return EmitUnaryOpLValue(cast<UnaryOperator>(E));
104   case Expr::ArraySubscriptExprClass:
105     return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
106   case Expr::ExtVectorElementExprClass:
107     return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
108   case Expr::MemberExprClass: return EmitMemberExpr(cast<MemberExpr>(E));
109   case Expr::CompoundLiteralExprClass:
110     return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
111   }
112 }
113 
114 /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
115 /// this method emits the address of the lvalue, then loads the result as an
116 /// rvalue, returning the rvalue.
117 RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, QualType ExprType) {
118   if (LV.isSimple()) {
119     llvm::Value *Ptr = LV.getAddress();
120     const llvm::Type *EltTy =
121       cast<llvm::PointerType>(Ptr->getType())->getElementType();
122 
123     // Simple scalar l-value.
124     if (EltTy->isFirstClassType()) {
125       llvm::Value *V = Builder.CreateLoad(Ptr, "tmp");
126 
127       // Bool can have different representation in memory than in registers.
128       if (ExprType->isBooleanType()) {
129         if (V->getType() != llvm::Type::Int1Ty)
130           V = Builder.CreateTrunc(V, llvm::Type::Int1Ty, "tobool");
131       }
132 
133       return RValue::get(V);
134     }
135 
136     assert(ExprType->isFunctionType() && "Unknown scalar value");
137     return RValue::get(Ptr);
138   }
139 
140   if (LV.isVectorElt()) {
141     llvm::Value *Vec = Builder.CreateLoad(LV.getVectorAddr(), "tmp");
142     return RValue::get(Builder.CreateExtractElement(Vec, LV.getVectorIdx(),
143                                                     "vecext"));
144   }
145 
146   // If this is a reference to a subset of the elements of a vector, either
147   // shuffle the input or extract/insert them as appropriate.
148   if (LV.isExtVectorElt())
149     return EmitLoadOfExtVectorElementLValue(LV, ExprType);
150 
151   if (LV.isBitfield())
152     return EmitLoadOfBitfieldLValue(LV, ExprType);
153 
154   assert(0 && "Unknown LValue type!");
155   //an invalid RValue, but the assert will
156   //ensure that this point is never reached
157   return RValue();
158 }
159 
160 RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
161                                                  QualType ExprType) {
162   llvm::Value *Ptr = LV.getBitfieldAddr();
163   const llvm::Type *EltTy =
164     cast<llvm::PointerType>(Ptr->getType())->getElementType();
165   unsigned EltTySize = EltTy->getPrimitiveSizeInBits();
166   unsigned short BitfieldSize = LV.getBitfieldSize();
167   unsigned short EndBit = LV.getBitfieldStartBit() + BitfieldSize;
168 
169   llvm::Value *V = Builder.CreateLoad(Ptr, "tmp");
170 
171   llvm::Value *ShAmt = llvm::ConstantInt::get(EltTy, EltTySize - EndBit);
172   V = Builder.CreateShl(V, ShAmt, "tmp");
173 
174   ShAmt = llvm::ConstantInt::get(EltTy, EltTySize - BitfieldSize);
175   V = LV.isBitfieldSigned() ?
176     Builder.CreateAShr(V, ShAmt, "tmp") :
177     Builder.CreateLShr(V, ShAmt, "tmp");
178   return RValue::get(V);
179 }
180 
181 // If this is a reference to a subset of the elements of a vector, either
182 // shuffle the input or extract/insert them as appropriate.
183 RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV,
184                                                          QualType ExprType) {
185   llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddr(), "tmp");
186 
187   const llvm::Constant *Elts = LV.getExtVectorElts();
188 
189   // If the result of the expression is a non-vector type, we must be
190   // extracting a single element.  Just codegen as an extractelement.
191   const VectorType *ExprVT = ExprType->getAsVectorType();
192   if (!ExprVT) {
193     unsigned InIdx = ExtVectorElementExpr::getAccessedFieldNo(0, Elts);
194     llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
195     return RValue::get(Builder.CreateExtractElement(Vec, Elt, "tmp"));
196   }
197 
198   // If the source and destination have the same number of elements, use a
199   // vector shuffle instead of insert/extracts.
200   unsigned NumResultElts = ExprVT->getNumElements();
201   unsigned NumSourceElts =
202     cast<llvm::VectorType>(Vec->getType())->getNumElements();
203 
204   if (NumResultElts == NumSourceElts) {
205     llvm::SmallVector<llvm::Constant*, 4> Mask;
206     for (unsigned i = 0; i != NumResultElts; ++i) {
207       unsigned InIdx = ExtVectorElementExpr::getAccessedFieldNo(i, Elts);
208       Mask.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx));
209     }
210 
211     llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size());
212     Vec = Builder.CreateShuffleVector(Vec,
213                                       llvm::UndefValue::get(Vec->getType()),
214                                       MaskV, "tmp");
215     return RValue::get(Vec);
216   }
217 
218   // Start out with an undef of the result type.
219   llvm::Value *Result = llvm::UndefValue::get(ConvertType(ExprType));
220 
221   // Extract/Insert each element of the result.
222   for (unsigned i = 0; i != NumResultElts; ++i) {
223     unsigned InIdx = ExtVectorElementExpr::getAccessedFieldNo(i, Elts);
224     llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
225     Elt = Builder.CreateExtractElement(Vec, Elt, "tmp");
226 
227     llvm::Value *OutIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
228     Result = Builder.CreateInsertElement(Result, Elt, OutIdx, "tmp");
229   }
230 
231   return RValue::get(Result);
232 }
233 
234 
235 
236 /// EmitStoreThroughLValue - Store the specified rvalue into the specified
237 /// lvalue, where both are guaranteed to the have the same type, and that type
238 /// is 'Ty'.
239 void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
240                                              QualType Ty) {
241   if (!Dst.isSimple()) {
242     if (Dst.isVectorElt()) {
243       // Read/modify/write the vector, inserting the new element.
244       // FIXME: Volatility.
245       llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddr(), "tmp");
246       Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
247                                         Dst.getVectorIdx(), "vecins");
248       Builder.CreateStore(Vec, Dst.getVectorAddr());
249       return;
250     }
251 
252     // If this is an update of extended vector elements, insert them as
253     // appropriate.
254     if (Dst.isExtVectorElt())
255       return EmitStoreThroughExtVectorComponentLValue(Src, Dst, Ty);
256 
257     if (Dst.isBitfield())
258       return EmitStoreThroughBitfieldLValue(Src, Dst, Ty);
259 
260     assert(0 && "Unknown LValue type");
261   }
262 
263   llvm::Value *DstAddr = Dst.getAddress();
264   assert(Src.isScalar() && "Can't emit an agg store with this method");
265   // FIXME: Handle volatility etc.
266   const llvm::Type *SrcTy = Src.getScalarVal()->getType();
267   const llvm::PointerType *DstPtr = cast<llvm::PointerType>(DstAddr->getType());
268   const llvm::Type *AddrTy = DstPtr->getElementType();
269   unsigned AS = DstPtr->getAddressSpace();
270 
271   if (AddrTy != SrcTy)
272     DstAddr = Builder.CreateBitCast(DstAddr,
273                                     llvm::PointerType::get(SrcTy, AS),
274                                     "storetmp");
275   Builder.CreateStore(Src.getScalarVal(), DstAddr);
276 }
277 
278 void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
279                                                      QualType Ty) {
280   unsigned short StartBit = Dst.getBitfieldStartBit();
281   unsigned short BitfieldSize = Dst.getBitfieldSize();
282   llvm::Value *Ptr = Dst.getBitfieldAddr();
283   const llvm::Type *EltTy =
284     cast<llvm::PointerType>(Ptr->getType())->getElementType();
285   unsigned EltTySize = EltTy->getPrimitiveSizeInBits();
286 
287   llvm::Value *NewVal = Src.getScalarVal();
288   llvm::Value *OldVal = Builder.CreateLoad(Ptr, "tmp");
289 
290   llvm::Value *ShAmt = llvm::ConstantInt::get(EltTy, StartBit);
291   NewVal = Builder.CreateShl(NewVal, ShAmt, "tmp");
292 
293   llvm::Constant *Mask = llvm::ConstantInt::get(
294            llvm::APInt::getBitsSet(EltTySize, StartBit,
295                                    StartBit + BitfieldSize));
296 
297   // Mask out any bits that shouldn't be set in the result.
298   NewVal = Builder.CreateAnd(NewVal, Mask, "tmp");
299 
300   // Next, mask out the bits this bit-field should include from the old value.
301   Mask = llvm::ConstantExpr::getNot(Mask);
302   OldVal = Builder.CreateAnd(OldVal, Mask, "tmp");
303 
304   // Finally, merge the two together and store it.
305   NewVal = Builder.CreateOr(OldVal, NewVal, "tmp");
306 
307   Builder.CreateStore(NewVal, Ptr);
308 }
309 
310 void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
311                                                                LValue Dst,
312                                                                QualType Ty) {
313   // This access turns into a read/modify/write of the vector.  Load the input
314   // value now.
315   llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddr(), "tmp");
316   // FIXME: Volatility.
317   const llvm::Constant *Elts = Dst.getExtVectorElts();
318 
319   llvm::Value *SrcVal = Src.getScalarVal();
320 
321   if (const VectorType *VTy = Ty->getAsVectorType()) {
322     unsigned NumSrcElts = VTy->getNumElements();
323 
324     // Extract/Insert each element.
325     for (unsigned i = 0; i != NumSrcElts; ++i) {
326       llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
327       Elt = Builder.CreateExtractElement(SrcVal, Elt, "tmp");
328 
329       unsigned Idx = ExtVectorElementExpr::getAccessedFieldNo(i, Elts);
330       llvm::Value *OutIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, Idx);
331       Vec = Builder.CreateInsertElement(Vec, Elt, OutIdx, "tmp");
332     }
333   } else {
334     // If the Src is a scalar (not a vector) it must be updating one element.
335     unsigned InIdx = ExtVectorElementExpr::getAccessedFieldNo(0, Elts);
336     llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
337     Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt, "tmp");
338   }
339 
340   Builder.CreateStore(Vec, Dst.getExtVectorAddr());
341 }
342 
343 
344 LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
345   const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
346 
347   if (VD && (VD->isBlockVarDecl() || isa<ParmVarDecl>(VD))) {
348     if (VD->getStorageClass() == VarDecl::Extern)
349       return LValue::MakeAddr(CGM.GetAddrOfGlobalVar(VD, false));
350     else {
351       llvm::Value *V = LocalDeclMap[VD];
352       assert(V && "BlockVarDecl not entered in LocalDeclMap?");
353       return LValue::MakeAddr(V);
354     }
355   } else if (VD && VD->isFileVarDecl()) {
356     return LValue::MakeAddr(CGM.GetAddrOfGlobalVar(VD, false));
357   } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl())) {
358     return LValue::MakeAddr(CGM.GetAddrOfFunctionDecl(FD, false));
359   }
360   assert(0 && "Unimp declref");
361   //an invalid LValue, but the assert will
362   //ensure that this point is never reached.
363   return LValue();
364 }
365 
366 LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
367   // __extension__ doesn't affect lvalue-ness.
368   if (E->getOpcode() == UnaryOperator::Extension)
369     return EmitLValue(E->getSubExpr());
370 
371   switch (E->getOpcode()) {
372   default: assert(0 && "Unknown unary operator lvalue!");
373   case UnaryOperator::Deref:
374     return LValue::MakeAddr(EmitScalarExpr(E->getSubExpr()));
375   case UnaryOperator::Real:
376   case UnaryOperator::Imag:
377     LValue LV = EmitLValue(E->getSubExpr());
378     unsigned Idx = E->getOpcode() == UnaryOperator::Imag;
379     return LValue::MakeAddr(Builder.CreateStructGEP(LV.getAddress(),
380                                                     Idx, "idx"));
381   }
382 }
383 
384 LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
385   assert(!E->isWide() && "FIXME: Wide strings not supported yet!");
386   const char *StrData = E->getStrData();
387   unsigned Len = E->getByteLength();
388   std::string StringLiteral(StrData, StrData+Len);
389   return LValue::MakeAddr(CGM.GetAddrOfConstantString(StringLiteral));
390 }
391 
392 LValue CodeGenFunction::EmitPreDefinedLValue(const PreDefinedExpr *E) {
393   std::string FunctionName;
394   if(const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurFuncDecl)) {
395     FunctionName = FD->getName();
396   }
397   else {
398     assert(0 && "Attempting to load predefined constant for invalid decl type");
399   }
400   std::string GlobalVarName;
401 
402   switch (E->getIdentType()) {
403     default:
404       assert(0 && "unknown pre-defined ident type");
405     case PreDefinedExpr::Func:
406       GlobalVarName = "__func__.";
407       break;
408     case PreDefinedExpr::Function:
409       GlobalVarName = "__FUNCTION__.";
410       break;
411     case PreDefinedExpr::PrettyFunction:
412       // FIXME:: Demangle C++ method names
413       GlobalVarName = "__PRETTY_FUNCTION__.";
414       break;
415   }
416 
417   GlobalVarName += FunctionName;
418 
419   // FIXME: Can cache/reuse these within the module.
420   llvm::Constant *C=llvm::ConstantArray::get(FunctionName);
421 
422   // Create a global variable for this.
423   C = new llvm::GlobalVariable(C->getType(), true,
424                                llvm::GlobalValue::InternalLinkage,
425                                C, GlobalVarName, CurFn->getParent());
426   return LValue::MakeAddr(C);
427 }
428 
429 LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
430   // The index must always be an integer, which is not an aggregate.  Emit it.
431   llvm::Value *Idx = EmitScalarExpr(E->getIdx());
432 
433   // If the base is a vector type, then we are forming a vector element lvalue
434   // with this subscript.
435   if (E->getLHS()->getType()->isVectorType()) {
436     // Emit the vector as an lvalue to get its address.
437     LValue LHS = EmitLValue(E->getLHS());
438     assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
439     // FIXME: This should properly sign/zero/extend or truncate Idx to i32.
440     return LValue::MakeVectorElt(LHS.getAddress(), Idx);
441   }
442 
443   // The base must be a pointer, which is not an aggregate.  Emit it.
444   llvm::Value *Base = EmitScalarExpr(E->getBase());
445 
446   // Extend or truncate the index type to 32 or 64-bits.
447   QualType IdxTy  = E->getIdx()->getType();
448   bool IdxSigned = IdxTy->isSignedIntegerType();
449   unsigned IdxBitwidth = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
450   if (IdxBitwidth != LLVMPointerWidth)
451     Idx = Builder.CreateIntCast(Idx, llvm::IntegerType::get(LLVMPointerWidth),
452                                 IdxSigned, "idxprom");
453 
454   // We know that the pointer points to a type of the correct size, unless the
455   // size is a VLA.
456   if (!E->getType()->isConstantSizeType())
457     assert(0 && "VLA idx not implemented");
458   return LValue::MakeAddr(Builder.CreateGEP(Base, Idx, "arrayidx"));
459 }
460 
461 static
462 llvm::Constant *GenerateConstantVector(llvm::SmallVector<unsigned, 4> &Elts) {
463   llvm::SmallVector<llvm::Constant *, 4> CElts;
464 
465   for (unsigned i = 0, e = Elts.size(); i != e; ++i)
466     CElts.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, Elts[i]));
467 
468   return llvm::ConstantVector::get(&CElts[0], CElts.size());
469 }
470 
471 LValue CodeGenFunction::
472 EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
473   // Emit the base vector as an l-value.
474   LValue Base = EmitLValue(E->getBase());
475 
476   // Encode the element access list into a vector of unsigned indices.
477   llvm::SmallVector<unsigned, 4> Indices;
478   E->getEncodedElementAccess(Indices);
479 
480   if (Base.isSimple()) {
481     llvm::Constant *CV = GenerateConstantVector(Indices);
482     return LValue::MakeExtVectorElt(Base.getAddress(), CV);
483   }
484   assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
485 
486   llvm::Constant *BaseElts = Base.getExtVectorElts();
487   llvm::SmallVector<llvm::Constant *, 4> CElts;
488 
489   for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
490     if (isa<llvm::ConstantAggregateZero>(BaseElts))
491       CElts.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
492     else
493       CElts.push_back(BaseElts->getOperand(Indices[i]));
494   }
495   llvm::Constant *CV = llvm::ConstantVector::get(&CElts[0], CElts.size());
496   return LValue::MakeExtVectorElt(Base.getExtVectorAddr(), CV);
497 }
498 
499 LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
500   bool isUnion = false;
501   Expr *BaseExpr = E->getBase();
502   llvm::Value *BaseValue = NULL;
503 
504   // If this is s.x, emit s as an lvalue.  If it is s->x, emit s as a scalar.
505   if (E->isArrow()) {
506     BaseValue = EmitScalarExpr(BaseExpr);
507     const PointerType *PTy =
508       cast<PointerType>(BaseExpr->getType().getCanonicalType());
509     if (PTy->getPointeeType()->isUnionType())
510       isUnion = true;
511   }
512   else {
513     LValue BaseLV = EmitLValue(BaseExpr);
514     // FIXME: this isn't right for bitfields.
515     BaseValue = BaseLV.getAddress();
516     if (BaseExpr->getType()->isUnionType())
517       isUnion = true;
518   }
519 
520   FieldDecl *Field = E->getMemberDecl();
521   return EmitLValueForField(BaseValue, Field, isUnion);
522 }
523 
524 LValue CodeGenFunction::EmitLValueForField(llvm::Value* BaseValue,
525                                            FieldDecl* Field,
526                                            bool isUnion)
527 {
528   llvm::Value *V;
529   unsigned idx = CGM.getTypes().getLLVMFieldNo(Field);
530 
531   if (!Field->isBitField()) {
532     V = Builder.CreateStructGEP(BaseValue, idx, "tmp");
533   } else {
534     const llvm::Type *FieldTy = ConvertType(Field->getType());
535     const llvm::PointerType *BaseTy =
536       cast<llvm::PointerType>(BaseValue->getType());
537     unsigned AS = BaseTy->getAddressSpace();
538     BaseValue = Builder.CreateBitCast(BaseValue,
539                                       llvm::PointerType::get(FieldTy, AS),
540                                       "tmp");
541     V = Builder.CreateGEP(BaseValue,
542                           llvm::ConstantInt::get(llvm::Type::Int32Ty, idx),
543                           "tmp");
544   }
545 
546   // Match union field type.
547   if (isUnion) {
548     const llvm::Type * FieldTy = ConvertType(Field->getType());
549     const llvm::PointerType * BaseTy =
550       cast<llvm::PointerType>(BaseValue->getType());
551     if (FieldTy != BaseTy->getElementType()) {
552       unsigned AS = BaseTy->getAddressSpace();
553       V = Builder.CreateBitCast(V,
554                                 llvm::PointerType::get(FieldTy, AS),
555                                 "tmp");
556     }
557   }
558 
559   if (!Field->isBitField())
560     return LValue::MakeAddr(V);
561 
562   CodeGenTypes::BitFieldInfo bitFieldInfo =
563     CGM.getTypes().getBitFieldInfo(Field);
564   return LValue::MakeBitfield(V, bitFieldInfo.Begin, bitFieldInfo.Size,
565                               Field->getType()->isSignedIntegerType());
566 }
567 
568 LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr* E) {
569   const llvm::Type *LTy = ConvertType(E->getType());
570   llvm::Value *DeclPtr = CreateTempAlloca(LTy, ".compoundliteral");
571 
572   const Expr* InitExpr = E->getInitializer();
573   LValue Result = LValue::MakeAddr(DeclPtr);
574 
575   if (E->getType()->isComplexType()) {
576     EmitComplexExprIntoAddr(InitExpr, DeclPtr, false);
577   } else if (hasAggregateLLVMType(E->getType())) {
578     EmitAnyExpr(InitExpr, DeclPtr, false);
579   } else {
580     EmitStoreThroughLValue(EmitAnyExpr(InitExpr), Result, E->getType());
581   }
582 
583   return Result;
584 }
585 
586 //===--------------------------------------------------------------------===//
587 //                             Expression Emission
588 //===--------------------------------------------------------------------===//
589 
590 
591 RValue CodeGenFunction::EmitCallExpr(const CallExpr *E) {
592   if (const ImplicitCastExpr *IcExpr =
593       dyn_cast<const ImplicitCastExpr>(E->getCallee()))
594     if (const DeclRefExpr *DRExpr =
595         dyn_cast<const DeclRefExpr>(IcExpr->getSubExpr()))
596       if (const FunctionDecl *FDecl =
597           dyn_cast<const FunctionDecl>(DRExpr->getDecl()))
598         if (unsigned builtinID = FDecl->getIdentifier()->getBuiltinID())
599           return EmitBuiltinExpr(builtinID, E);
600 
601   llvm::Value *Callee = EmitScalarExpr(E->getCallee());
602   return EmitCallExpr(Callee, E->getCallee()->getType(),
603                       E->arg_begin(), E->getNumArgs());
604 }
605 
606 RValue CodeGenFunction::EmitCallExpr(Expr *FnExpr, Expr *const *Args,
607                                      unsigned NumArgs) {
608   llvm::Value *Callee = EmitScalarExpr(FnExpr);
609   return EmitCallExpr(Callee, FnExpr->getType(), Args, NumArgs);
610 }
611 
612 LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
613   // Can only get l-value for call expression returning aggregate type
614   RValue RV = EmitCallExpr(E);
615   return LValue::MakeAddr(RV.getAggregateAddr());
616 }
617 
618 LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
619   // Objective-C objects are traditionally C structures with their layout
620   // defined at compile-time.  In some implementations, their layout is not
621   // defined until run time in order to allow instance variables to be added to
622   // a class without recompiling all of the subclasses.  If this is the case
623   // then the CGObjCRuntime subclass must return true to LateBoundIvars and
624   // implement the lookup itself.
625   if (CGM.getObjCRuntime()->LateBoundIVars()) {
626     assert(0 && "FIXME: Implement support for late-bound instance variables");
627     return LValue(); // Not reached.
628   }
629 
630   // Get a structure type for the object
631   QualType ExprTy = E->getBase()->getType();
632   const llvm::Type *ObjectType = ConvertType(ExprTy);
633   // TODO:  Add a special case for isa (index 0)
634   // Work out which index the ivar is
635   const ObjCIvarDecl *Decl = E->getDecl();
636   unsigned Index = CGM.getTypes().getLLVMFieldNo(Decl);
637 
638   // Get object pointer and coerce object pointer to correct type.
639   llvm::Value *Object = EmitLValue(E->getBase()).getAddress();
640   Object = Builder.CreateLoad(Object, E->getDecl()->getName());
641   if (Object->getType() != ObjectType)
642     Object = Builder.CreateBitCast(Object, ObjectType);
643 
644 
645   // Return a pointer to the right element.
646   return LValue::MakeAddr(Builder.CreateStructGEP(Object, Index,
647                                                   Decl->getName()));
648 }
649 
650 RValue CodeGenFunction::EmitCallExpr(llvm::Value *Callee, QualType FnType,
651                                      Expr *const *ArgExprs, unsigned NumArgs) {
652   // The callee type will always be a pointer to function type, get the function
653   // type.
654   FnType = cast<PointerType>(FnType.getCanonicalType())->getPointeeType();
655   QualType ResultType = cast<FunctionType>(FnType)->getResultType();
656 
657   llvm::SmallVector<llvm::Value*, 16> Args;
658 
659   // Handle struct-return functions by passing a pointer to the location that
660   // we would like to return into.
661   if (hasAggregateLLVMType(ResultType)) {
662     // Create a temporary alloca to hold the result of the call. :(
663     Args.push_back(CreateTempAlloca(ConvertType(ResultType)));
664     // FIXME: set the stret attribute on the argument.
665   }
666 
667   for (unsigned i = 0, e = NumArgs; i != e; ++i) {
668     QualType ArgTy = ArgExprs[i]->getType();
669 
670     if (!hasAggregateLLVMType(ArgTy)) {
671       // Scalar argument is passed by-value.
672       Args.push_back(EmitScalarExpr(ArgExprs[i]));
673     } else if (ArgTy->isAnyComplexType()) {
674       // Make a temporary alloca to pass the argument.
675       llvm::Value *DestMem = CreateTempAlloca(ConvertType(ArgTy));
676       EmitComplexExprIntoAddr(ArgExprs[i], DestMem, false);
677       Args.push_back(DestMem);
678     } else {
679       llvm::Value *DestMem = CreateTempAlloca(ConvertType(ArgTy));
680       EmitAggExpr(ArgExprs[i], DestMem, false);
681       Args.push_back(DestMem);
682     }
683   }
684 
685   llvm::CallInst *CI = Builder.CreateCall(Callee,&Args[0],&Args[0]+Args.size());
686   if (const llvm::Function *F = dyn_cast<llvm::Function>(Callee))
687     CI->setCallingConv(F->getCallingConv());
688   if (CI->getType() != llvm::Type::VoidTy)
689     CI->setName("call");
690   else if (ResultType->isAnyComplexType())
691     return RValue::getComplex(LoadComplexFromAddr(Args[0], false));
692   else if (hasAggregateLLVMType(ResultType))
693     // Struct return.
694     return RValue::getAggregate(Args[0]);
695   else {
696     // void return.
697     assert(ResultType->isVoidType() && "Should only have a void expr here");
698     CI = 0;
699   }
700 
701   return RValue::get(CI);
702 }
703