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 "CGCXXABI.h"
18 #include "CGRecordLayout.h"
19 #include "CGObjCRuntime.h"
20 #include "clang/AST/ASTContext.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "llvm/Intrinsics.h"
23 #include "clang/Frontend/CodeGenOptions.h"
24 #include "llvm/Target/TargetData.h"
25 using namespace clang;
26 using namespace CodeGen;
27 
28 //===--------------------------------------------------------------------===//
29 //                        Miscellaneous Helper Methods
30 //===--------------------------------------------------------------------===//
31 
32 /// CreateTempAlloca - This creates a alloca and inserts it into the entry
33 /// block.
34 llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(const llvm::Type *Ty,
35                                                     const llvm::Twine &Name) {
36   if (!Builder.isNamePreserving())
37     return new llvm::AllocaInst(Ty, 0, "", AllocaInsertPt);
38   return new llvm::AllocaInst(Ty, 0, Name, AllocaInsertPt);
39 }
40 
41 void CodeGenFunction::InitTempAlloca(llvm::AllocaInst *Var,
42                                      llvm::Value *Init) {
43   llvm::StoreInst *Store = new llvm::StoreInst(Init, Var);
44   llvm::BasicBlock *Block = AllocaInsertPt->getParent();
45   Block->getInstList().insertAfter(&*AllocaInsertPt, Store);
46 }
47 
48 llvm::AllocaInst *CodeGenFunction::CreateIRTemp(QualType Ty,
49                                                 const llvm::Twine &Name) {
50   llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertType(Ty), Name);
51   // FIXME: Should we prefer the preferred type alignment here?
52   CharUnits Align = getContext().getTypeAlignInChars(Ty);
53   Alloc->setAlignment(Align.getQuantity());
54   return Alloc;
55 }
56 
57 llvm::AllocaInst *CodeGenFunction::CreateMemTemp(QualType Ty,
58                                                  const llvm::Twine &Name) {
59   llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty), Name);
60   // FIXME: Should we prefer the preferred type alignment here?
61   CharUnits Align = getContext().getTypeAlignInChars(Ty);
62   Alloc->setAlignment(Align.getQuantity());
63   return Alloc;
64 }
65 
66 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
67 /// expression and compare the result against zero, returning an Int1Ty value.
68 llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
69   if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
70     llvm::Value *MemPtr = EmitScalarExpr(E);
71     return CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
72   }
73 
74   QualType BoolTy = getContext().BoolTy;
75   if (!E->getType()->isAnyComplexType())
76     return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy);
77 
78   return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(),BoolTy);
79 }
80 
81 /// EmitAnyExpr - Emit code to compute the specified expression which
82 /// can have any type.  The result is returned as an RValue struct.
83 /// If this is an aggregate expression, AggSlot indicates where the
84 /// result should be returned.
85 RValue CodeGenFunction::EmitAnyExpr(const Expr *E, AggValueSlot AggSlot,
86                                     bool IgnoreResult) {
87   if (!hasAggregateLLVMType(E->getType()))
88     return RValue::get(EmitScalarExpr(E, IgnoreResult));
89   else if (E->getType()->isAnyComplexType())
90     return RValue::getComplex(EmitComplexExpr(E, false, false,
91                                               IgnoreResult, IgnoreResult));
92 
93   EmitAggExpr(E, AggSlot, IgnoreResult);
94   return AggSlot.asRValue();
95 }
96 
97 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
98 /// always be accessible even if no aggregate location is provided.
99 RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
100   AggValueSlot AggSlot = AggValueSlot::ignored();
101 
102   if (hasAggregateLLVMType(E->getType()) &&
103       !E->getType()->isAnyComplexType())
104     AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
105   return EmitAnyExpr(E, AggSlot);
106 }
107 
108 /// EmitAnyExprToMem - Evaluate an expression into a given memory
109 /// location.
110 void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
111                                        llvm::Value *Location,
112                                        bool IsLocationVolatile,
113                                        bool IsInit) {
114   if (E->getType()->isComplexType())
115     EmitComplexExprIntoAddr(E, Location, IsLocationVolatile);
116   else if (hasAggregateLLVMType(E->getType()))
117     EmitAggExpr(E, AggValueSlot::forAddr(Location, IsLocationVolatile, IsInit));
118   else {
119     RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
120     LValue LV = MakeAddrLValue(Location, E->getType());
121     EmitStoreThroughLValue(RV, LV, E->getType());
122   }
123 }
124 
125 /// \brief An adjustment to be made to the temporary created when emitting a
126 /// reference binding, which accesses a particular subobject of that temporary.
127 struct SubobjectAdjustment {
128   enum { DerivedToBaseAdjustment, FieldAdjustment } Kind;
129 
130   union {
131     struct {
132       const CastExpr *BasePath;
133       const CXXRecordDecl *DerivedClass;
134     } DerivedToBase;
135 
136     FieldDecl *Field;
137   };
138 
139   SubobjectAdjustment(const CastExpr *BasePath,
140                       const CXXRecordDecl *DerivedClass)
141     : Kind(DerivedToBaseAdjustment)
142   {
143     DerivedToBase.BasePath = BasePath;
144     DerivedToBase.DerivedClass = DerivedClass;
145   }
146 
147   SubobjectAdjustment(FieldDecl *Field)
148     : Kind(FieldAdjustment)
149   {
150     this->Field = Field;
151   }
152 };
153 
154 static llvm::Value *
155 CreateReferenceTemporary(CodeGenFunction& CGF, QualType Type,
156                          const NamedDecl *InitializedDecl) {
157   if (const VarDecl *VD = dyn_cast_or_null<VarDecl>(InitializedDecl)) {
158     if (VD->hasGlobalStorage()) {
159       llvm::SmallString<256> Name;
160       CGF.CGM.getCXXABI().getMangleContext().mangleReferenceTemporary(VD, Name);
161 
162       const llvm::Type *RefTempTy = CGF.ConvertTypeForMem(Type);
163 
164       // Create the reference temporary.
165       llvm::GlobalValue *RefTemp =
166         new llvm::GlobalVariable(CGF.CGM.getModule(),
167                                  RefTempTy, /*isConstant=*/false,
168                                  llvm::GlobalValue::InternalLinkage,
169                                  llvm::Constant::getNullValue(RefTempTy),
170                                  Name.str());
171       return RefTemp;
172     }
173   }
174 
175   return CGF.CreateMemTemp(Type, "ref.tmp");
176 }
177 
178 static llvm::Value *
179 EmitExprForReferenceBinding(CodeGenFunction &CGF, const Expr *E,
180                             llvm::Value *&ReferenceTemporary,
181                             const CXXDestructorDecl *&ReferenceTemporaryDtor,
182                             const NamedDecl *InitializedDecl) {
183   if (const CXXDefaultArgExpr *DAE = dyn_cast<CXXDefaultArgExpr>(E))
184     E = DAE->getExpr();
185 
186   if (const CXXExprWithTemporaries *TE = dyn_cast<CXXExprWithTemporaries>(E)) {
187     CodeGenFunction::RunCleanupsScope Scope(CGF);
188 
189     return EmitExprForReferenceBinding(CGF, TE->getSubExpr(),
190                                        ReferenceTemporary,
191                                        ReferenceTemporaryDtor,
192                                        InitializedDecl);
193   }
194 
195   RValue RV;
196   if (E->isLvalue(CGF.getContext()) == Expr::LV_Valid) {
197     // Emit the expression as an lvalue.
198     LValue LV = CGF.EmitLValue(E);
199     if (LV.isPropertyRef() || LV.isKVCRef()) {
200       QualType QT = E->getType();
201       RValue RV =
202         LV.isPropertyRef() ? CGF.EmitLoadOfPropertyRefLValue(LV, QT)
203                            : CGF.EmitLoadOfKVCRefLValue(LV, QT);
204       assert(RV.isScalar() && "EmitExprForReferenceBinding");
205       return RV.getScalarVal();
206     }
207 
208     if (LV.isSimple())
209       return LV.getAddress();
210 
211     // We have to load the lvalue.
212     RV = CGF.EmitLoadOfLValue(LV, E->getType());
213   } else {
214     QualType ResultTy = E->getType();
215 
216     llvm::SmallVector<SubobjectAdjustment, 2> Adjustments;
217     while (true) {
218       if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
219         E = PE->getSubExpr();
220         continue;
221       }
222 
223       if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
224         if ((CE->getCastKind() == CK_DerivedToBase ||
225              CE->getCastKind() == CK_UncheckedDerivedToBase) &&
226             E->getType()->isRecordType()) {
227           E = CE->getSubExpr();
228           CXXRecordDecl *Derived
229             = cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl());
230           Adjustments.push_back(SubobjectAdjustment(CE, Derived));
231           continue;
232         }
233 
234         if (CE->getCastKind() == CK_NoOp) {
235           E = CE->getSubExpr();
236           continue;
237         }
238       } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
239         if (ME->getBase()->isLvalue(CGF.getContext()) != Expr::LV_Valid &&
240             ME->getBase()->getType()->isRecordType()) {
241           if (FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
242             E = ME->getBase();
243             Adjustments.push_back(SubobjectAdjustment(Field));
244             continue;
245           }
246         }
247       }
248 
249       // Nothing changed.
250       break;
251     }
252 
253     // Create a reference temporary if necessary.
254     AggValueSlot AggSlot = AggValueSlot::ignored();
255     if (CGF.hasAggregateLLVMType(E->getType()) &&
256         !E->getType()->isAnyComplexType()) {
257       ReferenceTemporary = CreateReferenceTemporary(CGF, E->getType(),
258                                                     InitializedDecl);
259       AggSlot = AggValueSlot::forAddr(ReferenceTemporary, false,
260                                       InitializedDecl != 0);
261     }
262 
263     RV = CGF.EmitAnyExpr(E, AggSlot);
264 
265     if (InitializedDecl) {
266       // Get the destructor for the reference temporary.
267       if (const RecordType *RT = E->getType()->getAs<RecordType>()) {
268         CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
269         if (!ClassDecl->hasTrivialDestructor())
270           ReferenceTemporaryDtor = ClassDecl->getDestructor();
271       }
272     }
273 
274     // Check if need to perform derived-to-base casts and/or field accesses, to
275     // get from the temporary object we created (and, potentially, for which we
276     // extended the lifetime) to the subobject we're binding the reference to.
277     if (!Adjustments.empty()) {
278       llvm::Value *Object = RV.getAggregateAddr();
279       for (unsigned I = Adjustments.size(); I != 0; --I) {
280         SubobjectAdjustment &Adjustment = Adjustments[I-1];
281         switch (Adjustment.Kind) {
282         case SubobjectAdjustment::DerivedToBaseAdjustment:
283           Object =
284               CGF.GetAddressOfBaseClass(Object,
285                                         Adjustment.DerivedToBase.DerivedClass,
286                               Adjustment.DerivedToBase.BasePath->path_begin(),
287                               Adjustment.DerivedToBase.BasePath->path_end(),
288                                         /*NullCheckValue=*/false);
289           break;
290 
291         case SubobjectAdjustment::FieldAdjustment: {
292           LValue LV =
293             CGF.EmitLValueForField(Object, Adjustment.Field, 0);
294           if (LV.isSimple()) {
295             Object = LV.getAddress();
296             break;
297           }
298 
299           // For non-simple lvalues, we actually have to create a copy of
300           // the object we're binding to.
301           QualType T = Adjustment.Field->getType().getNonReferenceType()
302                                                   .getUnqualifiedType();
303           Object = CreateReferenceTemporary(CGF, T, InitializedDecl);
304           LValue TempLV = CGF.MakeAddrLValue(Object,
305                                              Adjustment.Field->getType());
306           CGF.EmitStoreThroughLValue(CGF.EmitLoadOfLValue(LV, T), TempLV, T);
307           break;
308         }
309 
310         }
311       }
312 
313       const llvm::Type *ResultPtrTy = CGF.ConvertType(ResultTy)->getPointerTo();
314       return CGF.Builder.CreateBitCast(Object, ResultPtrTy, "temp");
315     }
316   }
317 
318   if (RV.isAggregate())
319     return RV.getAggregateAddr();
320 
321   // Create a temporary variable that we can bind the reference to.
322   ReferenceTemporary = CreateReferenceTemporary(CGF, E->getType(),
323                                                 InitializedDecl);
324 
325 
326   unsigned Alignment =
327     CGF.getContext().getTypeAlignInChars(E->getType()).getQuantity();
328   if (RV.isScalar())
329     CGF.EmitStoreOfScalar(RV.getScalarVal(), ReferenceTemporary,
330                           /*Volatile=*/false, Alignment, E->getType());
331   else
332     CGF.StoreComplexToAddr(RV.getComplexVal(), ReferenceTemporary,
333                            /*Volatile=*/false);
334   return ReferenceTemporary;
335 }
336 
337 RValue
338 CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E,
339                                             const NamedDecl *InitializedDecl) {
340   llvm::Value *ReferenceTemporary = 0;
341   const CXXDestructorDecl *ReferenceTemporaryDtor = 0;
342   llvm::Value *Value = EmitExprForReferenceBinding(*this, E, ReferenceTemporary,
343                                                    ReferenceTemporaryDtor,
344                                                    InitializedDecl);
345   if (!ReferenceTemporaryDtor)
346     return RValue::get(Value);
347 
348   // Make sure to call the destructor for the reference temporary.
349   if (const VarDecl *VD = dyn_cast_or_null<VarDecl>(InitializedDecl)) {
350     if (VD->hasGlobalStorage()) {
351       llvm::Constant *DtorFn =
352         CGM.GetAddrOfCXXDestructor(ReferenceTemporaryDtor, Dtor_Complete);
353       CGF.EmitCXXGlobalDtorRegistration(DtorFn,
354                                       cast<llvm::Constant>(ReferenceTemporary));
355 
356       return RValue::get(Value);
357     }
358   }
359 
360   PushDestructorCleanup(ReferenceTemporaryDtor, ReferenceTemporary);
361 
362   return RValue::get(Value);
363 }
364 
365 
366 /// getAccessedFieldNo - Given an encoded value and a result number, return the
367 /// input field number being accessed.
368 unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
369                                              const llvm::Constant *Elts) {
370   if (isa<llvm::ConstantAggregateZero>(Elts))
371     return 0;
372 
373   return cast<llvm::ConstantInt>(Elts->getOperand(Idx))->getZExtValue();
374 }
375 
376 void CodeGenFunction::EmitCheck(llvm::Value *Address, unsigned Size) {
377   if (!CatchUndefined)
378     return;
379 
380   Address = Builder.CreateBitCast(Address, PtrToInt8Ty);
381 
382   const llvm::Type *IntPtrT = IntPtrTy;
383   llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, &IntPtrT, 1);
384   const llvm::IntegerType *Int1Ty = llvm::Type::getInt1Ty(VMContext);
385 
386   // In time, people may want to control this and use a 1 here.
387   llvm::Value *Arg = llvm::ConstantInt::get(Int1Ty, 0);
388   llvm::Value *C = Builder.CreateCall2(F, Address, Arg);
389   llvm::BasicBlock *Cont = createBasicBlock();
390   llvm::BasicBlock *Check = createBasicBlock();
391   llvm::Value *NegativeOne = llvm::ConstantInt::get(IntPtrTy, -1ULL);
392   Builder.CreateCondBr(Builder.CreateICmpEQ(C, NegativeOne), Cont, Check);
393 
394   EmitBlock(Check);
395   Builder.CreateCondBr(Builder.CreateICmpUGE(C,
396                                         llvm::ConstantInt::get(IntPtrTy, Size)),
397                        Cont, getTrapBB());
398   EmitBlock(Cont);
399 }
400 
401 
402 CodeGenFunction::ComplexPairTy CodeGenFunction::
403 EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
404                          bool isInc, bool isPre) {
405   ComplexPairTy InVal = LoadComplexFromAddr(LV.getAddress(),
406                                             LV.isVolatileQualified());
407 
408   llvm::Value *NextVal;
409   if (isa<llvm::IntegerType>(InVal.first->getType())) {
410     uint64_t AmountVal = isInc ? 1 : -1;
411     NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
412 
413     // Add the inc/dec to the real part.
414     NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
415   } else {
416     QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
417     llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
418     if (!isInc)
419       FVal.changeSign();
420     NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
421 
422     // Add the inc/dec to the real part.
423     NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
424   }
425 
426   ComplexPairTy IncVal(NextVal, InVal.second);
427 
428   // Store the updated result through the lvalue.
429   StoreComplexToAddr(IncVal, LV.getAddress(), LV.isVolatileQualified());
430 
431   // If this is a postinc, return the value read from memory, otherwise use the
432   // updated value.
433   return isPre ? IncVal : InVal;
434 }
435 
436 
437 //===----------------------------------------------------------------------===//
438 //                         LValue Expression Emission
439 //===----------------------------------------------------------------------===//
440 
441 RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
442   if (Ty->isVoidType())
443     return RValue::get(0);
444 
445   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
446     const llvm::Type *EltTy = ConvertType(CTy->getElementType());
447     llvm::Value *U = llvm::UndefValue::get(EltTy);
448     return RValue::getComplex(std::make_pair(U, U));
449   }
450 
451   // If this is a use of an undefined aggregate type, the aggregate must have an
452   // identifiable address.  Just because the contents of the value are undefined
453   // doesn't mean that the address can't be taken and compared.
454   if (hasAggregateLLVMType(Ty)) {
455     llvm::Value *DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
456     return RValue::getAggregate(DestPtr);
457   }
458 
459   return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
460 }
461 
462 RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
463                                               const char *Name) {
464   ErrorUnsupported(E, Name);
465   return GetUndefRValue(E->getType());
466 }
467 
468 LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
469                                               const char *Name) {
470   ErrorUnsupported(E, Name);
471   llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
472   return MakeAddrLValue(llvm::UndefValue::get(Ty), E->getType());
473 }
474 
475 LValue CodeGenFunction::EmitCheckedLValue(const Expr *E) {
476   LValue LV = EmitLValue(E);
477   if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple())
478     EmitCheck(LV.getAddress(), getContext().getTypeSize(E->getType()) / 8);
479   return LV;
480 }
481 
482 /// EmitLValue - Emit code to compute a designator that specifies the location
483 /// of the expression.
484 ///
485 /// This can return one of two things: a simple address or a bitfield reference.
486 /// In either case, the LLVM Value* in the LValue structure is guaranteed to be
487 /// an LLVM pointer type.
488 ///
489 /// If this returns a bitfield reference, nothing about the pointee type of the
490 /// LLVM value is known: For example, it may not be a pointer to an integer.
491 ///
492 /// If this returns a normal address, and if the lvalue's C type is fixed size,
493 /// this method guarantees that the returned pointer type will point to an LLVM
494 /// type of the same size of the lvalue's type.  If the lvalue has a variable
495 /// length type, this is not possible.
496 ///
497 LValue CodeGenFunction::EmitLValue(const Expr *E) {
498   llvm::DenseMap<const Expr *, LValue>::iterator I =
499                                       CGF.ConditionalSaveLValueExprs.find(E);
500   if (I != CGF.ConditionalSaveLValueExprs.end())
501     return I->second;
502 
503   switch (E->getStmtClass()) {
504   default: return EmitUnsupportedLValue(E, "l-value expression");
505 
506   case Expr::ObjCSelectorExprClass:
507   return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
508   case Expr::ObjCIsaExprClass:
509     return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
510   case Expr::BinaryOperatorClass:
511     return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
512   case Expr::CompoundAssignOperatorClass:
513     return EmitCompoundAssignOperatorLValue(cast<CompoundAssignOperator>(E));
514   case Expr::CallExprClass:
515   case Expr::CXXMemberCallExprClass:
516   case Expr::CXXOperatorCallExprClass:
517     return EmitCallExprLValue(cast<CallExpr>(E));
518   case Expr::VAArgExprClass:
519     return EmitVAArgExprLValue(cast<VAArgExpr>(E));
520   case Expr::DeclRefExprClass:
521     return EmitDeclRefLValue(cast<DeclRefExpr>(E));
522   case Expr::ParenExprClass:return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
523   case Expr::PredefinedExprClass:
524     return EmitPredefinedLValue(cast<PredefinedExpr>(E));
525   case Expr::StringLiteralClass:
526     return EmitStringLiteralLValue(cast<StringLiteral>(E));
527   case Expr::ObjCEncodeExprClass:
528     return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
529 
530   case Expr::BlockDeclRefExprClass:
531     return EmitBlockDeclRefLValue(cast<BlockDeclRefExpr>(E));
532 
533   case Expr::CXXTemporaryObjectExprClass:
534   case Expr::CXXConstructExprClass:
535     return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
536   case Expr::CXXBindTemporaryExprClass:
537     return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
538   case Expr::CXXExprWithTemporariesClass:
539     return EmitCXXExprWithTemporariesLValue(cast<CXXExprWithTemporaries>(E));
540   case Expr::CXXScalarValueInitExprClass:
541     return EmitNullInitializationLValue(cast<CXXScalarValueInitExpr>(E));
542   case Expr::CXXDefaultArgExprClass:
543     return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
544   case Expr::CXXTypeidExprClass:
545     return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
546 
547   case Expr::ObjCMessageExprClass:
548     return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
549   case Expr::ObjCIvarRefExprClass:
550     return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
551   case Expr::ObjCPropertyRefExprClass:
552     return EmitObjCPropertyRefLValue(cast<ObjCPropertyRefExpr>(E));
553   case Expr::ObjCImplicitSetterGetterRefExprClass:
554     return EmitObjCKVCRefLValue(cast<ObjCImplicitSetterGetterRefExpr>(E));
555   case Expr::StmtExprClass:
556     return EmitStmtExprLValue(cast<StmtExpr>(E));
557   case Expr::UnaryOperatorClass:
558     return EmitUnaryOpLValue(cast<UnaryOperator>(E));
559   case Expr::ArraySubscriptExprClass:
560     return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
561   case Expr::ExtVectorElementExprClass:
562     return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
563   case Expr::MemberExprClass:
564     return EmitMemberExpr(cast<MemberExpr>(E));
565   case Expr::CompoundLiteralExprClass:
566     return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
567   case Expr::ConditionalOperatorClass:
568     return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
569   case Expr::ChooseExprClass:
570     return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr(getContext()));
571   case Expr::ImplicitCastExprClass:
572   case Expr::CStyleCastExprClass:
573   case Expr::CXXFunctionalCastExprClass:
574   case Expr::CXXStaticCastExprClass:
575   case Expr::CXXDynamicCastExprClass:
576   case Expr::CXXReinterpretCastExprClass:
577   case Expr::CXXConstCastExprClass:
578     return EmitCastLValue(cast<CastExpr>(E));
579   }
580 }
581 
582 llvm::Value *CodeGenFunction::EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
583                                               unsigned Alignment, QualType Ty,
584                                               llvm::MDNode *TBAAInfo) {
585   llvm::LoadInst *Load = Builder.CreateLoad(Addr, "tmp");
586   if (Volatile)
587     Load->setVolatile(true);
588   if (Alignment)
589     Load->setAlignment(Alignment);
590   if (TBAAInfo)
591     CGM.DecorateInstruction(Load, TBAAInfo);
592 
593   return EmitFromMemory(Load, Ty);
594 }
595 
596 static bool isBooleanUnderlyingType(QualType Ty) {
597   if (const EnumType *ET = dyn_cast<EnumType>(Ty))
598     return ET->getDecl()->getIntegerType()->isBooleanType();
599   return false;
600 }
601 
602 llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
603   // Bool has a different representation in memory than in registers.
604   if (Ty->isBooleanType() || isBooleanUnderlyingType(Ty)) {
605     // This should really always be an i1, but sometimes it's already
606     // an i8, and it's awkward to track those cases down.
607     if (Value->getType()->isIntegerTy(1))
608       return Builder.CreateZExt(Value, Builder.getInt8Ty(), "frombool");
609     assert(Value->getType()->isIntegerTy(8) && "value rep of bool not i1/i8");
610   }
611 
612   return Value;
613 }
614 
615 llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
616   // Bool has a different representation in memory than in registers.
617   if (Ty->isBooleanType() || isBooleanUnderlyingType(Ty)) {
618     assert(Value->getType()->isIntegerTy(8) && "memory rep of bool not i8");
619     return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
620   }
621 
622   return Value;
623 }
624 
625 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
626                                         bool Volatile, unsigned Alignment,
627                                         QualType Ty,
628                                         llvm::MDNode *TBAAInfo) {
629   Value = EmitToMemory(Value, Ty);
630   llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
631   if (Alignment)
632     Store->setAlignment(Alignment);
633   if (TBAAInfo)
634     CGM.DecorateInstruction(Store, TBAAInfo);
635 }
636 
637 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
638 /// method emits the address of the lvalue, then loads the result as an rvalue,
639 /// returning the rvalue.
640 RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, QualType ExprType) {
641   if (LV.isObjCWeak()) {
642     // load of a __weak object.
643     llvm::Value *AddrWeakObj = LV.getAddress();
644     return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
645                                                              AddrWeakObj));
646   }
647 
648   if (LV.isSimple()) {
649     llvm::Value *Ptr = LV.getAddress();
650 
651     // Functions are l-values that don't require loading.
652     if (ExprType->isFunctionType())
653       return RValue::get(Ptr);
654 
655     // Everything needs a load.
656     return RValue::get(EmitLoadOfScalar(Ptr, LV.isVolatileQualified(),
657                                         LV.getAlignment(), ExprType,
658                                         LV.getTBAAInfo()));
659 
660   }
661 
662   if (LV.isVectorElt()) {
663     llvm::Value *Vec = Builder.CreateLoad(LV.getVectorAddr(),
664                                           LV.isVolatileQualified(), "tmp");
665     return RValue::get(Builder.CreateExtractElement(Vec, LV.getVectorIdx(),
666                                                     "vecext"));
667   }
668 
669   // If this is a reference to a subset of the elements of a vector, either
670   // shuffle the input or extract/insert them as appropriate.
671   if (LV.isExtVectorElt())
672     return EmitLoadOfExtVectorElementLValue(LV, ExprType);
673 
674   if (LV.isBitField())
675     return EmitLoadOfBitfieldLValue(LV, ExprType);
676 
677   if (LV.isPropertyRef())
678     return EmitLoadOfPropertyRefLValue(LV, ExprType);
679 
680   assert(LV.isKVCRef() && "Unknown LValue type!");
681   return EmitLoadOfKVCRefLValue(LV, ExprType);
682 }
683 
684 RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
685                                                  QualType ExprType) {
686   const CGBitFieldInfo &Info = LV.getBitFieldInfo();
687 
688   // Get the output type.
689   const llvm::Type *ResLTy = ConvertType(ExprType);
690   unsigned ResSizeInBits = CGM.getTargetData().getTypeSizeInBits(ResLTy);
691 
692   // Compute the result as an OR of all of the individual component accesses.
693   llvm::Value *Res = 0;
694   for (unsigned i = 0, e = Info.getNumComponents(); i != e; ++i) {
695     const CGBitFieldInfo::AccessInfo &AI = Info.getComponent(i);
696 
697     // Get the field pointer.
698     llvm::Value *Ptr = LV.getBitFieldBaseAddr();
699 
700     // Only offset by the field index if used, so that incoming values are not
701     // required to be structures.
702     if (AI.FieldIndex)
703       Ptr = Builder.CreateStructGEP(Ptr, AI.FieldIndex, "bf.field");
704 
705     // Offset by the byte offset, if used.
706     if (AI.FieldByteOffset) {
707       const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext);
708       Ptr = Builder.CreateBitCast(Ptr, i8PTy);
709       Ptr = Builder.CreateConstGEP1_32(Ptr, AI.FieldByteOffset,"bf.field.offs");
710     }
711 
712     // Cast to the access type.
713     const llvm::Type *PTy = llvm::Type::getIntNPtrTy(VMContext, AI.AccessWidth,
714                                                     ExprType.getAddressSpace());
715     Ptr = Builder.CreateBitCast(Ptr, PTy);
716 
717     // Perform the load.
718     llvm::LoadInst *Load = Builder.CreateLoad(Ptr, LV.isVolatileQualified());
719     if (AI.AccessAlignment)
720       Load->setAlignment(AI.AccessAlignment);
721 
722     // Shift out unused low bits and mask out unused high bits.
723     llvm::Value *Val = Load;
724     if (AI.FieldBitStart)
725       Val = Builder.CreateLShr(Load, AI.FieldBitStart);
726     Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(AI.AccessWidth,
727                                                             AI.TargetBitWidth),
728                             "bf.clear");
729 
730     // Extend or truncate to the target size.
731     if (AI.AccessWidth < ResSizeInBits)
732       Val = Builder.CreateZExt(Val, ResLTy);
733     else if (AI.AccessWidth > ResSizeInBits)
734       Val = Builder.CreateTrunc(Val, ResLTy);
735 
736     // Shift into place, and OR into the result.
737     if (AI.TargetBitOffset)
738       Val = Builder.CreateShl(Val, AI.TargetBitOffset);
739     Res = Res ? Builder.CreateOr(Res, Val) : Val;
740   }
741 
742   // If the bit-field is signed, perform the sign-extension.
743   //
744   // FIXME: This can easily be folded into the load of the high bits, which
745   // could also eliminate the mask of high bits in some situations.
746   if (Info.isSigned()) {
747     unsigned ExtraBits = ResSizeInBits - Info.getSize();
748     if (ExtraBits)
749       Res = Builder.CreateAShr(Builder.CreateShl(Res, ExtraBits),
750                                ExtraBits, "bf.val.sext");
751   }
752 
753   return RValue::get(Res);
754 }
755 
756 RValue CodeGenFunction::EmitLoadOfPropertyRefLValue(LValue LV,
757                                                     QualType ExprType) {
758   return EmitObjCPropertyGet(LV.getPropertyRefExpr());
759 }
760 
761 RValue CodeGenFunction::EmitLoadOfKVCRefLValue(LValue LV,
762                                                QualType ExprType) {
763   return EmitObjCPropertyGet(LV.getKVCRefExpr());
764 }
765 
766 // If this is a reference to a subset of the elements of a vector, create an
767 // appropriate shufflevector.
768 RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV,
769                                                          QualType ExprType) {
770   llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddr(),
771                                         LV.isVolatileQualified(), "tmp");
772 
773   const llvm::Constant *Elts = LV.getExtVectorElts();
774 
775   // If the result of the expression is a non-vector type, we must be extracting
776   // a single element.  Just codegen as an extractelement.
777   const VectorType *ExprVT = ExprType->getAs<VectorType>();
778   if (!ExprVT) {
779     unsigned InIdx = getAccessedFieldNo(0, Elts);
780     llvm::Value *Elt = llvm::ConstantInt::get(Int32Ty, InIdx);
781     return RValue::get(Builder.CreateExtractElement(Vec, Elt, "tmp"));
782   }
783 
784   // Always use shuffle vector to try to retain the original program structure
785   unsigned NumResultElts = ExprVT->getNumElements();
786 
787   llvm::SmallVector<llvm::Constant*, 4> Mask;
788   for (unsigned i = 0; i != NumResultElts; ++i) {
789     unsigned InIdx = getAccessedFieldNo(i, Elts);
790     Mask.push_back(llvm::ConstantInt::get(Int32Ty, InIdx));
791   }
792 
793   llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size());
794   Vec = Builder.CreateShuffleVector(Vec,
795                                     llvm::UndefValue::get(Vec->getType()),
796                                     MaskV, "tmp");
797   return RValue::get(Vec);
798 }
799 
800 
801 
802 /// EmitStoreThroughLValue - Store the specified rvalue into the specified
803 /// lvalue, where both are guaranteed to the have the same type, and that type
804 /// is 'Ty'.
805 void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
806                                              QualType Ty) {
807   if (!Dst.isSimple()) {
808     if (Dst.isVectorElt()) {
809       // Read/modify/write the vector, inserting the new element.
810       llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddr(),
811                                             Dst.isVolatileQualified(), "tmp");
812       Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
813                                         Dst.getVectorIdx(), "vecins");
814       Builder.CreateStore(Vec, Dst.getVectorAddr(),Dst.isVolatileQualified());
815       return;
816     }
817 
818     // If this is an update of extended vector elements, insert them as
819     // appropriate.
820     if (Dst.isExtVectorElt())
821       return EmitStoreThroughExtVectorComponentLValue(Src, Dst, Ty);
822 
823     if (Dst.isBitField())
824       return EmitStoreThroughBitfieldLValue(Src, Dst, Ty);
825 
826     if (Dst.isPropertyRef())
827       return EmitStoreThroughPropertyRefLValue(Src, Dst, Ty);
828 
829     assert(Dst.isKVCRef() && "Unknown LValue type");
830     return EmitStoreThroughKVCRefLValue(Src, Dst, Ty);
831   }
832 
833   if (Dst.isObjCWeak() && !Dst.isNonGC()) {
834     // load of a __weak object.
835     llvm::Value *LvalueDst = Dst.getAddress();
836     llvm::Value *src = Src.getScalarVal();
837      CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
838     return;
839   }
840 
841   if (Dst.isObjCStrong() && !Dst.isNonGC()) {
842     // load of a __strong object.
843     llvm::Value *LvalueDst = Dst.getAddress();
844     llvm::Value *src = Src.getScalarVal();
845     if (Dst.isObjCIvar()) {
846       assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
847       const llvm::Type *ResultType = ConvertType(getContext().LongTy);
848       llvm::Value *RHS = EmitScalarExpr(Dst.getBaseIvarExp());
849       llvm::Value *dst = RHS;
850       RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
851       llvm::Value *LHS =
852         Builder.CreatePtrToInt(LvalueDst, ResultType, "sub.ptr.lhs.cast");
853       llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
854       CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
855                                               BytesBetween);
856     } else if (Dst.isGlobalObjCRef()) {
857       CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
858                                                 Dst.isThreadLocalRef());
859     }
860     else
861       CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
862     return;
863   }
864 
865   assert(Src.isScalar() && "Can't emit an agg store with this method");
866   EmitStoreOfScalar(Src.getScalarVal(), Dst.getAddress(),
867                     Dst.isVolatileQualified(), Dst.getAlignment(), Ty,
868                     Dst.getTBAAInfo());
869 }
870 
871 void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
872                                                      QualType Ty,
873                                                      llvm::Value **Result) {
874   const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
875 
876   // Get the output type.
877   const llvm::Type *ResLTy = ConvertTypeForMem(Ty);
878   unsigned ResSizeInBits = CGM.getTargetData().getTypeSizeInBits(ResLTy);
879 
880   // Get the source value, truncated to the width of the bit-field.
881   llvm::Value *SrcVal = Src.getScalarVal();
882 
883   if (Ty->isBooleanType())
884     SrcVal = Builder.CreateIntCast(SrcVal, ResLTy, /*IsSigned=*/false);
885 
886   SrcVal = Builder.CreateAnd(SrcVal, llvm::APInt::getLowBitsSet(ResSizeInBits,
887                                                                 Info.getSize()),
888                              "bf.value");
889 
890   // Return the new value of the bit-field, if requested.
891   if (Result) {
892     // Cast back to the proper type for result.
893     const llvm::Type *SrcTy = Src.getScalarVal()->getType();
894     llvm::Value *ReloadVal = Builder.CreateIntCast(SrcVal, SrcTy, false,
895                                                    "bf.reload.val");
896 
897     // Sign extend if necessary.
898     if (Info.isSigned()) {
899       unsigned ExtraBits = ResSizeInBits - Info.getSize();
900       if (ExtraBits)
901         ReloadVal = Builder.CreateAShr(Builder.CreateShl(ReloadVal, ExtraBits),
902                                        ExtraBits, "bf.reload.sext");
903     }
904 
905     *Result = ReloadVal;
906   }
907 
908   // Iterate over the components, writing each piece to memory.
909   for (unsigned i = 0, e = Info.getNumComponents(); i != e; ++i) {
910     const CGBitFieldInfo::AccessInfo &AI = Info.getComponent(i);
911 
912     // Get the field pointer.
913     llvm::Value *Ptr = Dst.getBitFieldBaseAddr();
914 
915     // Only offset by the field index if used, so that incoming values are not
916     // required to be structures.
917     if (AI.FieldIndex)
918       Ptr = Builder.CreateStructGEP(Ptr, AI.FieldIndex, "bf.field");
919 
920     // Offset by the byte offset, if used.
921     if (AI.FieldByteOffset) {
922       const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext);
923       Ptr = Builder.CreateBitCast(Ptr, i8PTy);
924       Ptr = Builder.CreateConstGEP1_32(Ptr, AI.FieldByteOffset,"bf.field.offs");
925     }
926 
927     // Cast to the access type.
928     const llvm::Type *PTy = llvm::Type::getIntNPtrTy(VMContext, AI.AccessWidth,
929                                                      Ty.getAddressSpace());
930     Ptr = Builder.CreateBitCast(Ptr, PTy);
931 
932     // Extract the piece of the bit-field value to write in this access, limited
933     // to the values that are part of this access.
934     llvm::Value *Val = SrcVal;
935     if (AI.TargetBitOffset)
936       Val = Builder.CreateLShr(Val, AI.TargetBitOffset);
937     Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(ResSizeInBits,
938                                                             AI.TargetBitWidth));
939 
940     // Extend or truncate to the access size.
941     const llvm::Type *AccessLTy =
942       llvm::Type::getIntNTy(VMContext, AI.AccessWidth);
943     if (ResSizeInBits < AI.AccessWidth)
944       Val = Builder.CreateZExt(Val, AccessLTy);
945     else if (ResSizeInBits > AI.AccessWidth)
946       Val = Builder.CreateTrunc(Val, AccessLTy);
947 
948     // Shift into the position in memory.
949     if (AI.FieldBitStart)
950       Val = Builder.CreateShl(Val, AI.FieldBitStart);
951 
952     // If necessary, load and OR in bits that are outside of the bit-field.
953     if (AI.TargetBitWidth != AI.AccessWidth) {
954       llvm::LoadInst *Load = Builder.CreateLoad(Ptr, Dst.isVolatileQualified());
955       if (AI.AccessAlignment)
956         Load->setAlignment(AI.AccessAlignment);
957 
958       // Compute the mask for zeroing the bits that are part of the bit-field.
959       llvm::APInt InvMask =
960         ~llvm::APInt::getBitsSet(AI.AccessWidth, AI.FieldBitStart,
961                                  AI.FieldBitStart + AI.TargetBitWidth);
962 
963       // Apply the mask and OR in to the value to write.
964       Val = Builder.CreateOr(Builder.CreateAnd(Load, InvMask), Val);
965     }
966 
967     // Write the value.
968     llvm::StoreInst *Store = Builder.CreateStore(Val, Ptr,
969                                                  Dst.isVolatileQualified());
970     if (AI.AccessAlignment)
971       Store->setAlignment(AI.AccessAlignment);
972   }
973 }
974 
975 void CodeGenFunction::EmitStoreThroughPropertyRefLValue(RValue Src,
976                                                         LValue Dst,
977                                                         QualType Ty) {
978   EmitObjCPropertySet(Dst.getPropertyRefExpr(), Src);
979 }
980 
981 void CodeGenFunction::EmitStoreThroughKVCRefLValue(RValue Src,
982                                                    LValue Dst,
983                                                    QualType Ty) {
984   EmitObjCPropertySet(Dst.getKVCRefExpr(), Src);
985 }
986 
987 void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
988                                                                LValue Dst,
989                                                                QualType Ty) {
990   // This access turns into a read/modify/write of the vector.  Load the input
991   // value now.
992   llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddr(),
993                                         Dst.isVolatileQualified(), "tmp");
994   const llvm::Constant *Elts = Dst.getExtVectorElts();
995 
996   llvm::Value *SrcVal = Src.getScalarVal();
997 
998   if (const VectorType *VTy = Ty->getAs<VectorType>()) {
999     unsigned NumSrcElts = VTy->getNumElements();
1000     unsigned NumDstElts =
1001        cast<llvm::VectorType>(Vec->getType())->getNumElements();
1002     if (NumDstElts == NumSrcElts) {
1003       // Use shuffle vector is the src and destination are the same number of
1004       // elements and restore the vector mask since it is on the side it will be
1005       // stored.
1006       llvm::SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
1007       for (unsigned i = 0; i != NumSrcElts; ++i) {
1008         unsigned InIdx = getAccessedFieldNo(i, Elts);
1009         Mask[InIdx] = llvm::ConstantInt::get(Int32Ty, i);
1010       }
1011 
1012       llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size());
1013       Vec = Builder.CreateShuffleVector(SrcVal,
1014                                         llvm::UndefValue::get(Vec->getType()),
1015                                         MaskV, "tmp");
1016     } else if (NumDstElts > NumSrcElts) {
1017       // Extended the source vector to the same length and then shuffle it
1018       // into the destination.
1019       // FIXME: since we're shuffling with undef, can we just use the indices
1020       //        into that?  This could be simpler.
1021       llvm::SmallVector<llvm::Constant*, 4> ExtMask;
1022       unsigned i;
1023       for (i = 0; i != NumSrcElts; ++i)
1024         ExtMask.push_back(llvm::ConstantInt::get(Int32Ty, i));
1025       for (; i != NumDstElts; ++i)
1026         ExtMask.push_back(llvm::UndefValue::get(Int32Ty));
1027       llvm::Value *ExtMaskV = llvm::ConstantVector::get(&ExtMask[0],
1028                                                         ExtMask.size());
1029       llvm::Value *ExtSrcVal =
1030         Builder.CreateShuffleVector(SrcVal,
1031                                     llvm::UndefValue::get(SrcVal->getType()),
1032                                     ExtMaskV, "tmp");
1033       // build identity
1034       llvm::SmallVector<llvm::Constant*, 4> Mask;
1035       for (unsigned i = 0; i != NumDstElts; ++i)
1036         Mask.push_back(llvm::ConstantInt::get(Int32Ty, i));
1037 
1038       // modify when what gets shuffled in
1039       for (unsigned i = 0; i != NumSrcElts; ++i) {
1040         unsigned Idx = getAccessedFieldNo(i, Elts);
1041         Mask[Idx] = llvm::ConstantInt::get(Int32Ty, i+NumDstElts);
1042       }
1043       llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size());
1044       Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV, "tmp");
1045     } else {
1046       // We should never shorten the vector
1047       assert(0 && "unexpected shorten vector length");
1048     }
1049   } else {
1050     // If the Src is a scalar (not a vector) it must be updating one element.
1051     unsigned InIdx = getAccessedFieldNo(0, Elts);
1052     llvm::Value *Elt = llvm::ConstantInt::get(Int32Ty, InIdx);
1053     Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt, "tmp");
1054   }
1055 
1056   Builder.CreateStore(Vec, Dst.getExtVectorAddr(), Dst.isVolatileQualified());
1057 }
1058 
1059 // setObjCGCLValueClass - sets class of he lvalue for the purpose of
1060 // generating write-barries API. It is currently a global, ivar,
1061 // or neither.
1062 static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
1063                                  LValue &LV) {
1064   if (Ctx.getLangOptions().getGCMode() == LangOptions::NonGC)
1065     return;
1066 
1067   if (isa<ObjCIvarRefExpr>(E)) {
1068     LV.setObjCIvar(true);
1069     ObjCIvarRefExpr *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr*>(E));
1070     LV.setBaseIvarExp(Exp->getBase());
1071     LV.setObjCArray(E->getType()->isArrayType());
1072     return;
1073   }
1074 
1075   if (const DeclRefExpr *Exp = dyn_cast<DeclRefExpr>(E)) {
1076     if (const VarDecl *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
1077       if (VD->hasGlobalStorage()) {
1078         LV.setGlobalObjCRef(true);
1079         LV.setThreadLocalRef(VD->isThreadSpecified());
1080       }
1081     }
1082     LV.setObjCArray(E->getType()->isArrayType());
1083     return;
1084   }
1085 
1086   if (const UnaryOperator *Exp = dyn_cast<UnaryOperator>(E)) {
1087     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV);
1088     return;
1089   }
1090 
1091   if (const ParenExpr *Exp = dyn_cast<ParenExpr>(E)) {
1092     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV);
1093     if (LV.isObjCIvar()) {
1094       // If cast is to a structure pointer, follow gcc's behavior and make it
1095       // a non-ivar write-barrier.
1096       QualType ExpTy = E->getType();
1097       if (ExpTy->isPointerType())
1098         ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1099       if (ExpTy->isRecordType())
1100         LV.setObjCIvar(false);
1101     }
1102     return;
1103   }
1104   if (const ImplicitCastExpr *Exp = dyn_cast<ImplicitCastExpr>(E)) {
1105     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV);
1106     return;
1107   }
1108 
1109   if (const CStyleCastExpr *Exp = dyn_cast<CStyleCastExpr>(E)) {
1110     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV);
1111     return;
1112   }
1113 
1114   if (const ArraySubscriptExpr *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
1115     setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
1116     if (LV.isObjCIvar() && !LV.isObjCArray())
1117       // Using array syntax to assigning to what an ivar points to is not
1118       // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
1119       LV.setObjCIvar(false);
1120     else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
1121       // Using array syntax to assigning to what global points to is not
1122       // same as assigning to the global itself. {id *G;} G[i] = 0;
1123       LV.setGlobalObjCRef(false);
1124     return;
1125   }
1126 
1127   if (const MemberExpr *Exp = dyn_cast<MemberExpr>(E)) {
1128     setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
1129     // We don't know if member is an 'ivar', but this flag is looked at
1130     // only in the context of LV.isObjCIvar().
1131     LV.setObjCArray(E->getType()->isArrayType());
1132     return;
1133   }
1134 }
1135 
1136 static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
1137                                       const Expr *E, const VarDecl *VD) {
1138   assert((VD->hasExternalStorage() || VD->isFileVarDecl()) &&
1139          "Var decl must have external storage or be a file var decl!");
1140 
1141   llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
1142   if (VD->getType()->isReferenceType())
1143     V = CGF.Builder.CreateLoad(V, "tmp");
1144   unsigned Alignment = CGF.getContext().getDeclAlign(VD).getQuantity();
1145   LValue LV = CGF.MakeAddrLValue(V, E->getType(), Alignment);
1146   setObjCGCLValueClass(CGF.getContext(), E, LV);
1147   return LV;
1148 }
1149 
1150 static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
1151                                       const Expr *E, const FunctionDecl *FD) {
1152   llvm::Value *V = CGF.CGM.GetAddrOfFunction(FD);
1153   if (!FD->hasPrototype()) {
1154     if (const FunctionProtoType *Proto =
1155             FD->getType()->getAs<FunctionProtoType>()) {
1156       // Ugly case: for a K&R-style definition, the type of the definition
1157       // isn't the same as the type of a use.  Correct for this with a
1158       // bitcast.
1159       QualType NoProtoType =
1160           CGF.getContext().getFunctionNoProtoType(Proto->getResultType());
1161       NoProtoType = CGF.getContext().getPointerType(NoProtoType);
1162       V = CGF.Builder.CreateBitCast(V, CGF.ConvertType(NoProtoType), "tmp");
1163     }
1164   }
1165   unsigned Alignment = CGF.getContext().getDeclAlign(FD).getQuantity();
1166   return CGF.MakeAddrLValue(V, E->getType(), Alignment);
1167 }
1168 
1169 LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
1170   const NamedDecl *ND = E->getDecl();
1171   unsigned Alignment = CGF.getContext().getDeclAlign(ND).getQuantity();
1172 
1173   if (ND->hasAttr<WeakRefAttr>()) {
1174     const ValueDecl *VD = cast<ValueDecl>(ND);
1175     llvm::Constant *Aliasee = CGM.GetWeakRefReference(VD);
1176     return MakeAddrLValue(Aliasee, E->getType(), Alignment);
1177   }
1178 
1179   if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1180 
1181     // Check if this is a global variable.
1182     if (VD->hasExternalStorage() || VD->isFileVarDecl())
1183       return EmitGlobalVarDeclLValue(*this, E, VD);
1184 
1185     bool NonGCable = VD->hasLocalStorage() && !VD->hasAttr<BlocksAttr>();
1186 
1187     llvm::Value *V = LocalDeclMap[VD];
1188     if (!V && VD->isStaticLocal())
1189       V = CGM.getStaticLocalDeclAddress(VD);
1190     assert(V && "DeclRefExpr not entered in LocalDeclMap?");
1191 
1192     if (VD->hasAttr<BlocksAttr>()) {
1193       V = Builder.CreateStructGEP(V, 1, "forwarding");
1194       V = Builder.CreateLoad(V);
1195       V = Builder.CreateStructGEP(V, getByRefValueLLVMField(VD),
1196                                   VD->getNameAsString());
1197     }
1198     if (VD->getType()->isReferenceType())
1199       V = Builder.CreateLoad(V, "tmp");
1200 
1201     LValue LV = MakeAddrLValue(V, E->getType(), Alignment);
1202     if (NonGCable) {
1203       LV.getQuals().removeObjCGCAttr();
1204       LV.setNonGC(true);
1205     }
1206     setObjCGCLValueClass(getContext(), E, LV);
1207     return LV;
1208   }
1209 
1210   // If we're emitting an instance method as an independent lvalue,
1211   // we're actually emitting a member pointer.
1212   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1213     if (MD->isInstance()) {
1214       llvm::Value *V = CGM.getCXXABI().EmitMemberPointer(MD);
1215       return MakeAddrLValue(V, MD->getType(), Alignment);
1216     }
1217   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
1218     return EmitFunctionDeclLValue(*this, E, FD);
1219 
1220   // If we're emitting a field as an independent lvalue, we're
1221   // actually emitting a member pointer.
1222   if (const FieldDecl *FD = dyn_cast<FieldDecl>(ND)) {
1223     llvm::Value *V = CGM.getCXXABI().EmitMemberPointer(FD);
1224     return MakeAddrLValue(V, FD->getType(), Alignment);
1225   }
1226 
1227   assert(false && "Unhandled DeclRefExpr");
1228 
1229   // an invalid LValue, but the assert will
1230   // ensure that this point is never reached.
1231   return LValue();
1232 }
1233 
1234 LValue CodeGenFunction::EmitBlockDeclRefLValue(const BlockDeclRefExpr *E) {
1235   unsigned Alignment =
1236     CGF.getContext().getDeclAlign(E->getDecl()).getQuantity();
1237   return MakeAddrLValue(GetAddrOfBlockDecl(E), E->getType(), Alignment);
1238 }
1239 
1240 LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
1241   // __extension__ doesn't affect lvalue-ness.
1242   if (E->getOpcode() == UO_Extension)
1243     return EmitLValue(E->getSubExpr());
1244 
1245   QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
1246   switch (E->getOpcode()) {
1247   default: assert(0 && "Unknown unary operator lvalue!");
1248   case UO_Deref: {
1249     QualType T = E->getSubExpr()->getType()->getPointeeType();
1250     assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
1251 
1252     LValue LV = MakeAddrLValue(EmitScalarExpr(E->getSubExpr()), T);
1253     LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
1254 
1255     // We should not generate __weak write barrier on indirect reference
1256     // of a pointer to object; as in void foo (__weak id *param); *param = 0;
1257     // But, we continue to generate __strong write barrier on indirect write
1258     // into a pointer to object.
1259     if (getContext().getLangOptions().ObjC1 &&
1260         getContext().getLangOptions().getGCMode() != LangOptions::NonGC &&
1261         LV.isObjCWeak())
1262       LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
1263     return LV;
1264   }
1265   case UO_Real:
1266   case UO_Imag: {
1267     LValue LV = EmitLValue(E->getSubExpr());
1268     unsigned Idx = E->getOpcode() == UO_Imag;
1269     return MakeAddrLValue(Builder.CreateStructGEP(LV.getAddress(),
1270                                                     Idx, "idx"),
1271                           ExprTy);
1272   }
1273   case UO_PreInc:
1274   case UO_PreDec: {
1275     LValue LV = EmitLValue(E->getSubExpr());
1276     bool isInc = E->getOpcode() == UO_PreInc;
1277 
1278     if (E->getType()->isAnyComplexType())
1279       EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
1280     else
1281       EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
1282     return LV;
1283   }
1284   }
1285 }
1286 
1287 LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
1288   return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
1289                         E->getType());
1290 }
1291 
1292 LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
1293   return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
1294                         E->getType());
1295 }
1296 
1297 
1298 LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
1299   switch (E->getIdentType()) {
1300   default:
1301     return EmitUnsupportedLValue(E, "predefined expression");
1302 
1303   case PredefinedExpr::Func:
1304   case PredefinedExpr::Function:
1305   case PredefinedExpr::PrettyFunction: {
1306     unsigned Type = E->getIdentType();
1307     std::string GlobalVarName;
1308 
1309     switch (Type) {
1310     default: assert(0 && "Invalid type");
1311     case PredefinedExpr::Func:
1312       GlobalVarName = "__func__.";
1313       break;
1314     case PredefinedExpr::Function:
1315       GlobalVarName = "__FUNCTION__.";
1316       break;
1317     case PredefinedExpr::PrettyFunction:
1318       GlobalVarName = "__PRETTY_FUNCTION__.";
1319       break;
1320     }
1321 
1322     llvm::StringRef FnName = CurFn->getName();
1323     if (FnName.startswith("\01"))
1324       FnName = FnName.substr(1);
1325     GlobalVarName += FnName;
1326 
1327     const Decl *CurDecl = CurCodeDecl;
1328     if (CurDecl == 0)
1329       CurDecl = getContext().getTranslationUnitDecl();
1330 
1331     std::string FunctionName =
1332       PredefinedExpr::ComputeName((PredefinedExpr::IdentType)Type, CurDecl);
1333 
1334     llvm::Constant *C =
1335       CGM.GetAddrOfConstantCString(FunctionName, GlobalVarName.c_str());
1336     return MakeAddrLValue(C, E->getType());
1337   }
1338   }
1339 }
1340 
1341 llvm::BasicBlock *CodeGenFunction::getTrapBB() {
1342   const CodeGenOptions &GCO = CGM.getCodeGenOpts();
1343 
1344   // If we are not optimzing, don't collapse all calls to trap in the function
1345   // to the same call, that way, in the debugger they can see which operation
1346   // did in fact fail.  If we are optimizing, we collapse all calls to trap down
1347   // to just one per function to save on codesize.
1348   if (GCO.OptimizationLevel && TrapBB)
1349     return TrapBB;
1350 
1351   llvm::BasicBlock *Cont = 0;
1352   if (HaveInsertPoint()) {
1353     Cont = createBasicBlock("cont");
1354     EmitBranch(Cont);
1355   }
1356   TrapBB = createBasicBlock("trap");
1357   EmitBlock(TrapBB);
1358 
1359   llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::trap, 0, 0);
1360   llvm::CallInst *TrapCall = Builder.CreateCall(F);
1361   TrapCall->setDoesNotReturn();
1362   TrapCall->setDoesNotThrow();
1363   Builder.CreateUnreachable();
1364 
1365   if (Cont)
1366     EmitBlock(Cont);
1367   return TrapBB;
1368 }
1369 
1370 /// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
1371 /// array to pointer, return the array subexpression.
1372 static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
1373   // If this isn't just an array->pointer decay, bail out.
1374   const CastExpr *CE = dyn_cast<CastExpr>(E);
1375   if (CE == 0 || CE->getCastKind() != CK_ArrayToPointerDecay)
1376     return 0;
1377 
1378   // If this is a decay from variable width array, bail out.
1379   const Expr *SubExpr = CE->getSubExpr();
1380   if (SubExpr->getType()->isVariableArrayType())
1381     return 0;
1382 
1383   return SubExpr;
1384 }
1385 
1386 LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
1387   // The index must always be an integer, which is not an aggregate.  Emit it.
1388   llvm::Value *Idx = EmitScalarExpr(E->getIdx());
1389   QualType IdxTy  = E->getIdx()->getType();
1390   bool IdxSigned = IdxTy->isSignedIntegerType();
1391 
1392   // If the base is a vector type, then we are forming a vector element lvalue
1393   // with this subscript.
1394   if (E->getBase()->getType()->isVectorType()) {
1395     // Emit the vector as an lvalue to get its address.
1396     LValue LHS = EmitLValue(E->getBase());
1397     assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
1398     Idx = Builder.CreateIntCast(Idx, CGF.Int32Ty, IdxSigned, "vidx");
1399     return LValue::MakeVectorElt(LHS.getAddress(), Idx,
1400                                  E->getBase()->getType().getCVRQualifiers());
1401   }
1402 
1403   // Extend or truncate the index type to 32 or 64-bits.
1404   if (!Idx->getType()->isIntegerTy(LLVMPointerWidth))
1405     Idx = Builder.CreateIntCast(Idx, IntPtrTy,
1406                                 IdxSigned, "idxprom");
1407 
1408   // FIXME: As llvm implements the object size checking, this can come out.
1409   if (CatchUndefined) {
1410     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E->getBase())){
1411       if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
1412         if (ICE->getCastKind() == CK_ArrayToPointerDecay) {
1413           if (const ConstantArrayType *CAT
1414               = getContext().getAsConstantArrayType(DRE->getType())) {
1415             llvm::APInt Size = CAT->getSize();
1416             llvm::BasicBlock *Cont = createBasicBlock("cont");
1417             Builder.CreateCondBr(Builder.CreateICmpULE(Idx,
1418                                   llvm::ConstantInt::get(Idx->getType(), Size)),
1419                                  Cont, getTrapBB());
1420             EmitBlock(Cont);
1421           }
1422         }
1423       }
1424     }
1425   }
1426 
1427   // We know that the pointer points to a type of the correct size, unless the
1428   // size is a VLA or Objective-C interface.
1429   llvm::Value *Address = 0;
1430   if (const VariableArrayType *VAT =
1431         getContext().getAsVariableArrayType(E->getType())) {
1432     llvm::Value *VLASize = GetVLASize(VAT);
1433 
1434     Idx = Builder.CreateMul(Idx, VLASize);
1435 
1436     const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext);
1437 
1438     // The base must be a pointer, which is not an aggregate.  Emit it.
1439     llvm::Value *Base = EmitScalarExpr(E->getBase());
1440 
1441     Address = Builder.CreateInBoundsGEP(Builder.CreateBitCast(Base, i8PTy),
1442                                         Idx, "arrayidx");
1443     Address = Builder.CreateBitCast(Address, Base->getType());
1444   } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
1445     // Indexing over an interface, as in "NSString *P; P[4];"
1446     llvm::Value *InterfaceSize =
1447       llvm::ConstantInt::get(Idx->getType(),
1448           getContext().getTypeSizeInChars(OIT).getQuantity());
1449 
1450     Idx = Builder.CreateMul(Idx, InterfaceSize);
1451 
1452     const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext);
1453 
1454     // The base must be a pointer, which is not an aggregate.  Emit it.
1455     llvm::Value *Base = EmitScalarExpr(E->getBase());
1456     Address = Builder.CreateGEP(Builder.CreateBitCast(Base, i8PTy),
1457                                 Idx, "arrayidx");
1458     Address = Builder.CreateBitCast(Address, Base->getType());
1459   } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
1460     // If this is A[i] where A is an array, the frontend will have decayed the
1461     // base to be a ArrayToPointerDecay implicit cast.  While correct, it is
1462     // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
1463     // "gep x, i" here.  Emit one "gep A, 0, i".
1464     assert(Array->getType()->isArrayType() &&
1465            "Array to pointer decay must have array source type!");
1466     llvm::Value *ArrayPtr = EmitLValue(Array).getAddress();
1467     llvm::Value *Zero = llvm::ConstantInt::get(Int32Ty, 0);
1468     llvm::Value *Args[] = { Zero, Idx };
1469 
1470     Address = Builder.CreateInBoundsGEP(ArrayPtr, Args, Args+2, "arrayidx");
1471   } else {
1472     // The base must be a pointer, which is not an aggregate.  Emit it.
1473     llvm::Value *Base = EmitScalarExpr(E->getBase());
1474     Address = Builder.CreateInBoundsGEP(Base, Idx, "arrayidx");
1475   }
1476 
1477   QualType T = E->getBase()->getType()->getPointeeType();
1478   assert(!T.isNull() &&
1479          "CodeGenFunction::EmitArraySubscriptExpr(): Illegal base type");
1480 
1481   LValue LV = MakeAddrLValue(Address, T);
1482   LV.getQuals().setAddressSpace(E->getBase()->getType().getAddressSpace());
1483 
1484   if (getContext().getLangOptions().ObjC1 &&
1485       getContext().getLangOptions().getGCMode() != LangOptions::NonGC) {
1486     LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
1487     setObjCGCLValueClass(getContext(), E, LV);
1488   }
1489   return LV;
1490 }
1491 
1492 static
1493 llvm::Constant *GenerateConstantVector(llvm::LLVMContext &VMContext,
1494                                        llvm::SmallVector<unsigned, 4> &Elts) {
1495   llvm::SmallVector<llvm::Constant*, 4> CElts;
1496 
1497   const llvm::Type *Int32Ty = llvm::Type::getInt32Ty(VMContext);
1498   for (unsigned i = 0, e = Elts.size(); i != e; ++i)
1499     CElts.push_back(llvm::ConstantInt::get(Int32Ty, Elts[i]));
1500 
1501   return llvm::ConstantVector::get(&CElts[0], CElts.size());
1502 }
1503 
1504 LValue CodeGenFunction::
1505 EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
1506   // Emit the base vector as an l-value.
1507   LValue Base;
1508 
1509   // ExtVectorElementExpr's base can either be a vector or pointer to vector.
1510   if (E->isArrow()) {
1511     // If it is a pointer to a vector, emit the address and form an lvalue with
1512     // it.
1513     llvm::Value *Ptr = EmitScalarExpr(E->getBase());
1514     const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
1515     Base = MakeAddrLValue(Ptr, PT->getPointeeType());
1516     Base.getQuals().removeObjCGCAttr();
1517   } else if (E->getBase()->isLvalue(getContext()) == Expr::LV_Valid) {
1518     // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
1519     // emit the base as an lvalue.
1520     assert(E->getBase()->getType()->isVectorType());
1521     Base = EmitLValue(E->getBase());
1522   } else {
1523     // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
1524     assert(E->getBase()->getType()->getAs<VectorType>() &&
1525            "Result must be a vector");
1526     llvm::Value *Vec = EmitScalarExpr(E->getBase());
1527 
1528     // Store the vector to memory (because LValue wants an address).
1529     llvm::Value *VecMem = CreateMemTemp(E->getBase()->getType());
1530     Builder.CreateStore(Vec, VecMem);
1531     Base = MakeAddrLValue(VecMem, E->getBase()->getType());
1532   }
1533 
1534   // Encode the element access list into a vector of unsigned indices.
1535   llvm::SmallVector<unsigned, 4> Indices;
1536   E->getEncodedElementAccess(Indices);
1537 
1538   if (Base.isSimple()) {
1539     llvm::Constant *CV = GenerateConstantVector(VMContext, Indices);
1540     return LValue::MakeExtVectorElt(Base.getAddress(), CV,
1541                                     Base.getVRQualifiers());
1542   }
1543   assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
1544 
1545   llvm::Constant *BaseElts = Base.getExtVectorElts();
1546   llvm::SmallVector<llvm::Constant *, 4> CElts;
1547 
1548   for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
1549     if (isa<llvm::ConstantAggregateZero>(BaseElts))
1550       CElts.push_back(llvm::ConstantInt::get(Int32Ty, 0));
1551     else
1552       CElts.push_back(cast<llvm::Constant>(BaseElts->getOperand(Indices[i])));
1553   }
1554   llvm::Constant *CV = llvm::ConstantVector::get(&CElts[0], CElts.size());
1555   return LValue::MakeExtVectorElt(Base.getExtVectorAddr(), CV,
1556                                   Base.getVRQualifiers());
1557 }
1558 
1559 LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
1560   bool isNonGC = false;
1561   Expr *BaseExpr = E->getBase();
1562   llvm::Value *BaseValue = NULL;
1563   Qualifiers BaseQuals;
1564 
1565   // If this is s.x, emit s as an lvalue.  If it is s->x, emit s as a scalar.
1566   if (E->isArrow()) {
1567     BaseValue = EmitScalarExpr(BaseExpr);
1568     const PointerType *PTy =
1569       BaseExpr->getType()->getAs<PointerType>();
1570     BaseQuals = PTy->getPointeeType().getQualifiers();
1571   } else if (isa<ObjCPropertyRefExpr>(BaseExpr->IgnoreParens()) ||
1572              isa<ObjCImplicitSetterGetterRefExpr>(
1573                BaseExpr->IgnoreParens())) {
1574     RValue RV = EmitObjCPropertyGet(BaseExpr);
1575     BaseValue = RV.getAggregateAddr();
1576     BaseQuals = BaseExpr->getType().getQualifiers();
1577   } else {
1578     LValue BaseLV = EmitLValue(BaseExpr);
1579     if (BaseLV.isNonGC())
1580       isNonGC = true;
1581     // FIXME: this isn't right for bitfields.
1582     BaseValue = BaseLV.getAddress();
1583     QualType BaseTy = BaseExpr->getType();
1584     BaseQuals = BaseTy.getQualifiers();
1585   }
1586 
1587   NamedDecl *ND = E->getMemberDecl();
1588   if (FieldDecl *Field = dyn_cast<FieldDecl>(ND)) {
1589     LValue LV = EmitLValueForField(BaseValue, Field,
1590                                    BaseQuals.getCVRQualifiers());
1591     LV.setNonGC(isNonGC);
1592     setObjCGCLValueClass(getContext(), E, LV);
1593     return LV;
1594   }
1595 
1596   if (VarDecl *VD = dyn_cast<VarDecl>(ND))
1597     return EmitGlobalVarDeclLValue(*this, E, VD);
1598 
1599   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
1600     return EmitFunctionDeclLValue(*this, E, FD);
1601 
1602   assert(false && "Unhandled member declaration!");
1603   return LValue();
1604 }
1605 
1606 LValue CodeGenFunction::EmitLValueForBitfield(llvm::Value *BaseValue,
1607                                               const FieldDecl *Field,
1608                                               unsigned CVRQualifiers) {
1609   const CGRecordLayout &RL =
1610     CGM.getTypes().getCGRecordLayout(Field->getParent());
1611   const CGBitFieldInfo &Info = RL.getBitFieldInfo(Field);
1612   return LValue::MakeBitfield(BaseValue, Info,
1613                              Field->getType().getCVRQualifiers()|CVRQualifiers);
1614 }
1615 
1616 /// EmitLValueForAnonRecordField - Given that the field is a member of
1617 /// an anonymous struct or union buried inside a record, and given
1618 /// that the base value is a pointer to the enclosing record, derive
1619 /// an lvalue for the ultimate field.
1620 LValue CodeGenFunction::EmitLValueForAnonRecordField(llvm::Value *BaseValue,
1621                                                      const FieldDecl *Field,
1622                                                      unsigned CVRQualifiers) {
1623   llvm::SmallVector<const FieldDecl *, 8> Path;
1624   Path.push_back(Field);
1625 
1626   while (Field->getParent()->isAnonymousStructOrUnion()) {
1627     const ValueDecl *VD = Field->getParent()->getAnonymousStructOrUnionObject();
1628     if (!isa<FieldDecl>(VD)) break;
1629     Field = cast<FieldDecl>(VD);
1630     Path.push_back(Field);
1631   }
1632 
1633   llvm::SmallVectorImpl<const FieldDecl*>::reverse_iterator
1634     I = Path.rbegin(), E = Path.rend();
1635   while (true) {
1636     LValue LV = EmitLValueForField(BaseValue, *I, CVRQualifiers);
1637     if (++I == E) return LV;
1638 
1639     assert(LV.isSimple());
1640     BaseValue = LV.getAddress();
1641     CVRQualifiers |= LV.getVRQualifiers();
1642   }
1643 }
1644 
1645 LValue CodeGenFunction::EmitLValueForField(llvm::Value *BaseValue,
1646                                            const FieldDecl *Field,
1647                                            unsigned CVRQualifiers) {
1648   if (Field->isBitField())
1649     return EmitLValueForBitfield(BaseValue, Field, CVRQualifiers);
1650 
1651   const CGRecordLayout &RL =
1652     CGM.getTypes().getCGRecordLayout(Field->getParent());
1653   unsigned idx = RL.getLLVMFieldNo(Field);
1654   llvm::Value *V = Builder.CreateStructGEP(BaseValue, idx, "tmp");
1655 
1656   // Match union field type.
1657   if (Field->getParent()->isUnion()) {
1658     const llvm::Type *FieldTy =
1659       CGM.getTypes().ConvertTypeForMem(Field->getType());
1660     const llvm::PointerType *BaseTy =
1661       cast<llvm::PointerType>(BaseValue->getType());
1662     unsigned AS = BaseTy->getAddressSpace();
1663     V = Builder.CreateBitCast(V,
1664                               llvm::PointerType::get(FieldTy, AS),
1665                               "tmp");
1666   }
1667   if (Field->getType()->isReferenceType())
1668     V = Builder.CreateLoad(V, "tmp");
1669 
1670   unsigned Alignment = getContext().getDeclAlign(Field).getQuantity();
1671   LValue LV = MakeAddrLValue(V, Field->getType(), Alignment);
1672   LV.getQuals().addCVRQualifiers(CVRQualifiers);
1673 
1674   // __weak attribute on a field is ignored.
1675   if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
1676     LV.getQuals().removeObjCGCAttr();
1677 
1678   return LV;
1679 }
1680 
1681 LValue
1682 CodeGenFunction::EmitLValueForFieldInitialization(llvm::Value *BaseValue,
1683                                                   const FieldDecl *Field,
1684                                                   unsigned CVRQualifiers) {
1685   QualType FieldType = Field->getType();
1686 
1687   if (!FieldType->isReferenceType())
1688     return EmitLValueForField(BaseValue, Field, CVRQualifiers);
1689 
1690   const CGRecordLayout &RL =
1691     CGM.getTypes().getCGRecordLayout(Field->getParent());
1692   unsigned idx = RL.getLLVMFieldNo(Field);
1693   llvm::Value *V = Builder.CreateStructGEP(BaseValue, idx, "tmp");
1694 
1695   assert(!FieldType.getObjCGCAttr() && "fields cannot have GC attrs");
1696 
1697   unsigned Alignment = getContext().getDeclAlign(Field).getQuantity();
1698   return MakeAddrLValue(V, FieldType, Alignment);
1699 }
1700 
1701 LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
1702   llvm::Value *DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
1703   const Expr *InitExpr = E->getInitializer();
1704   LValue Result = MakeAddrLValue(DeclPtr, E->getType());
1705 
1706   EmitAnyExprToMem(InitExpr, DeclPtr, /*Volatile*/ false, /*Init*/ true);
1707 
1708   return Result;
1709 }
1710 
1711 LValue
1712 CodeGenFunction::EmitConditionalOperatorLValue(const ConditionalOperator *E) {
1713   if (E->isLvalue(getContext()) == Expr::LV_Valid) {
1714     if (int Cond = ConstantFoldsToSimpleInteger(E->getCond())) {
1715       Expr *Live = Cond == 1 ? E->getLHS() : E->getRHS();
1716       if (Live)
1717         return EmitLValue(Live);
1718     }
1719 
1720     llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
1721     llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
1722     llvm::BasicBlock *ContBlock = createBasicBlock("cond.end");
1723 
1724     if (E->getLHS())
1725       EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
1726     else {
1727       Expr *save = E->getSAVE();
1728       assert(save && "VisitConditionalOperator - save is null");
1729       // Intentianlly not doing direct assignment to ConditionalSaveExprs[save]
1730       LValue SaveVal = EmitLValue(save);
1731       ConditionalSaveLValueExprs[save] = SaveVal;
1732       EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
1733     }
1734 
1735     // Any temporaries created here are conditional.
1736     BeginConditionalBranch();
1737     EmitBlock(LHSBlock);
1738     LValue LHS = EmitLValue(E->getTrueExpr());
1739 
1740     EndConditionalBranch();
1741 
1742     if (!LHS.isSimple())
1743       return EmitUnsupportedLValue(E, "conditional operator");
1744 
1745     // FIXME: We shouldn't need an alloca for this.
1746     llvm::Value *Temp = CreateTempAlloca(LHS.getAddress()->getType(),"condtmp");
1747     Builder.CreateStore(LHS.getAddress(), Temp);
1748     EmitBranch(ContBlock);
1749 
1750     // Any temporaries created here are conditional.
1751     BeginConditionalBranch();
1752     EmitBlock(RHSBlock);
1753     LValue RHS = EmitLValue(E->getRHS());
1754     EndConditionalBranch();
1755     if (!RHS.isSimple())
1756       return EmitUnsupportedLValue(E, "conditional operator");
1757 
1758     Builder.CreateStore(RHS.getAddress(), Temp);
1759     EmitBranch(ContBlock);
1760 
1761     EmitBlock(ContBlock);
1762 
1763     Temp = Builder.CreateLoad(Temp, "lv");
1764     return MakeAddrLValue(Temp, E->getType());
1765   }
1766 
1767   // ?: here should be an aggregate.
1768   assert((hasAggregateLLVMType(E->getType()) &&
1769           !E->getType()->isAnyComplexType()) &&
1770          "Unexpected conditional operator!");
1771 
1772   return EmitAggExprToLValue(E);
1773 }
1774 
1775 /// EmitCastLValue - Casts are never lvalues unless that cast is a dynamic_cast.
1776 /// If the cast is a dynamic_cast, we can have the usual lvalue result,
1777 /// otherwise if a cast is needed by the code generator in an lvalue context,
1778 /// then it must mean that we need the address of an aggregate in order to
1779 /// access one of its fields.  This can happen for all the reasons that casts
1780 /// are permitted with aggregate result, including noop aggregate casts, and
1781 /// cast from scalar to union.
1782 LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
1783   switch (E->getCastKind()) {
1784   case CK_ToVoid:
1785     return EmitUnsupportedLValue(E, "unexpected cast lvalue");
1786 
1787   case CK_NoOp:
1788     if (E->getSubExpr()->Classify(getContext()).getKind()
1789                                           != Expr::Classification::CL_PRValue) {
1790       LValue LV = EmitLValue(E->getSubExpr());
1791       if (LV.isPropertyRef() || LV.isKVCRef()) {
1792         QualType QT = E->getSubExpr()->getType();
1793         RValue RV =
1794           LV.isPropertyRef() ? EmitLoadOfPropertyRefLValue(LV, QT)
1795                              : EmitLoadOfKVCRefLValue(LV, QT);
1796         assert(!RV.isScalar() && "EmitCastLValue-scalar cast of property ref");
1797         llvm::Value *V = RV.getAggregateAddr();
1798         return MakeAddrLValue(V, QT);
1799       }
1800       return LV;
1801     }
1802     // Fall through to synthesize a temporary.
1803 
1804   case CK_Unknown:
1805   case CK_BitCast:
1806   case CK_ArrayToPointerDecay:
1807   case CK_FunctionToPointerDecay:
1808   case CK_NullToMemberPointer:
1809   case CK_NullToPointer:
1810   case CK_IntegralToPointer:
1811   case CK_PointerToIntegral:
1812   case CK_VectorSplat:
1813   case CK_IntegralCast:
1814   case CK_IntegralToFloating:
1815   case CK_FloatingToIntegral:
1816   case CK_FloatingCast:
1817   case CK_DerivedToBaseMemberPointer:
1818   case CK_BaseToDerivedMemberPointer:
1819   case CK_MemberPointerToBoolean:
1820   case CK_AnyPointerToBlockPointerCast: {
1821     // These casts only produce lvalues when we're binding a reference to a
1822     // temporary realized from a (converted) pure rvalue. Emit the expression
1823     // as a value, copy it into a temporary, and return an lvalue referring to
1824     // that temporary.
1825     llvm::Value *V = CreateMemTemp(E->getType(), "ref.temp");
1826     EmitAnyExprToMem(E, V, false, false);
1827     return MakeAddrLValue(V, E->getType());
1828   }
1829 
1830   case CK_Dynamic: {
1831     LValue LV = EmitLValue(E->getSubExpr());
1832     llvm::Value *V = LV.getAddress();
1833     const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(E);
1834     return MakeAddrLValue(EmitDynamicCast(V, DCE), E->getType());
1835   }
1836 
1837   case CK_ConstructorConversion:
1838   case CK_UserDefinedConversion:
1839   case CK_AnyPointerToObjCPointerCast:
1840     return EmitLValue(E->getSubExpr());
1841 
1842   case CK_UncheckedDerivedToBase:
1843   case CK_DerivedToBase: {
1844     const RecordType *DerivedClassTy =
1845       E->getSubExpr()->getType()->getAs<RecordType>();
1846     CXXRecordDecl *DerivedClassDecl =
1847       cast<CXXRecordDecl>(DerivedClassTy->getDecl());
1848 
1849     LValue LV = EmitLValue(E->getSubExpr());
1850     llvm::Value *This;
1851     if (LV.isPropertyRef() || LV.isKVCRef()) {
1852       QualType QT = E->getSubExpr()->getType();
1853       RValue RV =
1854         LV.isPropertyRef() ? EmitLoadOfPropertyRefLValue(LV, QT)
1855                            : EmitLoadOfKVCRefLValue(LV, QT);
1856       assert (!RV.isScalar() && "EmitCastLValue");
1857       This = RV.getAggregateAddr();
1858     }
1859     else
1860       This = LV.getAddress();
1861 
1862     // Perform the derived-to-base conversion
1863     llvm::Value *Base =
1864       GetAddressOfBaseClass(This, DerivedClassDecl,
1865                             E->path_begin(), E->path_end(),
1866                             /*NullCheckValue=*/false);
1867 
1868     return MakeAddrLValue(Base, E->getType());
1869   }
1870   case CK_ToUnion:
1871     return EmitAggExprToLValue(E);
1872   case CK_BaseToDerived: {
1873     const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
1874     CXXRecordDecl *DerivedClassDecl =
1875       cast<CXXRecordDecl>(DerivedClassTy->getDecl());
1876 
1877     LValue LV = EmitLValue(E->getSubExpr());
1878 
1879     // Perform the base-to-derived conversion
1880     llvm::Value *Derived =
1881       GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
1882                                E->path_begin(), E->path_end(),
1883                                /*NullCheckValue=*/false);
1884 
1885     return MakeAddrLValue(Derived, E->getType());
1886   }
1887   case CK_LValueBitCast: {
1888     // This must be a reinterpret_cast (or c-style equivalent).
1889     const ExplicitCastExpr *CE = cast<ExplicitCastExpr>(E);
1890 
1891     LValue LV = EmitLValue(E->getSubExpr());
1892     llvm::Value *V = Builder.CreateBitCast(LV.getAddress(),
1893                                            ConvertType(CE->getTypeAsWritten()));
1894     return MakeAddrLValue(V, E->getType());
1895   }
1896   case CK_ObjCObjectLValueCast: {
1897     LValue LV = EmitLValue(E->getSubExpr());
1898     QualType ToType = getContext().getLValueReferenceType(E->getType());
1899     llvm::Value *V = Builder.CreateBitCast(LV.getAddress(),
1900                                            ConvertType(ToType));
1901     return MakeAddrLValue(V, E->getType());
1902   }
1903   }
1904 
1905   llvm_unreachable("Unhandled lvalue cast kind?");
1906 }
1907 
1908 LValue CodeGenFunction::EmitNullInitializationLValue(
1909                                               const CXXScalarValueInitExpr *E) {
1910   QualType Ty = E->getType();
1911   LValue LV = MakeAddrLValue(CreateMemTemp(Ty), Ty);
1912   EmitNullInitialization(LV.getAddress(), Ty);
1913   return LV;
1914 }
1915 
1916 //===--------------------------------------------------------------------===//
1917 //                             Expression Emission
1918 //===--------------------------------------------------------------------===//
1919 
1920 
1921 RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
1922                                      ReturnValueSlot ReturnValue) {
1923   // Builtins never have block type.
1924   if (E->getCallee()->getType()->isBlockPointerType())
1925     return EmitBlockCallExpr(E, ReturnValue);
1926 
1927   if (const CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(E))
1928     return EmitCXXMemberCallExpr(CE, ReturnValue);
1929 
1930   const Decl *TargetDecl = 0;
1931   if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E->getCallee())) {
1932     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1933       TargetDecl = DRE->getDecl();
1934       if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(TargetDecl))
1935         if (unsigned builtinID = FD->getBuiltinID())
1936           return EmitBuiltinExpr(FD, builtinID, E);
1937     }
1938   }
1939 
1940   if (const CXXOperatorCallExpr *CE = dyn_cast<CXXOperatorCallExpr>(E))
1941     if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(TargetDecl))
1942       return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
1943 
1944   if (isa<CXXPseudoDestructorExpr>(E->getCallee()->IgnoreParens())) {
1945     // C++ [expr.pseudo]p1:
1946     //   The result shall only be used as the operand for the function call
1947     //   operator (), and the result of such a call has type void. The only
1948     //   effect is the evaluation of the postfix-expression before the dot or
1949     //   arrow.
1950     EmitScalarExpr(E->getCallee());
1951     return RValue::get(0);
1952   }
1953 
1954   llvm::Value *Callee = EmitScalarExpr(E->getCallee());
1955   return EmitCall(E->getCallee()->getType(), Callee, ReturnValue,
1956                   E->arg_begin(), E->arg_end(), TargetDecl);
1957 }
1958 
1959 LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
1960   // Comma expressions just emit their LHS then their RHS as an l-value.
1961   if (E->getOpcode() == BO_Comma) {
1962     EmitAnyExpr(E->getLHS());
1963     EnsureInsertPoint();
1964     return EmitLValue(E->getRHS());
1965   }
1966 
1967   if (E->getOpcode() == BO_PtrMemD ||
1968       E->getOpcode() == BO_PtrMemI)
1969     return EmitPointerToDataMemberBinaryExpr(E);
1970 
1971   // Can only get l-value for binary operator expressions which are a
1972   // simple assignment of aggregate type.
1973   if (E->getOpcode() != BO_Assign)
1974     return EmitUnsupportedLValue(E, "binary l-value expression");
1975 
1976   if (!hasAggregateLLVMType(E->getType())) {
1977     // Emit the LHS as an l-value.
1978     LValue LV = EmitLValue(E->getLHS());
1979     // Store the value through the l-value.
1980     EmitStoreThroughLValue(EmitAnyExpr(E->getRHS()), LV, E->getType());
1981     return LV;
1982   }
1983 
1984   return EmitAggExprToLValue(E);
1985 }
1986 
1987 LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
1988   RValue RV = EmitCallExpr(E);
1989 
1990   if (!RV.isScalar())
1991     return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
1992 
1993   assert(E->getCallReturnType()->isReferenceType() &&
1994          "Can't have a scalar return unless the return type is a "
1995          "reference type!");
1996 
1997   return MakeAddrLValue(RV.getScalarVal(), E->getType());
1998 }
1999 
2000 LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
2001   // FIXME: This shouldn't require another copy.
2002   return EmitAggExprToLValue(E);
2003 }
2004 
2005 LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
2006   assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
2007          && "binding l-value to type which needs a temporary");
2008   AggValueSlot Slot = CreateAggTemp(E->getType(), "tmp");
2009   EmitCXXConstructExpr(E, Slot);
2010   return MakeAddrLValue(Slot.getAddr(), E->getType());
2011 }
2012 
2013 LValue
2014 CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
2015   return MakeAddrLValue(EmitCXXTypeidExpr(E), E->getType());
2016 }
2017 
2018 LValue
2019 CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
2020   AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
2021   Slot.setLifetimeExternallyManaged();
2022   EmitAggExpr(E->getSubExpr(), Slot);
2023   EmitCXXTemporary(E->getTemporary(), Slot.getAddr());
2024   return MakeAddrLValue(Slot.getAddr(), E->getType());
2025 }
2026 
2027 LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
2028   RValue RV = EmitObjCMessageExpr(E);
2029 
2030   if (!RV.isScalar())
2031     return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
2032 
2033   assert(E->getMethodDecl()->getResultType()->isReferenceType() &&
2034          "Can't have a scalar return unless the return type is a "
2035          "reference type!");
2036 
2037   return MakeAddrLValue(RV.getScalarVal(), E->getType());
2038 }
2039 
2040 LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
2041   llvm::Value *V =
2042     CGM.getObjCRuntime().GetSelector(Builder, E->getSelector(), true);
2043   return MakeAddrLValue(V, E->getType());
2044 }
2045 
2046 llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
2047                                              const ObjCIvarDecl *Ivar) {
2048   return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
2049 }
2050 
2051 LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
2052                                           llvm::Value *BaseValue,
2053                                           const ObjCIvarDecl *Ivar,
2054                                           unsigned CVRQualifiers) {
2055   return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
2056                                                    Ivar, CVRQualifiers);
2057 }
2058 
2059 LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
2060   // FIXME: A lot of the code below could be shared with EmitMemberExpr.
2061   llvm::Value *BaseValue = 0;
2062   const Expr *BaseExpr = E->getBase();
2063   Qualifiers BaseQuals;
2064   QualType ObjectTy;
2065   if (E->isArrow()) {
2066     BaseValue = EmitScalarExpr(BaseExpr);
2067     ObjectTy = BaseExpr->getType()->getPointeeType();
2068     BaseQuals = ObjectTy.getQualifiers();
2069   } else {
2070     LValue BaseLV = EmitLValue(BaseExpr);
2071     // FIXME: this isn't right for bitfields.
2072     BaseValue = BaseLV.getAddress();
2073     ObjectTy = BaseExpr->getType();
2074     BaseQuals = ObjectTy.getQualifiers();
2075   }
2076 
2077   LValue LV =
2078     EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
2079                       BaseQuals.getCVRQualifiers());
2080   setObjCGCLValueClass(getContext(), E, LV);
2081   return LV;
2082 }
2083 
2084 LValue
2085 CodeGenFunction::EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E) {
2086   // This is a special l-value that just issues sends when we load or store
2087   // through it.
2088   return LValue::MakePropertyRef(E, E->getType().getCVRQualifiers());
2089 }
2090 
2091 LValue CodeGenFunction::EmitObjCKVCRefLValue(
2092                                 const ObjCImplicitSetterGetterRefExpr *E) {
2093   // This is a special l-value that just issues sends when we load or store
2094   // through it.
2095   return LValue::MakeKVCRef(E, E->getType().getCVRQualifiers());
2096 }
2097 
2098 LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
2099   // Can only get l-value for message expression returning aggregate type
2100   RValue RV = EmitAnyExprToTemp(E);
2101   return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
2102 }
2103 
2104 RValue CodeGenFunction::EmitCall(QualType CalleeType, llvm::Value *Callee,
2105                                  ReturnValueSlot ReturnValue,
2106                                  CallExpr::const_arg_iterator ArgBeg,
2107                                  CallExpr::const_arg_iterator ArgEnd,
2108                                  const Decl *TargetDecl) {
2109   // Get the actual function type. The callee type will always be a pointer to
2110   // function type or a block pointer type.
2111   assert(CalleeType->isFunctionPointerType() &&
2112          "Call must have function pointer type!");
2113 
2114   CalleeType = getContext().getCanonicalType(CalleeType);
2115 
2116   const FunctionType *FnType
2117     = cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
2118   QualType ResultType = FnType->getResultType();
2119 
2120   CallArgList Args;
2121   EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), ArgBeg, ArgEnd);
2122 
2123   return EmitCall(CGM.getTypes().getFunctionInfo(Args, FnType),
2124                   Callee, ReturnValue, Args, TargetDecl);
2125 }
2126 
2127 LValue CodeGenFunction::
2128 EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
2129   llvm::Value *BaseV;
2130   if (E->getOpcode() == BO_PtrMemI)
2131     BaseV = EmitScalarExpr(E->getLHS());
2132   else
2133     BaseV = EmitLValue(E->getLHS()).getAddress();
2134 
2135   llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
2136 
2137   const MemberPointerType *MPT
2138     = E->getRHS()->getType()->getAs<MemberPointerType>();
2139 
2140   llvm::Value *AddV =
2141     CGM.getCXXABI().EmitMemberDataPointerAddress(*this, BaseV, OffsetV, MPT);
2142 
2143   return MakeAddrLValue(AddV, MPT->getPointeeType());
2144 }
2145 
2146