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