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 "CGCall.h"
17 #include "CGObjCRuntime.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "llvm/Target/TargetData.h"
21 using namespace clang;
22 using namespace CodeGen;
23 
24 //===--------------------------------------------------------------------===//
25 //                        Miscellaneous Helper Methods
26 //===--------------------------------------------------------------------===//
27 
28 /// CreateTempAlloca - This creates a alloca and inserts it into the entry
29 /// block.
30 llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(const llvm::Type *Ty,
31                                                     const char *Name) {
32   return new llvm::AllocaInst(Ty, 0, Name, AllocaInsertPt);
33 }
34 
35 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
36 /// expression and compare the result against zero, returning an Int1Ty value.
37 llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
38   QualType BoolTy = getContext().BoolTy;
39   if (!E->getType()->isAnyComplexType())
40     return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy);
41 
42   return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(),BoolTy);
43 }
44 
45 /// EmitAnyExpr - Emit code to compute the specified expression which can have
46 /// any type.  The result is returned as an RValue struct.  If this is an
47 /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
48 /// the result should be returned.
49 RValue CodeGenFunction::EmitAnyExpr(const Expr *E, llvm::Value *AggLoc,
50                                     bool isAggLocVolatile) {
51   if (!hasAggregateLLVMType(E->getType()))
52     return RValue::get(EmitScalarExpr(E));
53   else if (E->getType()->isAnyComplexType())
54     return RValue::getComplex(EmitComplexExpr(E));
55 
56   EmitAggExpr(E, AggLoc, isAggLocVolatile);
57   return RValue::getAggregate(AggLoc);
58 }
59 
60 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result
61 /// will always be accessible even if no aggregate location is
62 /// provided.
63 RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E, llvm::Value *AggLoc,
64                                           bool isAggLocVolatile) {
65   if (!AggLoc && hasAggregateLLVMType(E->getType()) &&
66       !E->getType()->isAnyComplexType())
67     AggLoc = CreateTempAlloca(ConvertType(E->getType()), "agg.tmp");
68   return EmitAnyExpr(E, AggLoc, isAggLocVolatile);
69 }
70 
71 /// getAccessedFieldNo - Given an encoded value and a result number, return
72 /// the input field number being accessed.
73 unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
74                                              const llvm::Constant *Elts) {
75   if (isa<llvm::ConstantAggregateZero>(Elts))
76     return 0;
77 
78   return cast<llvm::ConstantInt>(Elts->getOperand(Idx))->getZExtValue();
79 }
80 
81 
82 //===----------------------------------------------------------------------===//
83 //                         LValue Expression Emission
84 //===----------------------------------------------------------------------===//
85 
86 RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
87   if (Ty->isVoidType()) {
88     return RValue::get(0);
89   } else if (const ComplexType *CTy = Ty->getAsComplexType()) {
90     const llvm::Type *EltTy = ConvertType(CTy->getElementType());
91     llvm::Value *U = llvm::UndefValue::get(EltTy);
92     return RValue::getComplex(std::make_pair(U, U));
93   } else if (hasAggregateLLVMType(Ty)) {
94     const llvm::Type *LTy = llvm::PointerType::getUnqual(ConvertType(Ty));
95     return RValue::getAggregate(llvm::UndefValue::get(LTy));
96   } else {
97     return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
98   }
99 }
100 
101 RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
102                                               const char *Name) {
103   ErrorUnsupported(E, Name);
104   return GetUndefRValue(E->getType());
105 }
106 
107 LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
108                                               const char *Name) {
109   ErrorUnsupported(E, Name);
110   llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
111   return LValue::MakeAddr(llvm::UndefValue::get(Ty),
112                           E->getType().getCVRQualifiers(),
113                           getContext().getObjCGCAttrKind(E->getType()));
114 }
115 
116 /// EmitLValue - Emit code to compute a designator that specifies the location
117 /// of the expression.
118 ///
119 /// This can return one of two things: a simple address or a bitfield
120 /// reference.  In either case, the LLVM Value* in the LValue structure is
121 /// guaranteed to be an LLVM pointer type.
122 ///
123 /// If this returns a bitfield reference, nothing about the pointee type of
124 /// the LLVM value is known: For example, it may not be a pointer to an
125 /// integer.
126 ///
127 /// If this returns a normal address, and if the lvalue's C type is fixed
128 /// size, this method guarantees that the returned pointer type will point to
129 /// an LLVM type of the same size of the lvalue's type.  If the lvalue has a
130 /// variable length type, this is not possible.
131 ///
132 LValue CodeGenFunction::EmitLValue(const Expr *E) {
133   switch (E->getStmtClass()) {
134   default: return EmitUnsupportedLValue(E, "l-value expression");
135 
136   case Expr::BinaryOperatorClass:
137     return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
138   case Expr::CallExprClass:
139   case Expr::CXXOperatorCallExprClass:
140     return EmitCallExprLValue(cast<CallExpr>(E));
141   case Expr::VAArgExprClass:
142     return EmitVAArgExprLValue(cast<VAArgExpr>(E));
143   case Expr::DeclRefExprClass:
144   case Expr::QualifiedDeclRefExprClass:
145     return EmitDeclRefLValue(cast<DeclRefExpr>(E));
146   case Expr::ParenExprClass:return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
147   case Expr::PredefinedExprClass:
148     return EmitPredefinedLValue(cast<PredefinedExpr>(E));
149   case Expr::StringLiteralClass:
150     return EmitStringLiteralLValue(cast<StringLiteral>(E));
151   case Expr::ObjCEncodeExprClass:
152     return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
153 
154   case Expr::BlockDeclRefExprClass:
155     return EmitBlockDeclRefLValue(cast<BlockDeclRefExpr>(E));
156 
157   case Expr::CXXConditionDeclExprClass:
158     return EmitCXXConditionDeclLValue(cast<CXXConditionDeclExpr>(E));
159 
160   case Expr::ObjCMessageExprClass:
161     return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
162   case Expr::ObjCIvarRefExprClass:
163     return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
164   case Expr::ObjCPropertyRefExprClass:
165     return EmitObjCPropertyRefLValue(cast<ObjCPropertyRefExpr>(E));
166   case Expr::ObjCKVCRefExprClass:
167     return EmitObjCKVCRefLValue(cast<ObjCKVCRefExpr>(E));
168   case Expr::ObjCSuperExprClass:
169     return EmitObjCSuperExpr(cast<ObjCSuperExpr>(E));
170 
171   case Expr::UnaryOperatorClass:
172     return EmitUnaryOpLValue(cast<UnaryOperator>(E));
173   case Expr::ArraySubscriptExprClass:
174     return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
175   case Expr::ExtVectorElementExprClass:
176     return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
177   case Expr::MemberExprClass: return EmitMemberExpr(cast<MemberExpr>(E));
178   case Expr::CompoundLiteralExprClass:
179     return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
180   case Expr::ChooseExprClass:
181     return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr(getContext()));
182   }
183 }
184 
185 llvm::Value *CodeGenFunction::EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
186                                                QualType Ty) {
187   llvm::Value *V = Builder.CreateLoad(Addr, Volatile, "tmp");
188 
189   // Bool can have different representation in memory than in
190   // registers.
191   if (Ty->isBooleanType())
192     if (V->getType() != llvm::Type::Int1Ty)
193       V = Builder.CreateTrunc(V, llvm::Type::Int1Ty, "tobool");
194 
195   return V;
196 }
197 
198 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
199                                         bool Volatile) {
200   // Handle stores of types which have different representations in
201   // memory and as LLVM values.
202 
203   // FIXME: We shouldn't be this loose, we should only do this
204   // conversion when we have a type we know has a different memory
205   // representation (e.g., bool).
206 
207   const llvm::Type *SrcTy = Value->getType();
208   const llvm::PointerType *DstPtr = cast<llvm::PointerType>(Addr->getType());
209   if (DstPtr->getElementType() != SrcTy) {
210     const llvm::Type *MemTy =
211       llvm::PointerType::get(SrcTy, DstPtr->getAddressSpace());
212     Addr = Builder.CreateBitCast(Addr, MemTy, "storetmp");
213   }
214 
215   Builder.CreateStore(Value, Addr, Volatile);
216 }
217 
218 /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
219 /// this method emits the address of the lvalue, then loads the result as an
220 /// rvalue, returning the rvalue.
221 RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, QualType ExprType) {
222   if (LV.isObjCWeak()) {
223     // load of a __weak object.
224     llvm::Value *AddrWeakObj = LV.getAddress();
225     llvm::Value *read_weak = CGM.getObjCRuntime().EmitObjCWeakRead(*this,
226                                                                    AddrWeakObj);
227     return RValue::get(read_weak);
228   }
229 
230   if (LV.isSimple()) {
231     llvm::Value *Ptr = LV.getAddress();
232     const llvm::Type *EltTy =
233       cast<llvm::PointerType>(Ptr->getType())->getElementType();
234 
235     // Simple scalar l-value.
236     if (EltTy->isSingleValueType())
237       return RValue::get(EmitLoadOfScalar(Ptr, LV.isVolatileQualified(),
238                                           ExprType));
239 
240     assert(ExprType->isFunctionType() && "Unknown scalar value");
241     return RValue::get(Ptr);
242   }
243 
244   if (LV.isVectorElt()) {
245     llvm::Value *Vec = Builder.CreateLoad(LV.getVectorAddr(),
246                                           LV.isVolatileQualified(), "tmp");
247     return RValue::get(Builder.CreateExtractElement(Vec, LV.getVectorIdx(),
248                                                     "vecext"));
249   }
250 
251   // If this is a reference to a subset of the elements of a vector, either
252   // shuffle the input or extract/insert them as appropriate.
253   if (LV.isExtVectorElt())
254     return EmitLoadOfExtVectorElementLValue(LV, ExprType);
255 
256   if (LV.isBitfield())
257     return EmitLoadOfBitfieldLValue(LV, ExprType);
258 
259   if (LV.isPropertyRef())
260     return EmitLoadOfPropertyRefLValue(LV, ExprType);
261 
262   assert(LV.isKVCRef() && "Unknown LValue type!");
263   return EmitLoadOfKVCRefLValue(LV, ExprType);
264 }
265 
266 RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
267                                                  QualType ExprType) {
268   unsigned StartBit = LV.getBitfieldStartBit();
269   unsigned BitfieldSize = LV.getBitfieldSize();
270   llvm::Value *Ptr = LV.getBitfieldAddr();
271 
272   const llvm::Type *EltTy =
273     cast<llvm::PointerType>(Ptr->getType())->getElementType();
274   unsigned EltTySize = CGM.getTargetData().getTypeSizeInBits(EltTy);
275 
276   // In some cases the bitfield may straddle two memory locations.
277   // Currently we load the entire bitfield, then do the magic to
278   // sign-extend it if necessary. This results in somewhat more code
279   // than necessary for the common case (one load), since two shifts
280   // accomplish both the masking and sign extension.
281   unsigned LowBits = std::min(BitfieldSize, EltTySize - StartBit);
282   llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "tmp");
283 
284   // Shift to proper location.
285   if (StartBit)
286     Val = Builder.CreateLShr(Val, llvm::ConstantInt::get(EltTy, StartBit),
287                              "bf.lo");
288 
289   // Mask off unused bits.
290   llvm::Constant *LowMask =
291     llvm::ConstantInt::get(llvm::APInt::getLowBitsSet(EltTySize, LowBits));
292   Val = Builder.CreateAnd(Val, LowMask, "bf.lo.cleared");
293 
294   // Fetch the high bits if necessary.
295   if (LowBits < BitfieldSize) {
296     unsigned HighBits = BitfieldSize - LowBits;
297     llvm::Value *HighPtr =
298       Builder.CreateGEP(Ptr, llvm::ConstantInt::get(llvm::Type::Int32Ty, 1),
299                         "bf.ptr.hi");
300     llvm::Value *HighVal = Builder.CreateLoad(HighPtr,
301                                               LV.isVolatileQualified(),
302                                               "tmp");
303 
304     // Mask off unused bits.
305     llvm::Constant *HighMask =
306       llvm::ConstantInt::get(llvm::APInt::getLowBitsSet(EltTySize, HighBits));
307     HighVal = Builder.CreateAnd(HighVal, HighMask, "bf.lo.cleared");
308 
309     // Shift to proper location and or in to bitfield value.
310     HighVal = Builder.CreateShl(HighVal,
311                                 llvm::ConstantInt::get(EltTy, LowBits));
312     Val = Builder.CreateOr(Val, HighVal, "bf.val");
313   }
314 
315   // Sign extend if necessary.
316   if (LV.isBitfieldSigned()) {
317     llvm::Value *ExtraBits = llvm::ConstantInt::get(EltTy,
318                                                     EltTySize - BitfieldSize);
319     Val = Builder.CreateAShr(Builder.CreateShl(Val, ExtraBits),
320                              ExtraBits, "bf.val.sext");
321   }
322 
323   // The bitfield type and the normal type differ when the storage sizes
324   // differ (currently just _Bool).
325   Val = Builder.CreateIntCast(Val, ConvertType(ExprType), false, "tmp");
326 
327   return RValue::get(Val);
328 }
329 
330 RValue CodeGenFunction::EmitLoadOfPropertyRefLValue(LValue LV,
331                                                     QualType ExprType) {
332   return EmitObjCPropertyGet(LV.getPropertyRefExpr());
333 }
334 
335 RValue CodeGenFunction::EmitLoadOfKVCRefLValue(LValue LV,
336                                                QualType ExprType) {
337   return EmitObjCPropertyGet(LV.getKVCRefExpr());
338 }
339 
340 // If this is a reference to a subset of the elements of a vector, create an
341 // appropriate shufflevector.
342 RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV,
343                                                          QualType ExprType) {
344   llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddr(),
345                                         LV.isVolatileQualified(), "tmp");
346 
347   const llvm::Constant *Elts = LV.getExtVectorElts();
348 
349   // If the result of the expression is a non-vector type, we must be
350   // extracting a single element.  Just codegen as an extractelement.
351   const VectorType *ExprVT = ExprType->getAsVectorType();
352   if (!ExprVT) {
353     unsigned InIdx = getAccessedFieldNo(0, Elts);
354     llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
355     return RValue::get(Builder.CreateExtractElement(Vec, Elt, "tmp"));
356   }
357 
358   // Always use shuffle vector to try to retain the original program structure
359   unsigned NumResultElts = ExprVT->getNumElements();
360 
361   llvm::SmallVector<llvm::Constant*, 4> Mask;
362   for (unsigned i = 0; i != NumResultElts; ++i) {
363     unsigned InIdx = getAccessedFieldNo(i, Elts);
364     Mask.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx));
365   }
366 
367   llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size());
368   Vec = Builder.CreateShuffleVector(Vec,
369                                     llvm::UndefValue::get(Vec->getType()),
370                                     MaskV, "tmp");
371   return RValue::get(Vec);
372 }
373 
374 
375 
376 /// EmitStoreThroughLValue - Store the specified rvalue into the specified
377 /// lvalue, where both are guaranteed to the have the same type, and that type
378 /// is 'Ty'.
379 void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
380                                              QualType Ty) {
381   if (!Dst.isSimple()) {
382     if (Dst.isVectorElt()) {
383       // Read/modify/write the vector, inserting the new element.
384       llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddr(),
385                                             Dst.isVolatileQualified(), "tmp");
386       Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
387                                         Dst.getVectorIdx(), "vecins");
388       Builder.CreateStore(Vec, Dst.getVectorAddr(),Dst.isVolatileQualified());
389       return;
390     }
391 
392     // If this is an update of extended vector elements, insert them as
393     // appropriate.
394     if (Dst.isExtVectorElt())
395       return EmitStoreThroughExtVectorComponentLValue(Src, Dst, Ty);
396 
397     if (Dst.isBitfield())
398       return EmitStoreThroughBitfieldLValue(Src, Dst, Ty);
399 
400     if (Dst.isPropertyRef())
401       return EmitStoreThroughPropertyRefLValue(Src, Dst, Ty);
402 
403     if (Dst.isKVCRef())
404       return EmitStoreThroughKVCRefLValue(Src, Dst, Ty);
405 
406     assert(0 && "Unknown LValue type");
407   }
408 
409   if (Dst.isObjCWeak() && !Dst.isNonGC()) {
410     // load of a __weak object.
411     llvm::Value *LvalueDst = Dst.getAddress();
412     llvm::Value *src = Src.getScalarVal();
413     CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
414     return;
415   }
416 
417   if (Dst.isObjCStrong() && !Dst.isNonGC()) {
418     // load of a __strong object.
419     llvm::Value *LvalueDst = Dst.getAddress();
420     llvm::Value *src = Src.getScalarVal();
421 #if 0
422     // FIXME. We cannot positively determine if we have an
423     // 'ivar' assignment, object assignment or an unknown
424     // assignment. For now, generate call to objc_assign_strongCast
425     // assignment which is a safe, but consevative assumption.
426     if (Dst.isObjCIvar())
427       CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, LvalueDst);
428     else
429       CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst);
430 #endif
431     CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
432     return;
433   }
434 
435   assert(Src.isScalar() && "Can't emit an agg store with this method");
436   EmitStoreOfScalar(Src.getScalarVal(), Dst.getAddress(),
437                     Dst.isVolatileQualified());
438 }
439 
440 void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
441                                                      QualType Ty,
442                                                      llvm::Value **Result) {
443   unsigned StartBit = Dst.getBitfieldStartBit();
444   unsigned BitfieldSize = Dst.getBitfieldSize();
445   llvm::Value *Ptr = Dst.getBitfieldAddr();
446 
447   const llvm::Type *EltTy =
448     cast<llvm::PointerType>(Ptr->getType())->getElementType();
449   unsigned EltTySize = CGM.getTargetData().getTypeSizeInBits(EltTy);
450 
451   // Get the new value, cast to the appropriate type and masked to
452   // exactly the size of the bit-field.
453   llvm::Value *SrcVal = Src.getScalarVal();
454   llvm::Value *NewVal = Builder.CreateIntCast(SrcVal, EltTy, false, "tmp");
455   llvm::Constant *Mask =
456     llvm::ConstantInt::get(llvm::APInt::getLowBitsSet(EltTySize, BitfieldSize));
457   NewVal = Builder.CreateAnd(NewVal, Mask, "bf.value");
458 
459   // Return the new value of the bit-field, if requested.
460   if (Result) {
461     // Cast back to the proper type for result.
462     const llvm::Type *SrcTy = SrcVal->getType();
463     llvm::Value *SrcTrunc = Builder.CreateIntCast(NewVal, SrcTy, false,
464                                                   "bf.reload.val");
465 
466     // Sign extend if necessary.
467     if (Dst.isBitfieldSigned()) {
468       unsigned SrcTySize = CGM.getTargetData().getTypeSizeInBits(SrcTy);
469       llvm::Value *ExtraBits = llvm::ConstantInt::get(SrcTy,
470                                                       SrcTySize - BitfieldSize);
471       SrcTrunc = Builder.CreateAShr(Builder.CreateShl(SrcTrunc, ExtraBits),
472                                     ExtraBits, "bf.reload.sext");
473     }
474 
475     *Result = SrcTrunc;
476   }
477 
478   // In some cases the bitfield may straddle two memory locations.
479   // Emit the low part first and check to see if the high needs to be
480   // done.
481   unsigned LowBits = std::min(BitfieldSize, EltTySize - StartBit);
482   llvm::Value *LowVal = Builder.CreateLoad(Ptr, Dst.isVolatileQualified(),
483                                            "bf.prev.low");
484 
485   // Compute the mask for zero-ing the low part of this bitfield.
486   llvm::Constant *InvMask =
487     llvm::ConstantInt::get(~llvm::APInt::getBitsSet(EltTySize, StartBit,
488                                                     StartBit + LowBits));
489 
490   // Compute the new low part as
491   //   LowVal = (LowVal & InvMask) | (NewVal << StartBit),
492   // with the shift of NewVal implicitly stripping the high bits.
493   llvm::Value *NewLowVal =
494     Builder.CreateShl(NewVal, llvm::ConstantInt::get(EltTy, StartBit),
495                       "bf.value.lo");
496   LowVal = Builder.CreateAnd(LowVal, InvMask, "bf.prev.lo.cleared");
497   LowVal = Builder.CreateOr(LowVal, NewLowVal, "bf.new.lo");
498 
499   // Write back.
500   Builder.CreateStore(LowVal, Ptr, Dst.isVolatileQualified());
501 
502   // If the low part doesn't cover the bitfield emit a high part.
503   if (LowBits < BitfieldSize) {
504     unsigned HighBits = BitfieldSize - LowBits;
505     llvm::Value *HighPtr =
506       Builder.CreateGEP(Ptr, llvm::ConstantInt::get(llvm::Type::Int32Ty, 1),
507                         "bf.ptr.hi");
508     llvm::Value *HighVal = Builder.CreateLoad(HighPtr,
509                                               Dst.isVolatileQualified(),
510                                               "bf.prev.hi");
511 
512     // Compute the mask for zero-ing the high part of this bitfield.
513     llvm::Constant *InvMask =
514       llvm::ConstantInt::get(~llvm::APInt::getLowBitsSet(EltTySize, HighBits));
515 
516     // Compute the new high part as
517     //   HighVal = (HighVal & InvMask) | (NewVal lshr LowBits),
518     // where the high bits of NewVal have already been cleared and the
519     // shift stripping the low bits.
520     llvm::Value *NewHighVal =
521       Builder.CreateLShr(NewVal, llvm::ConstantInt::get(EltTy, LowBits),
522                         "bf.value.high");
523     HighVal = Builder.CreateAnd(HighVal, InvMask, "bf.prev.hi.cleared");
524     HighVal = Builder.CreateOr(HighVal, NewHighVal, "bf.new.hi");
525 
526     // Write back.
527     Builder.CreateStore(HighVal, HighPtr, Dst.isVolatileQualified());
528   }
529 }
530 
531 void CodeGenFunction::EmitStoreThroughPropertyRefLValue(RValue Src,
532                                                         LValue Dst,
533                                                         QualType Ty) {
534   EmitObjCPropertySet(Dst.getPropertyRefExpr(), Src);
535 }
536 
537 void CodeGenFunction::EmitStoreThroughKVCRefLValue(RValue Src,
538                                                    LValue Dst,
539                                                    QualType Ty) {
540   EmitObjCPropertySet(Dst.getKVCRefExpr(), Src);
541 }
542 
543 void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
544                                                                LValue Dst,
545                                                                QualType Ty) {
546   // This access turns into a read/modify/write of the vector.  Load the input
547   // value now.
548   llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddr(),
549                                         Dst.isVolatileQualified(), "tmp");
550   const llvm::Constant *Elts = Dst.getExtVectorElts();
551 
552   llvm::Value *SrcVal = Src.getScalarVal();
553 
554   if (const VectorType *VTy = Ty->getAsVectorType()) {
555     unsigned NumSrcElts = VTy->getNumElements();
556     unsigned NumDstElts =
557        cast<llvm::VectorType>(Vec->getType())->getNumElements();
558     if (NumDstElts == NumSrcElts) {
559       // Use shuffle vector is the src and destination are the same number
560       // of elements
561       llvm::SmallVector<llvm::Constant*, 4> Mask;
562       for (unsigned i = 0; i != NumSrcElts; ++i) {
563         unsigned InIdx = getAccessedFieldNo(i, Elts);
564         Mask.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx));
565       }
566 
567       llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size());
568       Vec = Builder.CreateShuffleVector(SrcVal,
569                                         llvm::UndefValue::get(Vec->getType()),
570                                         MaskV, "tmp");
571     }
572     else if (NumDstElts > NumSrcElts) {
573       // Extended the source vector to the same length and then shuffle it
574       // into the destination.
575       // FIXME: since we're shuffling with undef, can we just use the indices
576       //        into that?  This could be simpler.
577       llvm::SmallVector<llvm::Constant*, 4> ExtMask;
578       unsigned i;
579       for (i = 0; i != NumSrcElts; ++i)
580         ExtMask.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, i));
581       for (; i != NumDstElts; ++i)
582         ExtMask.push_back(llvm::UndefValue::get(llvm::Type::Int32Ty));
583       llvm::Value *ExtMaskV = llvm::ConstantVector::get(&ExtMask[0],
584                                                         ExtMask.size());
585       llvm::Value *ExtSrcVal =
586         Builder.CreateShuffleVector(SrcVal,
587                                     llvm::UndefValue::get(SrcVal->getType()),
588                                     ExtMaskV, "tmp");
589       // build identity
590       llvm::SmallVector<llvm::Constant*, 4> Mask;
591       for (unsigned i = 0; i != NumDstElts; ++i) {
592         Mask.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, i));
593       }
594       // modify when what gets shuffled in
595       for (unsigned i = 0; i != NumSrcElts; ++i) {
596         unsigned Idx = getAccessedFieldNo(i, Elts);
597         Mask[Idx] =llvm::ConstantInt::get(llvm::Type::Int32Ty, i+NumDstElts);
598       }
599       llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size());
600       Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV, "tmp");
601     }
602     else {
603       // We should never shorten the vector
604       assert(0 && "unexpected shorten vector length");
605     }
606   } else {
607     // If the Src is a scalar (not a vector) it must be updating one element.
608     unsigned InIdx = getAccessedFieldNo(0, Elts);
609     llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
610     Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt, "tmp");
611   }
612 
613   Builder.CreateStore(Vec, Dst.getExtVectorAddr(), Dst.isVolatileQualified());
614 }
615 
616 LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
617   const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
618 
619   if (VD && (VD->isBlockVarDecl() || isa<ParmVarDecl>(VD) ||
620         isa<ImplicitParamDecl>(VD))) {
621     LValue LV;
622     if (VD->getStorageClass() == VarDecl::Extern) {
623       LV = LValue::MakeAddr(CGM.GetAddrOfGlobalVar(VD),
624                             E->getType().getCVRQualifiers(),
625                             getContext().getObjCGCAttrKind(E->getType()));
626     }
627     else {
628       llvm::Value *V = LocalDeclMap[VD];
629       assert(V && "DeclRefExpr not entered in LocalDeclMap?");
630       // local variables do not get their gc attribute set.
631       QualType::GCAttrTypes attr = QualType::GCNone;
632       // local static?
633       if (!VD->hasLocalStorage())
634         attr = getContext().getObjCGCAttrKind(E->getType());
635       if (VD->getAttr<BlocksAttr>()) {
636         bool needsCopyDispose = BlockRequiresCopying(VD->getType());
637         const llvm::Type *PtrStructTy = V->getType();
638         const llvm::Type *Ty = PtrStructTy;
639         Ty = llvm::PointerType::get(Ty, 0);
640         V = Builder.CreateStructGEP(V, 1, "forwarding");
641         V = Builder.CreateBitCast(V, Ty);
642         V = Builder.CreateLoad(V, false);
643         V = Builder.CreateBitCast(V, PtrStructTy);
644         V = Builder.CreateStructGEP(V, needsCopyDispose*2 + 4, "x");
645       }
646       LV = LValue::MakeAddr(V, E->getType().getCVRQualifiers(), attr);
647     }
648     LValue::SetObjCNonGC(LV, VD->hasLocalStorage());
649     return LV;
650   } else if (VD && VD->isFileVarDecl()) {
651     LValue LV = LValue::MakeAddr(CGM.GetAddrOfGlobalVar(VD),
652                                  E->getType().getCVRQualifiers(),
653                                  getContext().getObjCGCAttrKind(E->getType()));
654     return LV;
655   } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl())) {
656     return LValue::MakeAddr(CGM.GetAddrOfFunction(FD),
657                             E->getType().getCVRQualifiers(),
658                             getContext().getObjCGCAttrKind(E->getType()));
659   }
660   else if (const ImplicitParamDecl *IPD =
661       dyn_cast<ImplicitParamDecl>(E->getDecl())) {
662     llvm::Value *V = LocalDeclMap[IPD];
663     assert(V && "BlockVarDecl not entered in LocalDeclMap?");
664     return LValue::MakeAddr(V, E->getType().getCVRQualifiers(),
665                             getContext().getObjCGCAttrKind(E->getType()));
666   }
667   assert(0 && "Unimp declref");
668   //an invalid LValue, but the assert will
669   //ensure that this point is never reached.
670   return LValue();
671 }
672 
673 LValue CodeGenFunction::EmitBlockDeclRefLValue(const BlockDeclRefExpr *E) {
674   return LValue::MakeAddr(GetAddrOfBlockDecl(E), 0);
675 }
676 
677 LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
678   // __extension__ doesn't affect lvalue-ness.
679   if (E->getOpcode() == UnaryOperator::Extension)
680     return EmitLValue(E->getSubExpr());
681 
682   QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
683   switch (E->getOpcode()) {
684   default: assert(0 && "Unknown unary operator lvalue!");
685   case UnaryOperator::Deref:
686     {
687       QualType T =
688         E->getSubExpr()->getType()->getAsPointerType()->getPointeeType();
689       LValue LV = LValue::MakeAddr(EmitScalarExpr(E->getSubExpr()),
690                                    ExprTy->getAsPointerType()->getPointeeType()
691                                       .getCVRQualifiers(),
692                                    getContext().getObjCGCAttrKind(T));
693      // We should not generate __weak write barrier on indirect reference
694      // of a pointer to object; as in void foo (__weak id *param); *param = 0;
695      // But, we continue to generate __strong write barrier on indirect write
696      // into a pointer to object.
697      if (getContext().getLangOptions().ObjC1 &&
698          getContext().getLangOptions().getGCMode() != LangOptions::NonGC &&
699          LV.isObjCWeak())
700        LValue::SetObjCNonGC(LV, !E->isOBJCGCCandidate());
701      return LV;
702     }
703   case UnaryOperator::Real:
704   case UnaryOperator::Imag:
705     LValue LV = EmitLValue(E->getSubExpr());
706     unsigned Idx = E->getOpcode() == UnaryOperator::Imag;
707     return LValue::MakeAddr(Builder.CreateStructGEP(LV.getAddress(),
708                                                     Idx, "idx"),
709                             ExprTy.getCVRQualifiers());
710   }
711 }
712 
713 LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
714   return LValue::MakeAddr(CGM.GetAddrOfConstantStringFromLiteral(E), 0);
715 }
716 
717 LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
718   return LValue::MakeAddr(CGM.GetAddrOfConstantStringFromObjCEncode(E), 0);
719 }
720 
721 
722 LValue CodeGenFunction::EmitPredefinedFunctionName(unsigned Type) {
723   std::string GlobalVarName;
724 
725   switch (Type) {
726   default:
727     assert(0 && "Invalid type");
728   case PredefinedExpr::Func:
729     GlobalVarName = "__func__.";
730     break;
731   case PredefinedExpr::Function:
732     GlobalVarName = "__FUNCTION__.";
733     break;
734   case PredefinedExpr::PrettyFunction:
735     // FIXME:: Demangle C++ method names
736     GlobalVarName = "__PRETTY_FUNCTION__.";
737     break;
738   }
739 
740   std::string FunctionName;
741   if(const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurFuncDecl)) {
742     FunctionName = CGM.getMangledName(FD);
743   } else {
744     // Just get the mangled name.
745     FunctionName = CurFn->getName();
746   }
747 
748   GlobalVarName += FunctionName;
749   llvm::Constant *C =
750     CGM.GetAddrOfConstantCString(FunctionName, GlobalVarName.c_str());
751   return LValue::MakeAddr(C, 0);
752 }
753 
754 LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
755   switch (E->getIdentType()) {
756   default:
757     return EmitUnsupportedLValue(E, "predefined expression");
758   case PredefinedExpr::Func:
759   case PredefinedExpr::Function:
760   case PredefinedExpr::PrettyFunction:
761     return EmitPredefinedFunctionName(E->getIdentType());
762   }
763 }
764 
765 LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
766   // The index must always be an integer, which is not an aggregate.  Emit it.
767   llvm::Value *Idx = EmitScalarExpr(E->getIdx());
768 
769   // If the base is a vector type, then we are forming a vector element lvalue
770   // with this subscript.
771   if (E->getBase()->getType()->isVectorType()) {
772     // Emit the vector as an lvalue to get its address.
773     LValue LHS = EmitLValue(E->getBase());
774     assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
775     // FIXME: This should properly sign/zero/extend or truncate Idx to i32.
776     return LValue::MakeVectorElt(LHS.getAddress(), Idx,
777       E->getBase()->getType().getCVRQualifiers());
778   }
779 
780   // The base must be a pointer, which is not an aggregate.  Emit it.
781   llvm::Value *Base = EmitScalarExpr(E->getBase());
782 
783   // Extend or truncate the index type to 32 or 64-bits.
784   QualType IdxTy  = E->getIdx()->getType();
785   bool IdxSigned = IdxTy->isSignedIntegerType();
786   unsigned IdxBitwidth = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
787   if (IdxBitwidth != LLVMPointerWidth)
788     Idx = Builder.CreateIntCast(Idx, llvm::IntegerType::get(LLVMPointerWidth),
789                                 IdxSigned, "idxprom");
790 
791   // We know that the pointer points to a type of the correct size, unless the
792   // size is a VLA.
793   if (const VariableArrayType *VAT =
794         getContext().getAsVariableArrayType(E->getType())) {
795     llvm::Value *VLASize = VLASizeMap[VAT];
796 
797     Idx = Builder.CreateMul(Idx, VLASize);
798 
799     QualType BaseType = getContext().getBaseElementType(VAT);
800 
801     uint64_t BaseTypeSize = getContext().getTypeSize(BaseType) / 8;
802     Idx = Builder.CreateUDiv(Idx,
803                              llvm::ConstantInt::get(Idx->getType(),
804                                                     BaseTypeSize));
805   }
806 
807   QualType T = E->getBase()->getType();
808   QualType ExprTy = getContext().getCanonicalType(T);
809   T = T->getAsPointerType()->getPointeeType();
810   LValue LV =
811            LValue::MakeAddr(Builder.CreateGEP(Base, Idx, "arrayidx"),
812            ExprTy->getAsPointerType()->getPointeeType().getCVRQualifiers(),
813            getContext().getObjCGCAttrKind(T));
814   if (getContext().getLangOptions().ObjC1 &&
815       getContext().getLangOptions().getGCMode() != LangOptions::NonGC)
816     LValue::SetObjCNonGC(LV, !E->isOBJCGCCandidate());
817   return LV;
818 }
819 
820 static
821 llvm::Constant *GenerateConstantVector(llvm::SmallVector<unsigned, 4> &Elts) {
822   llvm::SmallVector<llvm::Constant *, 4> CElts;
823 
824   for (unsigned i = 0, e = Elts.size(); i != e; ++i)
825     CElts.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, Elts[i]));
826 
827   return llvm::ConstantVector::get(&CElts[0], CElts.size());
828 }
829 
830 LValue CodeGenFunction::
831 EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
832   // Emit the base vector as an l-value.
833   LValue Base;
834 
835   // ExtVectorElementExpr's base can either be a vector or pointer to vector.
836   if (!E->isArrow()) {
837     assert(E->getBase()->getType()->isVectorType());
838     Base = EmitLValue(E->getBase());
839   } else {
840     const PointerType *PT = E->getBase()->getType()->getAsPointerType();
841     llvm::Value *Ptr = EmitScalarExpr(E->getBase());
842     Base = LValue::MakeAddr(Ptr, PT->getPointeeType().getCVRQualifiers());
843   }
844 
845   // Encode the element access list into a vector of unsigned indices.
846   llvm::SmallVector<unsigned, 4> Indices;
847   E->getEncodedElementAccess(Indices);
848 
849   if (Base.isSimple()) {
850     llvm::Constant *CV = GenerateConstantVector(Indices);
851     return LValue::MakeExtVectorElt(Base.getAddress(), CV,
852                                     Base.getQualifiers());
853   }
854   assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
855 
856   llvm::Constant *BaseElts = Base.getExtVectorElts();
857   llvm::SmallVector<llvm::Constant *, 4> CElts;
858 
859   for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
860     if (isa<llvm::ConstantAggregateZero>(BaseElts))
861       CElts.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
862     else
863       CElts.push_back(BaseElts->getOperand(Indices[i]));
864   }
865   llvm::Constant *CV = llvm::ConstantVector::get(&CElts[0], CElts.size());
866   return LValue::MakeExtVectorElt(Base.getExtVectorAddr(), CV,
867                                   Base.getQualifiers());
868 }
869 
870 LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
871   bool isUnion = false;
872   bool isIvar = false;
873   bool isNonGC = false;
874   Expr *BaseExpr = E->getBase();
875   llvm::Value *BaseValue = NULL;
876   unsigned CVRQualifiers=0;
877 
878   // If this is s.x, emit s as an lvalue.  If it is s->x, emit s as a scalar.
879   if (E->isArrow()) {
880     BaseValue = EmitScalarExpr(BaseExpr);
881     const PointerType *PTy =
882       cast<PointerType>(getContext().getCanonicalType(BaseExpr->getType()));
883     if (PTy->getPointeeType()->isUnionType())
884       isUnion = true;
885     CVRQualifiers = PTy->getPointeeType().getCVRQualifiers();
886   } else if (isa<ObjCPropertyRefExpr>(BaseExpr) ||
887              isa<ObjCKVCRefExpr>(BaseExpr)) {
888     RValue RV = EmitObjCPropertyGet(BaseExpr);
889     BaseValue = RV.getAggregateAddr();
890     if (BaseExpr->getType()->isUnionType())
891       isUnion = true;
892     CVRQualifiers = BaseExpr->getType().getCVRQualifiers();
893   } else {
894     LValue BaseLV = EmitLValue(BaseExpr);
895     if (BaseLV.isObjCIvar())
896       isIvar = true;
897     if (BaseLV.isNonGC())
898       isNonGC = true;
899     // FIXME: this isn't right for bitfields.
900     BaseValue = BaseLV.getAddress();
901     if (BaseExpr->getType()->isUnionType())
902       isUnion = true;
903     CVRQualifiers = BaseExpr->getType().getCVRQualifiers();
904   }
905 
906   FieldDecl *Field = dyn_cast<FieldDecl>(E->getMemberDecl());
907   // FIXME: Handle non-field member expressions
908   assert(Field && "No code generation for non-field member references");
909   LValue MemExpLV = EmitLValueForField(BaseValue, Field, isUnion,
910                                        CVRQualifiers);
911   LValue::SetObjCIvar(MemExpLV, isIvar);
912   LValue::SetObjCNonGC(MemExpLV, isNonGC);
913   return MemExpLV;
914 }
915 
916 LValue CodeGenFunction::EmitLValueForBitfield(llvm::Value* BaseValue,
917                                               FieldDecl* Field,
918                                               unsigned CVRQualifiers) {
919    unsigned idx = CGM.getTypes().getLLVMFieldNo(Field);
920   // FIXME: CodeGenTypes should expose a method to get the appropriate
921   // type for FieldTy (the appropriate type is ABI-dependent).
922   const llvm::Type *FieldTy =
923     CGM.getTypes().ConvertTypeForMem(Field->getType());
924   const llvm::PointerType *BaseTy =
925   cast<llvm::PointerType>(BaseValue->getType());
926   unsigned AS = BaseTy->getAddressSpace();
927   BaseValue = Builder.CreateBitCast(BaseValue,
928                                     llvm::PointerType::get(FieldTy, AS),
929                                     "tmp");
930   llvm::Value *V = Builder.CreateGEP(BaseValue,
931                               llvm::ConstantInt::get(llvm::Type::Int32Ty, idx),
932                               "tmp");
933 
934   CodeGenTypes::BitFieldInfo bitFieldInfo =
935     CGM.getTypes().getBitFieldInfo(Field);
936   return LValue::MakeBitfield(V, bitFieldInfo.Begin, bitFieldInfo.Size,
937                               Field->getType()->isSignedIntegerType(),
938                             Field->getType().getCVRQualifiers()|CVRQualifiers);
939 }
940 
941 LValue CodeGenFunction::EmitLValueForField(llvm::Value* BaseValue,
942                                            FieldDecl* Field,
943                                            bool isUnion,
944                                            unsigned CVRQualifiers)
945 {
946   if (Field->isBitField())
947     return EmitLValueForBitfield(BaseValue, Field, CVRQualifiers);
948 
949   unsigned idx = CGM.getTypes().getLLVMFieldNo(Field);
950   llvm::Value *V = Builder.CreateStructGEP(BaseValue, idx, "tmp");
951 
952   // Match union field type.
953   if (isUnion) {
954     const llvm::Type *FieldTy =
955       CGM.getTypes().ConvertTypeForMem(Field->getType());
956     const llvm::PointerType * BaseTy =
957       cast<llvm::PointerType>(BaseValue->getType());
958     unsigned AS = BaseTy->getAddressSpace();
959     V = Builder.CreateBitCast(V,
960                               llvm::PointerType::get(FieldTy, AS),
961                               "tmp");
962   }
963 
964   QualType::GCAttrTypes attr = QualType::GCNone;
965   if (CGM.getLangOptions().ObjC1 &&
966       CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
967     QualType Ty = Field->getType();
968     attr = Ty.getObjCGCAttr();
969     if (attr != QualType::GCNone) {
970       // __weak attribute on a field is ignored.
971       if (attr == QualType::Weak)
972         attr = QualType::GCNone;
973     }
974     else if (getContext().isObjCObjectPointerType(Ty))
975       attr = QualType::Strong;
976   }
977   LValue LV =
978     LValue::MakeAddr(V,
979                      Field->getType().getCVRQualifiers()|CVRQualifiers,
980                      attr);
981   return LV;
982 }
983 
984 LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr* E)
985 {
986   const llvm::Type *LTy = ConvertType(E->getType());
987   llvm::Value *DeclPtr = CreateTempAlloca(LTy, ".compoundliteral");
988 
989   const Expr* InitExpr = E->getInitializer();
990   LValue Result = LValue::MakeAddr(DeclPtr, E->getType().getCVRQualifiers());
991 
992   if (E->getType()->isComplexType()) {
993     EmitComplexExprIntoAddr(InitExpr, DeclPtr, false);
994   } else if (hasAggregateLLVMType(E->getType())) {
995     EmitAnyExpr(InitExpr, DeclPtr, false);
996   } else {
997     EmitStoreThroughLValue(EmitAnyExpr(InitExpr), Result, E->getType());
998   }
999 
1000   return Result;
1001 }
1002 
1003 //===--------------------------------------------------------------------===//
1004 //                             Expression Emission
1005 //===--------------------------------------------------------------------===//
1006 
1007 
1008 RValue CodeGenFunction::EmitCallExpr(const CallExpr *E) {
1009   // Builtins never have block type.
1010   if (E->getCallee()->getType()->isBlockPointerType())
1011     return EmitBlockCallExpr(E);
1012 
1013   const Decl *TargetDecl = 0;
1014   if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E->getCallee())) {
1015     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1016       TargetDecl = DRE->getDecl();
1017       if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(TargetDecl))
1018         if (unsigned builtinID = FD->getBuiltinID(getContext()))
1019           return EmitBuiltinExpr(FD, builtinID, E);
1020     }
1021   }
1022 
1023   llvm::Value *Callee = EmitScalarExpr(E->getCallee());
1024   return EmitCallExpr(Callee, E->getCallee()->getType(),
1025                       E->arg_begin(), E->arg_end(), TargetDecl);
1026 }
1027 
1028 LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
1029   // Can only get l-value for binary operator expressions which are a
1030   // simple assignment of aggregate type.
1031   if (E->getOpcode() != BinaryOperator::Assign)
1032     return EmitUnsupportedLValue(E, "binary l-value expression");
1033 
1034   llvm::Value *Temp = CreateTempAlloca(ConvertType(E->getType()));
1035   EmitAggExpr(E, Temp, false);
1036   // FIXME: Are these qualifiers correct?
1037   return LValue::MakeAddr(Temp, E->getType().getCVRQualifiers(),
1038                           getContext().getObjCGCAttrKind(E->getType()));
1039 }
1040 
1041 LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
1042   // Can only get l-value for call expression returning aggregate type
1043   RValue RV = EmitCallExpr(E);
1044   return LValue::MakeAddr(RV.getAggregateAddr(),
1045                           E->getType().getCVRQualifiers(),
1046                           getContext().getObjCGCAttrKind(E->getType()));
1047 }
1048 
1049 LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
1050   // FIXME: This shouldn't require another copy.
1051   llvm::Value *Temp = CreateTempAlloca(ConvertType(E->getType()));
1052   EmitAggExpr(E, Temp, false);
1053   return LValue::MakeAddr(Temp, E->getType().getCVRQualifiers());
1054 }
1055 
1056 LValue
1057 CodeGenFunction::EmitCXXConditionDeclLValue(const CXXConditionDeclExpr *E) {
1058   EmitLocalBlockVarDecl(*E->getVarDecl());
1059   return EmitDeclRefLValue(E);
1060 }
1061 
1062 LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
1063   // Can only get l-value for message expression returning aggregate type
1064   RValue RV = EmitObjCMessageExpr(E);
1065   // FIXME: can this be volatile?
1066   return LValue::MakeAddr(RV.getAggregateAddr(),
1067                           E->getType().getCVRQualifiers(),
1068                           getContext().getObjCGCAttrKind(E->getType()));
1069 }
1070 
1071 llvm::Value *CodeGenFunction::EmitIvarOffset(ObjCInterfaceDecl *Interface,
1072                                              const ObjCIvarDecl *Ivar) {
1073   // Objective-C objects are traditionally C structures with their layout
1074   // defined at compile-time.  In some implementations, their layout is not
1075   // defined until run time in order to allow instance variables to be added to
1076   // a class without recompiling all of the subclasses.  If this is the case
1077   // then the CGObjCRuntime subclass must return true to LateBoundIvars and
1078   // implement the lookup itself.
1079   if (CGM.getObjCRuntime().LateBoundIVars())
1080     assert(0 && "late-bound ivars are unsupported");
1081   return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
1082 }
1083 
1084 LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
1085                                           llvm::Value *BaseValue,
1086                                           const ObjCIvarDecl *Ivar,
1087                                           const FieldDecl *Field,
1088                                           unsigned CVRQualifiers) {
1089   // See comment in EmitIvarOffset.
1090   if (CGM.getObjCRuntime().LateBoundIVars())
1091     assert(0 && "late-bound ivars are unsupported");
1092 
1093   LValue LV = CGM.getObjCRuntime().EmitObjCValueForIvar(*this,
1094                                                         ObjectTy,
1095                                                         BaseValue, Ivar, Field,
1096                                                         CVRQualifiers);
1097   return LV;
1098 }
1099 
1100 LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
1101   // FIXME: A lot of the code below could be shared with EmitMemberExpr.
1102   llvm::Value *BaseValue = 0;
1103   const Expr *BaseExpr = E->getBase();
1104   unsigned CVRQualifiers = 0;
1105   QualType ObjectTy;
1106   if (E->isArrow()) {
1107     BaseValue = EmitScalarExpr(BaseExpr);
1108     const PointerType *PTy =
1109       cast<PointerType>(getContext().getCanonicalType(BaseExpr->getType()));
1110     ObjectTy = PTy->getPointeeType();
1111     CVRQualifiers = ObjectTy.getCVRQualifiers();
1112   } else {
1113     LValue BaseLV = EmitLValue(BaseExpr);
1114     // FIXME: this isn't right for bitfields.
1115     BaseValue = BaseLV.getAddress();
1116     ObjectTy = BaseExpr->getType();
1117     CVRQualifiers = ObjectTy.getCVRQualifiers();
1118   }
1119 
1120   return EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
1121                            getContext().getFieldDecl(E), CVRQualifiers);
1122 }
1123 
1124 LValue
1125 CodeGenFunction::EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E) {
1126   // This is a special l-value that just issues sends when we load or
1127   // store through it.
1128   return LValue::MakePropertyRef(E, E->getType().getCVRQualifiers());
1129 }
1130 
1131 LValue
1132 CodeGenFunction::EmitObjCKVCRefLValue(const ObjCKVCRefExpr *E) {
1133   // This is a special l-value that just issues sends when we load or
1134   // store through it.
1135   return LValue::MakeKVCRef(E, E->getType().getCVRQualifiers());
1136 }
1137 
1138 LValue
1139 CodeGenFunction::EmitObjCSuperExpr(const ObjCSuperExpr *E) {
1140   return EmitUnsupportedLValue(E, "use of super");
1141 }
1142 
1143 RValue CodeGenFunction::EmitCallExpr(llvm::Value *Callee, QualType CalleeType,
1144                                      CallExpr::const_arg_iterator ArgBeg,
1145                                      CallExpr::const_arg_iterator ArgEnd,
1146                                      const Decl *TargetDecl) {
1147   // Get the actual function type. The callee type will always be a
1148   // pointer to function type or a block pointer type.
1149   QualType ResultType;
1150   if (const BlockPointerType *BPT = dyn_cast<BlockPointerType>(CalleeType)) {
1151     ResultType = BPT->getPointeeType()->getAsFunctionType()->getResultType();
1152   } else {
1153     assert(CalleeType->isFunctionPointerType() &&
1154            "Call must have function pointer type!");
1155     QualType FnType = CalleeType->getAsPointerType()->getPointeeType();
1156     ResultType = FnType->getAsFunctionType()->getResultType();
1157   }
1158 
1159   CallArgList Args;
1160   for (CallExpr::const_arg_iterator I = ArgBeg; I != ArgEnd; ++I)
1161     Args.push_back(std::make_pair(EmitAnyExprToTemp(*I),
1162                                   I->getType()));
1163 
1164   return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args),
1165                   Callee, Args, TargetDecl);
1166 }
1167