CGExpr.cpp revision 08a9ae95ba7e0a87e667f97ccc5bac646df9a705
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 "CGDebugInfo.h"
19#include "CGRecordLayout.h"
20#include "CGObjCRuntime.h"
21#include "TargetInfo.h"
22#include "clang/AST/ASTContext.h"
23#include "clang/AST/DeclObjC.h"
24#include "clang/Frontend/CodeGenOptions.h"
25#include "llvm/Intrinsics.h"
26#include "llvm/LLVMContext.h"
27#include "llvm/Support/MDBuilder.h"
28#include "llvm/Target/TargetData.h"
29using namespace clang;
30using namespace CodeGen;
31
32//===--------------------------------------------------------------------===//
33//                        Miscellaneous Helper Methods
34//===--------------------------------------------------------------------===//
35
36llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) {
37  unsigned addressSpace =
38    cast<llvm::PointerType>(value->getType())->getAddressSpace();
39
40  llvm::PointerType *destType = Int8PtrTy;
41  if (addressSpace)
42    destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace);
43
44  if (value->getType() == destType) return value;
45  return Builder.CreateBitCast(value, destType);
46}
47
48/// CreateTempAlloca - This creates a alloca and inserts it into the entry
49/// block.
50llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
51                                                    const Twine &Name) {
52  if (!Builder.isNamePreserving())
53    return new llvm::AllocaInst(Ty, 0, "", AllocaInsertPt);
54  return new llvm::AllocaInst(Ty, 0, Name, AllocaInsertPt);
55}
56
57void CodeGenFunction::InitTempAlloca(llvm::AllocaInst *Var,
58                                     llvm::Value *Init) {
59  llvm::StoreInst *Store = new llvm::StoreInst(Init, Var);
60  llvm::BasicBlock *Block = AllocaInsertPt->getParent();
61  Block->getInstList().insertAfter(&*AllocaInsertPt, Store);
62}
63
64llvm::AllocaInst *CodeGenFunction::CreateIRTemp(QualType Ty,
65                                                const Twine &Name) {
66  llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertType(Ty), Name);
67  // FIXME: Should we prefer the preferred type alignment here?
68  CharUnits Align = getContext().getTypeAlignInChars(Ty);
69  Alloc->setAlignment(Align.getQuantity());
70  return Alloc;
71}
72
73llvm::AllocaInst *CodeGenFunction::CreateMemTemp(QualType Ty,
74                                                 const Twine &Name) {
75  llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty), Name);
76  // FIXME: Should we prefer the preferred type alignment here?
77  CharUnits Align = getContext().getTypeAlignInChars(Ty);
78  Alloc->setAlignment(Align.getQuantity());
79  return Alloc;
80}
81
82/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
83/// expression and compare the result against zero, returning an Int1Ty value.
84llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
85  if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
86    llvm::Value *MemPtr = EmitScalarExpr(E);
87    return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
88  }
89
90  QualType BoolTy = getContext().BoolTy;
91  if (!E->getType()->isAnyComplexType())
92    return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy);
93
94  return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(),BoolTy);
95}
96
97/// EmitIgnoredExpr - Emit code to compute the specified expression,
98/// ignoring the result.
99void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
100  if (E->isRValue())
101    return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
102
103  // Just emit it as an l-value and drop the result.
104  EmitLValue(E);
105}
106
107/// EmitAnyExpr - Emit code to compute the specified expression which
108/// can have any type.  The result is returned as an RValue struct.
109/// If this is an aggregate expression, AggSlot indicates where the
110/// result should be returned.
111RValue CodeGenFunction::EmitAnyExpr(const Expr *E, AggValueSlot AggSlot,
112                                    bool IgnoreResult) {
113  if (!hasAggregateLLVMType(E->getType()))
114    return RValue::get(EmitScalarExpr(E, IgnoreResult));
115  else if (E->getType()->isAnyComplexType())
116    return RValue::getComplex(EmitComplexExpr(E, IgnoreResult, IgnoreResult));
117
118  EmitAggExpr(E, AggSlot, IgnoreResult);
119  return AggSlot.asRValue();
120}
121
122/// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
123/// always be accessible even if no aggregate location is provided.
124RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
125  AggValueSlot AggSlot = AggValueSlot::ignored();
126
127  if (hasAggregateLLVMType(E->getType()) &&
128      !E->getType()->isAnyComplexType())
129    AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
130  return EmitAnyExpr(E, AggSlot);
131}
132
133/// EmitAnyExprToMem - Evaluate an expression into a given memory
134/// location.
135void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
136                                       llvm::Value *Location,
137                                       Qualifiers Quals,
138                                       bool IsInit) {
139  // FIXME: This function should take an LValue as an argument.
140  if (E->getType()->isAnyComplexType()) {
141    EmitComplexExprIntoAddr(E, Location, Quals.hasVolatile());
142  } else if (hasAggregateLLVMType(E->getType())) {
143    CharUnits Alignment = getContext().getTypeAlignInChars(E->getType());
144    EmitAggExpr(E, AggValueSlot::forAddr(Location, Alignment, Quals,
145                                         AggValueSlot::IsDestructed_t(IsInit),
146                                         AggValueSlot::DoesNotNeedGCBarriers,
147                                         AggValueSlot::IsAliased_t(!IsInit)));
148  } else {
149    RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
150    LValue LV = MakeAddrLValue(Location, E->getType());
151    EmitStoreThroughLValue(RV, LV);
152  }
153}
154
155namespace {
156/// \brief An adjustment to be made to the temporary created when emitting a
157/// reference binding, which accesses a particular subobject of that temporary.
158  struct SubobjectAdjustment {
159    enum { DerivedToBaseAdjustment, FieldAdjustment } Kind;
160
161    union {
162      struct {
163        const CastExpr *BasePath;
164        const CXXRecordDecl *DerivedClass;
165      } DerivedToBase;
166
167      FieldDecl *Field;
168    };
169
170    SubobjectAdjustment(const CastExpr *BasePath,
171                        const CXXRecordDecl *DerivedClass)
172      : Kind(DerivedToBaseAdjustment) {
173      DerivedToBase.BasePath = BasePath;
174      DerivedToBase.DerivedClass = DerivedClass;
175    }
176
177    SubobjectAdjustment(FieldDecl *Field)
178      : Kind(FieldAdjustment) {
179      this->Field = Field;
180    }
181  };
182}
183
184static llvm::Value *
185CreateReferenceTemporary(CodeGenFunction &CGF, QualType Type,
186                         const NamedDecl *InitializedDecl) {
187  if (const VarDecl *VD = dyn_cast_or_null<VarDecl>(InitializedDecl)) {
188    if (VD->hasGlobalStorage()) {
189      SmallString<256> Name;
190      llvm::raw_svector_ostream Out(Name);
191      CGF.CGM.getCXXABI().getMangleContext().mangleReferenceTemporary(VD, Out);
192      Out.flush();
193
194      llvm::Type *RefTempTy = CGF.ConvertTypeForMem(Type);
195
196      // Create the reference temporary.
197      llvm::GlobalValue *RefTemp =
198        new llvm::GlobalVariable(CGF.CGM.getModule(),
199                                 RefTempTy, /*isConstant=*/false,
200                                 llvm::GlobalValue::InternalLinkage,
201                                 llvm::Constant::getNullValue(RefTempTy),
202                                 Name.str());
203      return RefTemp;
204    }
205  }
206
207  return CGF.CreateMemTemp(Type, "ref.tmp");
208}
209
210static llvm::Value *
211EmitExprForReferenceBinding(CodeGenFunction &CGF, const Expr *E,
212                            llvm::Value *&ReferenceTemporary,
213                            const CXXDestructorDecl *&ReferenceTemporaryDtor,
214                            QualType &ObjCARCReferenceLifetimeType,
215                            const NamedDecl *InitializedDecl) {
216  // Look through single-element init lists that claim to be lvalues. They're
217  // just syntactic wrappers in this case.
218  if (const InitListExpr *ILE = dyn_cast<InitListExpr>(E)) {
219    if (ILE->getNumInits() == 1 && ILE->isGLValue())
220      E = ILE->getInit(0);
221  }
222
223  // Look through expressions for materialized temporaries (for now).
224  if (const MaterializeTemporaryExpr *M
225                                      = dyn_cast<MaterializeTemporaryExpr>(E)) {
226    // Objective-C++ ARC:
227    //   If we are binding a reference to a temporary that has ownership, we
228    //   need to perform retain/release operations on the temporary.
229    if (CGF.getContext().getLangOpts().ObjCAutoRefCount &&
230        E->getType()->isObjCLifetimeType() &&
231        (E->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
232         E->getType().getObjCLifetime() == Qualifiers::OCL_Weak ||
233         E->getType().getObjCLifetime() == Qualifiers::OCL_Autoreleasing))
234      ObjCARCReferenceLifetimeType = E->getType();
235
236    E = M->GetTemporaryExpr();
237  }
238
239  if (const CXXDefaultArgExpr *DAE = dyn_cast<CXXDefaultArgExpr>(E))
240    E = DAE->getExpr();
241
242  if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(E)) {
243    CGF.enterFullExpression(EWC);
244    CodeGenFunction::RunCleanupsScope Scope(CGF);
245
246    return EmitExprForReferenceBinding(CGF, EWC->getSubExpr(),
247                                       ReferenceTemporary,
248                                       ReferenceTemporaryDtor,
249                                       ObjCARCReferenceLifetimeType,
250                                       InitializedDecl);
251  }
252
253  RValue RV;
254  if (E->isGLValue()) {
255    // Emit the expression as an lvalue.
256    LValue LV = CGF.EmitLValue(E);
257
258    if (LV.isSimple())
259      return LV.getAddress();
260
261    // We have to load the lvalue.
262    RV = CGF.EmitLoadOfLValue(LV);
263  } else {
264    if (!ObjCARCReferenceLifetimeType.isNull()) {
265      ReferenceTemporary = CreateReferenceTemporary(CGF,
266                                                  ObjCARCReferenceLifetimeType,
267                                                    InitializedDecl);
268
269
270      LValue RefTempDst = CGF.MakeAddrLValue(ReferenceTemporary,
271                                             ObjCARCReferenceLifetimeType);
272
273      CGF.EmitScalarInit(E, dyn_cast_or_null<ValueDecl>(InitializedDecl),
274                         RefTempDst, false);
275
276      bool ExtendsLifeOfTemporary = false;
277      if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(InitializedDecl)) {
278        if (Var->extendsLifetimeOfTemporary())
279          ExtendsLifeOfTemporary = true;
280      } else if (InitializedDecl && isa<FieldDecl>(InitializedDecl)) {
281        ExtendsLifeOfTemporary = true;
282      }
283
284      if (!ExtendsLifeOfTemporary) {
285        // Since the lifetime of this temporary isn't going to be extended,
286        // we need to clean it up ourselves at the end of the full expression.
287        switch (ObjCARCReferenceLifetimeType.getObjCLifetime()) {
288        case Qualifiers::OCL_None:
289        case Qualifiers::OCL_ExplicitNone:
290        case Qualifiers::OCL_Autoreleasing:
291          break;
292
293        case Qualifiers::OCL_Strong: {
294          assert(!ObjCARCReferenceLifetimeType->isArrayType());
295          CleanupKind cleanupKind = CGF.getARCCleanupKind();
296          CGF.pushDestroy(cleanupKind,
297                          ReferenceTemporary,
298                          ObjCARCReferenceLifetimeType,
299                          CodeGenFunction::destroyARCStrongImprecise,
300                          cleanupKind & EHCleanup);
301          break;
302        }
303
304        case Qualifiers::OCL_Weak:
305          assert(!ObjCARCReferenceLifetimeType->isArrayType());
306          CGF.pushDestroy(NormalAndEHCleanup,
307                          ReferenceTemporary,
308                          ObjCARCReferenceLifetimeType,
309                          CodeGenFunction::destroyARCWeak,
310                          /*useEHCleanupForArray*/ true);
311          break;
312        }
313
314        ObjCARCReferenceLifetimeType = QualType();
315      }
316
317      return ReferenceTemporary;
318    }
319
320    SmallVector<SubobjectAdjustment, 2> Adjustments;
321    while (true) {
322      E = E->IgnoreParens();
323
324      if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
325        if ((CE->getCastKind() == CK_DerivedToBase ||
326             CE->getCastKind() == CK_UncheckedDerivedToBase) &&
327            E->getType()->isRecordType()) {
328          E = CE->getSubExpr();
329          CXXRecordDecl *Derived
330            = cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl());
331          Adjustments.push_back(SubobjectAdjustment(CE, Derived));
332          continue;
333        }
334
335        if (CE->getCastKind() == CK_NoOp) {
336          E = CE->getSubExpr();
337          continue;
338        }
339      } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
340        if (!ME->isArrow() && ME->getBase()->isRValue()) {
341          assert(ME->getBase()->getType()->isRecordType());
342          if (FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
343            E = ME->getBase();
344            Adjustments.push_back(SubobjectAdjustment(Field));
345            continue;
346          }
347        }
348      }
349
350      if (const OpaqueValueExpr *opaque = dyn_cast<OpaqueValueExpr>(E))
351        if (opaque->getType()->isRecordType())
352          return CGF.EmitOpaqueValueLValue(opaque).getAddress();
353
354      // Nothing changed.
355      break;
356    }
357
358    // Create a reference temporary if necessary.
359    AggValueSlot AggSlot = AggValueSlot::ignored();
360    if (CGF.hasAggregateLLVMType(E->getType()) &&
361        !E->getType()->isAnyComplexType()) {
362      ReferenceTemporary = CreateReferenceTemporary(CGF, E->getType(),
363                                                    InitializedDecl);
364      CharUnits Alignment = CGF.getContext().getTypeAlignInChars(E->getType());
365      AggValueSlot::IsDestructed_t isDestructed
366        = AggValueSlot::IsDestructed_t(InitializedDecl != 0);
367      AggSlot = AggValueSlot::forAddr(ReferenceTemporary, Alignment,
368                                      Qualifiers(), isDestructed,
369                                      AggValueSlot::DoesNotNeedGCBarriers,
370                                      AggValueSlot::IsNotAliased);
371    }
372
373    if (InitializedDecl) {
374      // Get the destructor for the reference temporary.
375      if (const RecordType *RT = E->getType()->getAs<RecordType>()) {
376        CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
377        if (!ClassDecl->hasTrivialDestructor())
378          ReferenceTemporaryDtor = ClassDecl->getDestructor();
379      }
380    }
381
382    RV = CGF.EmitAnyExpr(E, AggSlot);
383
384    // Check if need to perform derived-to-base casts and/or field accesses, to
385    // get from the temporary object we created (and, potentially, for which we
386    // extended the lifetime) to the subobject we're binding the reference to.
387    if (!Adjustments.empty()) {
388      llvm::Value *Object = RV.getAggregateAddr();
389      for (unsigned I = Adjustments.size(); I != 0; --I) {
390        SubobjectAdjustment &Adjustment = Adjustments[I-1];
391        switch (Adjustment.Kind) {
392        case SubobjectAdjustment::DerivedToBaseAdjustment:
393          Object =
394              CGF.GetAddressOfBaseClass(Object,
395                                        Adjustment.DerivedToBase.DerivedClass,
396                              Adjustment.DerivedToBase.BasePath->path_begin(),
397                              Adjustment.DerivedToBase.BasePath->path_end(),
398                                        /*NullCheckValue=*/false);
399          break;
400
401        case SubobjectAdjustment::FieldAdjustment: {
402          LValue LV = CGF.MakeAddrLValue(Object, E->getType());
403          LV = CGF.EmitLValueForField(LV, Adjustment.Field);
404          if (LV.isSimple()) {
405            Object = LV.getAddress();
406            break;
407          }
408
409          // For non-simple lvalues, we actually have to create a copy of
410          // the object we're binding to.
411          QualType T = Adjustment.Field->getType().getNonReferenceType()
412                                                  .getUnqualifiedType();
413          Object = CreateReferenceTemporary(CGF, T, InitializedDecl);
414          LValue TempLV = CGF.MakeAddrLValue(Object,
415                                             Adjustment.Field->getType());
416          CGF.EmitStoreThroughLValue(CGF.EmitLoadOfLValue(LV), TempLV);
417          break;
418        }
419
420        }
421      }
422
423      return Object;
424    }
425  }
426
427  if (RV.isAggregate())
428    return RV.getAggregateAddr();
429
430  // Create a temporary variable that we can bind the reference to.
431  ReferenceTemporary = CreateReferenceTemporary(CGF, E->getType(),
432                                                InitializedDecl);
433
434
435  unsigned Alignment =
436    CGF.getContext().getTypeAlignInChars(E->getType()).getQuantity();
437  if (RV.isScalar())
438    CGF.EmitStoreOfScalar(RV.getScalarVal(), ReferenceTemporary,
439                          /*Volatile=*/false, Alignment, E->getType());
440  else
441    CGF.StoreComplexToAddr(RV.getComplexVal(), ReferenceTemporary,
442                           /*Volatile=*/false);
443  return ReferenceTemporary;
444}
445
446RValue
447CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E,
448                                            const NamedDecl *InitializedDecl) {
449  llvm::Value *ReferenceTemporary = 0;
450  const CXXDestructorDecl *ReferenceTemporaryDtor = 0;
451  QualType ObjCARCReferenceLifetimeType;
452  llvm::Value *Value = EmitExprForReferenceBinding(*this, E, ReferenceTemporary,
453                                                   ReferenceTemporaryDtor,
454                                                   ObjCARCReferenceLifetimeType,
455                                                   InitializedDecl);
456  if (!ReferenceTemporaryDtor && ObjCARCReferenceLifetimeType.isNull())
457    return RValue::get(Value);
458
459  // Make sure to call the destructor for the reference temporary.
460  const VarDecl *VD = dyn_cast_or_null<VarDecl>(InitializedDecl);
461  if (VD && VD->hasGlobalStorage()) {
462    if (ReferenceTemporaryDtor) {
463      llvm::Constant *DtorFn =
464        CGM.GetAddrOfCXXDestructor(ReferenceTemporaryDtor, Dtor_Complete);
465      CGM.getCXXABI().registerGlobalDtor(*this, DtorFn,
466                                    cast<llvm::Constant>(ReferenceTemporary));
467    } else {
468      assert(!ObjCARCReferenceLifetimeType.isNull());
469      // Note: We intentionally do not register a global "destructor" to
470      // release the object.
471    }
472
473    return RValue::get(Value);
474  }
475
476  if (ReferenceTemporaryDtor)
477    PushDestructorCleanup(ReferenceTemporaryDtor, ReferenceTemporary);
478  else {
479    switch (ObjCARCReferenceLifetimeType.getObjCLifetime()) {
480    case Qualifiers::OCL_None:
481      llvm_unreachable(
482                      "Not a reference temporary that needs to be deallocated");
483    case Qualifiers::OCL_ExplicitNone:
484    case Qualifiers::OCL_Autoreleasing:
485      // Nothing to do.
486      break;
487
488    case Qualifiers::OCL_Strong: {
489      bool precise = VD && VD->hasAttr<ObjCPreciseLifetimeAttr>();
490      CleanupKind cleanupKind = getARCCleanupKind();
491      pushDestroy(cleanupKind, ReferenceTemporary, ObjCARCReferenceLifetimeType,
492                  precise ? destroyARCStrongPrecise : destroyARCStrongImprecise,
493                  cleanupKind & EHCleanup);
494      break;
495    }
496
497    case Qualifiers::OCL_Weak: {
498      // __weak objects always get EH cleanups; otherwise, exceptions
499      // could cause really nasty crashes instead of mere leaks.
500      pushDestroy(NormalAndEHCleanup, ReferenceTemporary,
501                  ObjCARCReferenceLifetimeType, destroyARCWeak, true);
502      break;
503    }
504    }
505  }
506
507  return RValue::get(Value);
508}
509
510
511/// getAccessedFieldNo - Given an encoded value and a result number, return the
512/// input field number being accessed.
513unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
514                                             const llvm::Constant *Elts) {
515  return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
516      ->getZExtValue();
517}
518
519void CodeGenFunction::EmitCheck(llvm::Value *Address, unsigned Size) {
520  if (BoundsChecking <= 0)
521    return;
522
523  // This needs to be to the standard address space.
524  Address = Builder.CreateBitCast(Address, Int8PtrTy);
525
526  llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, IntPtrTy);
527
528  llvm::Value *Min = Builder.getFalse();
529  llvm::Value *Runtime = Builder.getInt32(BoundsChecking);
530  llvm::Value *C = Builder.CreateCall3(F, Address, Min, Runtime);
531  llvm::BasicBlock *Cont = createBasicBlock();
532  Builder.CreateCondBr(Builder.CreateICmpUGE(C,
533                                        llvm::ConstantInt::get(IntPtrTy, Size)),
534                       Cont, getTrapBB());
535  EmitBlock(Cont);
536}
537
538
539CodeGenFunction::ComplexPairTy CodeGenFunction::
540EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
541                         bool isInc, bool isPre) {
542  ComplexPairTy InVal = LoadComplexFromAddr(LV.getAddress(),
543                                            LV.isVolatileQualified());
544
545  llvm::Value *NextVal;
546  if (isa<llvm::IntegerType>(InVal.first->getType())) {
547    uint64_t AmountVal = isInc ? 1 : -1;
548    NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
549
550    // Add the inc/dec to the real part.
551    NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
552  } else {
553    QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
554    llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
555    if (!isInc)
556      FVal.changeSign();
557    NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
558
559    // Add the inc/dec to the real part.
560    NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
561  }
562
563  ComplexPairTy IncVal(NextVal, InVal.second);
564
565  // Store the updated result through the lvalue.
566  StoreComplexToAddr(IncVal, LV.getAddress(), LV.isVolatileQualified());
567
568  // If this is a postinc, return the value read from memory, otherwise use the
569  // updated value.
570  return isPre ? IncVal : InVal;
571}
572
573
574//===----------------------------------------------------------------------===//
575//                         LValue Expression Emission
576//===----------------------------------------------------------------------===//
577
578RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
579  if (Ty->isVoidType())
580    return RValue::get(0);
581
582  if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
583    llvm::Type *EltTy = ConvertType(CTy->getElementType());
584    llvm::Value *U = llvm::UndefValue::get(EltTy);
585    return RValue::getComplex(std::make_pair(U, U));
586  }
587
588  // If this is a use of an undefined aggregate type, the aggregate must have an
589  // identifiable address.  Just because the contents of the value are undefined
590  // doesn't mean that the address can't be taken and compared.
591  if (hasAggregateLLVMType(Ty)) {
592    llvm::Value *DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
593    return RValue::getAggregate(DestPtr);
594  }
595
596  return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
597}
598
599RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
600                                              const char *Name) {
601  ErrorUnsupported(E, Name);
602  return GetUndefRValue(E->getType());
603}
604
605LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
606                                              const char *Name) {
607  ErrorUnsupported(E, Name);
608  llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
609  return MakeAddrLValue(llvm::UndefValue::get(Ty), E->getType());
610}
611
612LValue CodeGenFunction::EmitCheckedLValue(const Expr *E) {
613  LValue LV = EmitLValue(E);
614  if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple())
615    EmitCheck(LV.getAddress(),
616              getContext().getTypeSizeInChars(E->getType()).getQuantity());
617  return LV;
618}
619
620/// EmitLValue - Emit code to compute a designator that specifies the location
621/// of the expression.
622///
623/// This can return one of two things: a simple address or a bitfield reference.
624/// In either case, the LLVM Value* in the LValue structure is guaranteed to be
625/// an LLVM pointer type.
626///
627/// If this returns a bitfield reference, nothing about the pointee type of the
628/// LLVM value is known: For example, it may not be a pointer to an integer.
629///
630/// If this returns a normal address, and if the lvalue's C type is fixed size,
631/// this method guarantees that the returned pointer type will point to an LLVM
632/// type of the same size of the lvalue's type.  If the lvalue has a variable
633/// length type, this is not possible.
634///
635LValue CodeGenFunction::EmitLValue(const Expr *E) {
636  switch (E->getStmtClass()) {
637  default: return EmitUnsupportedLValue(E, "l-value expression");
638
639  case Expr::ObjCPropertyRefExprClass:
640    llvm_unreachable("cannot emit a property reference directly");
641
642  case Expr::ObjCSelectorExprClass:
643  return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
644  case Expr::ObjCIsaExprClass:
645    return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
646  case Expr::BinaryOperatorClass:
647    return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
648  case Expr::CompoundAssignOperatorClass:
649    if (!E->getType()->isAnyComplexType())
650      return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
651    return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
652  case Expr::CallExprClass:
653  case Expr::CXXMemberCallExprClass:
654  case Expr::CXXOperatorCallExprClass:
655  case Expr::UserDefinedLiteralClass:
656    return EmitCallExprLValue(cast<CallExpr>(E));
657  case Expr::VAArgExprClass:
658    return EmitVAArgExprLValue(cast<VAArgExpr>(E));
659  case Expr::DeclRefExprClass:
660    return EmitDeclRefLValue(cast<DeclRefExpr>(E));
661  case Expr::ParenExprClass:
662    return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
663  case Expr::GenericSelectionExprClass:
664    return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
665  case Expr::PredefinedExprClass:
666    return EmitPredefinedLValue(cast<PredefinedExpr>(E));
667  case Expr::StringLiteralClass:
668    return EmitStringLiteralLValue(cast<StringLiteral>(E));
669  case Expr::ObjCEncodeExprClass:
670    return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
671  case Expr::PseudoObjectExprClass:
672    return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
673  case Expr::InitListExprClass:
674    assert(cast<InitListExpr>(E)->getNumInits() == 1 &&
675           "Only single-element init list can be lvalue.");
676    return EmitLValue(cast<InitListExpr>(E)->getInit(0));
677
678  case Expr::CXXTemporaryObjectExprClass:
679  case Expr::CXXConstructExprClass:
680    return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
681  case Expr::CXXBindTemporaryExprClass:
682    return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
683  case Expr::LambdaExprClass:
684    return EmitLambdaLValue(cast<LambdaExpr>(E));
685
686  case Expr::ExprWithCleanupsClass: {
687    const ExprWithCleanups *cleanups = cast<ExprWithCleanups>(E);
688    enterFullExpression(cleanups);
689    RunCleanupsScope Scope(*this);
690    return EmitLValue(cleanups->getSubExpr());
691  }
692
693  case Expr::CXXScalarValueInitExprClass:
694    return EmitNullInitializationLValue(cast<CXXScalarValueInitExpr>(E));
695  case Expr::CXXDefaultArgExprClass:
696    return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
697  case Expr::CXXTypeidExprClass:
698    return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
699
700  case Expr::ObjCMessageExprClass:
701    return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
702  case Expr::ObjCIvarRefExprClass:
703    return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
704  case Expr::StmtExprClass:
705    return EmitStmtExprLValue(cast<StmtExpr>(E));
706  case Expr::UnaryOperatorClass:
707    return EmitUnaryOpLValue(cast<UnaryOperator>(E));
708  case Expr::ArraySubscriptExprClass:
709    return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
710  case Expr::ExtVectorElementExprClass:
711    return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
712  case Expr::MemberExprClass:
713    return EmitMemberExpr(cast<MemberExpr>(E));
714  case Expr::CompoundLiteralExprClass:
715    return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
716  case Expr::ConditionalOperatorClass:
717    return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
718  case Expr::BinaryConditionalOperatorClass:
719    return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
720  case Expr::ChooseExprClass:
721    return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr(getContext()));
722  case Expr::OpaqueValueExprClass:
723    return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
724  case Expr::SubstNonTypeTemplateParmExprClass:
725    return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
726  case Expr::ImplicitCastExprClass:
727  case Expr::CStyleCastExprClass:
728  case Expr::CXXFunctionalCastExprClass:
729  case Expr::CXXStaticCastExprClass:
730  case Expr::CXXDynamicCastExprClass:
731  case Expr::CXXReinterpretCastExprClass:
732  case Expr::CXXConstCastExprClass:
733  case Expr::ObjCBridgedCastExprClass:
734    return EmitCastLValue(cast<CastExpr>(E));
735
736  case Expr::MaterializeTemporaryExprClass:
737    return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
738  }
739}
740
741/// Given an object of the given canonical type, can we safely copy a
742/// value out of it based on its initializer?
743static bool isConstantEmittableObjectType(QualType type) {
744  assert(type.isCanonical());
745  assert(!type->isReferenceType());
746
747  // Must be const-qualified but non-volatile.
748  Qualifiers qs = type.getLocalQualifiers();
749  if (!qs.hasConst() || qs.hasVolatile()) return false;
750
751  // Otherwise, all object types satisfy this except C++ classes with
752  // mutable subobjects or non-trivial copy/destroy behavior.
753  if (const RecordType *RT = dyn_cast<RecordType>(type))
754    if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
755      if (RD->hasMutableFields() || !RD->isTrivial())
756        return false;
757
758  return true;
759}
760
761/// Can we constant-emit a load of a reference to a variable of the
762/// given type?  This is different from predicates like
763/// Decl::isUsableInConstantExpressions because we do want it to apply
764/// in situations that don't necessarily satisfy the language's rules
765/// for this (e.g. C++'s ODR-use rules).  For example, we want to able
766/// to do this with const float variables even if those variables
767/// aren't marked 'constexpr'.
768enum ConstantEmissionKind {
769  CEK_None,
770  CEK_AsReferenceOnly,
771  CEK_AsValueOrReference,
772  CEK_AsValueOnly
773};
774static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
775  type = type.getCanonicalType();
776  if (const ReferenceType *ref = dyn_cast<ReferenceType>(type)) {
777    if (isConstantEmittableObjectType(ref->getPointeeType()))
778      return CEK_AsValueOrReference;
779    return CEK_AsReferenceOnly;
780  }
781  if (isConstantEmittableObjectType(type))
782    return CEK_AsValueOnly;
783  return CEK_None;
784}
785
786/// Try to emit a reference to the given value without producing it as
787/// an l-value.  This is actually more than an optimization: we can't
788/// produce an l-value for variables that we never actually captured
789/// in a block or lambda, which means const int variables or constexpr
790/// literals or similar.
791CodeGenFunction::ConstantEmission
792CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
793  ValueDecl *value = refExpr->getDecl();
794
795  // The value needs to be an enum constant or a constant variable.
796  ConstantEmissionKind CEK;
797  if (isa<ParmVarDecl>(value)) {
798    CEK = CEK_None;
799  } else if (VarDecl *var = dyn_cast<VarDecl>(value)) {
800    CEK = checkVarTypeForConstantEmission(var->getType());
801  } else if (isa<EnumConstantDecl>(value)) {
802    CEK = CEK_AsValueOnly;
803  } else {
804    CEK = CEK_None;
805  }
806  if (CEK == CEK_None) return ConstantEmission();
807
808  Expr::EvalResult result;
809  bool resultIsReference;
810  QualType resultType;
811
812  // It's best to evaluate all the way as an r-value if that's permitted.
813  if (CEK != CEK_AsReferenceOnly &&
814      refExpr->EvaluateAsRValue(result, getContext())) {
815    resultIsReference = false;
816    resultType = refExpr->getType();
817
818  // Otherwise, try to evaluate as an l-value.
819  } else if (CEK != CEK_AsValueOnly &&
820             refExpr->EvaluateAsLValue(result, getContext())) {
821    resultIsReference = true;
822    resultType = value->getType();
823
824  // Failure.
825  } else {
826    return ConstantEmission();
827  }
828
829  // In any case, if the initializer has side-effects, abandon ship.
830  if (result.HasSideEffects)
831    return ConstantEmission();
832
833  // Emit as a constant.
834  llvm::Constant *C = CGM.EmitConstantValue(result.Val, resultType, this);
835
836  // Make sure we emit a debug reference to the global variable.
837  // This should probably fire even for
838  if (isa<VarDecl>(value)) {
839    if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
840      EmitDeclRefExprDbgValue(refExpr, C);
841  } else {
842    assert(isa<EnumConstantDecl>(value));
843    EmitDeclRefExprDbgValue(refExpr, C);
844  }
845
846  // If we emitted a reference constant, we need to dereference that.
847  if (resultIsReference)
848    return ConstantEmission::forReference(C);
849
850  return ConstantEmission::forValue(C);
851}
852
853llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue) {
854  return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
855                          lvalue.getAlignment().getQuantity(),
856                          lvalue.getType(), lvalue.getTBAAInfo());
857}
858
859static bool hasBooleanRepresentation(QualType Ty) {
860  if (Ty->isBooleanType())
861    return true;
862
863  if (const EnumType *ET = Ty->getAs<EnumType>())
864    return ET->getDecl()->getIntegerType()->isBooleanType();
865
866  if (const AtomicType *AT = Ty->getAs<AtomicType>())
867    return hasBooleanRepresentation(AT->getValueType());
868
869  return false;
870}
871
872llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
873  const EnumType *ET = Ty->getAs<EnumType>();
874  bool IsRegularCPlusPlusEnum = (getLangOpts().CPlusPlus && ET &&
875                                 CGM.getCodeGenOpts().StrictEnums &&
876                                 !ET->getDecl()->isFixed());
877  bool IsBool = hasBooleanRepresentation(Ty);
878  if (!IsBool && !IsRegularCPlusPlusEnum)
879    return NULL;
880
881  llvm::APInt Min;
882  llvm::APInt End;
883  if (IsBool) {
884    Min = llvm::APInt(8, 0);
885    End = llvm::APInt(8, 2);
886  } else {
887    const EnumDecl *ED = ET->getDecl();
888    llvm::Type *LTy = ConvertTypeForMem(ED->getIntegerType());
889    unsigned Bitwidth = LTy->getScalarSizeInBits();
890    unsigned NumNegativeBits = ED->getNumNegativeBits();
891    unsigned NumPositiveBits = ED->getNumPositiveBits();
892
893    if (NumNegativeBits) {
894      unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
895      assert(NumBits <= Bitwidth);
896      End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
897      Min = -End;
898    } else {
899      assert(NumPositiveBits <= Bitwidth);
900      End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
901      Min = llvm::APInt(Bitwidth, 0);
902    }
903  }
904
905  llvm::MDBuilder MDHelper(getLLVMContext());
906  return MDHelper.createRange(Min, End);
907}
908
909llvm::Value *CodeGenFunction::EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
910                                              unsigned Alignment, QualType Ty,
911                                              llvm::MDNode *TBAAInfo) {
912  llvm::LoadInst *Load = Builder.CreateLoad(Addr);
913  if (Volatile)
914    Load->setVolatile(true);
915  if (Alignment)
916    Load->setAlignment(Alignment);
917  if (TBAAInfo)
918    CGM.DecorateInstruction(Load, TBAAInfo);
919  // If this is an atomic type, all normal reads must be atomic
920  if (Ty->isAtomicType())
921    Load->setAtomic(llvm::SequentiallyConsistent);
922
923  if (CGM.getCodeGenOpts().OptimizationLevel > 0)
924    if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
925      Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
926
927  return EmitFromMemory(Load, Ty);
928}
929
930llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
931  // Bool has a different representation in memory than in registers.
932  if (hasBooleanRepresentation(Ty)) {
933    // This should really always be an i1, but sometimes it's already
934    // an i8, and it's awkward to track those cases down.
935    if (Value->getType()->isIntegerTy(1))
936      return Builder.CreateZExt(Value, Builder.getInt8Ty(), "frombool");
937    assert(Value->getType()->isIntegerTy(8) && "value rep of bool not i1/i8");
938  }
939
940  return Value;
941}
942
943llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
944  // Bool has a different representation in memory than in registers.
945  if (hasBooleanRepresentation(Ty)) {
946    assert(Value->getType()->isIntegerTy(8) && "memory rep of bool not i8");
947    return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
948  }
949
950  return Value;
951}
952
953void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
954                                        bool Volatile, unsigned Alignment,
955                                        QualType Ty,
956                                        llvm::MDNode *TBAAInfo,
957                                        bool isInit) {
958  Value = EmitToMemory(Value, Ty);
959
960  llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
961  if (Alignment)
962    Store->setAlignment(Alignment);
963  if (TBAAInfo)
964    CGM.DecorateInstruction(Store, TBAAInfo);
965  if (!isInit && Ty->isAtomicType())
966    Store->setAtomic(llvm::SequentiallyConsistent);
967}
968
969void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
970    bool isInit) {
971  EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
972                    lvalue.getAlignment().getQuantity(), lvalue.getType(),
973                    lvalue.getTBAAInfo(), isInit);
974}
975
976/// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
977/// method emits the address of the lvalue, then loads the result as an rvalue,
978/// returning the rvalue.
979RValue CodeGenFunction::EmitLoadOfLValue(LValue LV) {
980  if (LV.isObjCWeak()) {
981    // load of a __weak object.
982    llvm::Value *AddrWeakObj = LV.getAddress();
983    return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
984                                                             AddrWeakObj));
985  }
986  if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak)
987    return RValue::get(EmitARCLoadWeak(LV.getAddress()));
988
989  if (LV.isSimple()) {
990    assert(!LV.getType()->isFunctionType());
991
992    // Everything needs a load.
993    return RValue::get(EmitLoadOfScalar(LV));
994  }
995
996  if (LV.isVectorElt()) {
997    llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddr(),
998                                              LV.isVolatileQualified());
999    Load->setAlignment(LV.getAlignment().getQuantity());
1000    return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
1001                                                    "vecext"));
1002  }
1003
1004  // If this is a reference to a subset of the elements of a vector, either
1005  // shuffle the input or extract/insert them as appropriate.
1006  if (LV.isExtVectorElt())
1007    return EmitLoadOfExtVectorElementLValue(LV);
1008
1009  assert(LV.isBitField() && "Unknown LValue type!");
1010  return EmitLoadOfBitfieldLValue(LV);
1011}
1012
1013RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV) {
1014  const CGBitFieldInfo &Info = LV.getBitFieldInfo();
1015
1016  // Get the output type.
1017  llvm::Type *ResLTy = ConvertType(LV.getType());
1018  unsigned ResSizeInBits = CGM.getTargetData().getTypeSizeInBits(ResLTy);
1019
1020  // Compute the result as an OR of all of the individual component accesses.
1021  llvm::Value *Res = 0;
1022  for (unsigned i = 0, e = Info.getNumComponents(); i != e; ++i) {
1023    const CGBitFieldInfo::AccessInfo &AI = Info.getComponent(i);
1024
1025    // Get the field pointer.
1026    llvm::Value *Ptr = LV.getBitFieldBaseAddr();
1027
1028    // Only offset by the field index if used, so that incoming values are not
1029    // required to be structures.
1030    if (AI.FieldIndex)
1031      Ptr = Builder.CreateStructGEP(Ptr, AI.FieldIndex, "bf.field");
1032
1033    // Offset by the byte offset, if used.
1034    if (!AI.FieldByteOffset.isZero()) {
1035      Ptr = EmitCastToVoidPtr(Ptr);
1036      Ptr = Builder.CreateConstGEP1_32(Ptr, AI.FieldByteOffset.getQuantity(),
1037                                       "bf.field.offs");
1038    }
1039
1040    // Cast to the access type.
1041    llvm::Type *PTy = llvm::Type::getIntNPtrTy(getLLVMContext(), AI.AccessWidth,
1042                       CGM.getContext().getTargetAddressSpace(LV.getType()));
1043    Ptr = Builder.CreateBitCast(Ptr, PTy);
1044
1045    // Perform the load.
1046    llvm::LoadInst *Load = Builder.CreateLoad(Ptr, LV.isVolatileQualified());
1047    if (!AI.AccessAlignment.isZero())
1048      Load->setAlignment(AI.AccessAlignment.getQuantity());
1049
1050    // Shift out unused low bits and mask out unused high bits.
1051    llvm::Value *Val = Load;
1052    if (AI.FieldBitStart)
1053      Val = Builder.CreateLShr(Load, AI.FieldBitStart);
1054    Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(AI.AccessWidth,
1055                                                            AI.TargetBitWidth),
1056                            "bf.clear");
1057
1058    // Extend or truncate to the target size.
1059    if (AI.AccessWidth < ResSizeInBits)
1060      Val = Builder.CreateZExt(Val, ResLTy);
1061    else if (AI.AccessWidth > ResSizeInBits)
1062      Val = Builder.CreateTrunc(Val, ResLTy);
1063
1064    // Shift into place, and OR into the result.
1065    if (AI.TargetBitOffset)
1066      Val = Builder.CreateShl(Val, AI.TargetBitOffset);
1067    Res = Res ? Builder.CreateOr(Res, Val) : Val;
1068  }
1069
1070  // If the bit-field is signed, perform the sign-extension.
1071  //
1072  // FIXME: This can easily be folded into the load of the high bits, which
1073  // could also eliminate the mask of high bits in some situations.
1074  if (Info.isSigned()) {
1075    unsigned ExtraBits = ResSizeInBits - Info.getSize();
1076    if (ExtraBits)
1077      Res = Builder.CreateAShr(Builder.CreateShl(Res, ExtraBits),
1078                               ExtraBits, "bf.val.sext");
1079  }
1080
1081  return RValue::get(Res);
1082}
1083
1084// If this is a reference to a subset of the elements of a vector, create an
1085// appropriate shufflevector.
1086RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
1087  llvm::LoadInst *Load = Builder.CreateLoad(LV.getExtVectorAddr(),
1088                                            LV.isVolatileQualified());
1089  Load->setAlignment(LV.getAlignment().getQuantity());
1090  llvm::Value *Vec = Load;
1091
1092  const llvm::Constant *Elts = LV.getExtVectorElts();
1093
1094  // If the result of the expression is a non-vector type, we must be extracting
1095  // a single element.  Just codegen as an extractelement.
1096  const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1097  if (!ExprVT) {
1098    unsigned InIdx = getAccessedFieldNo(0, Elts);
1099    llvm::Value *Elt = llvm::ConstantInt::get(Int32Ty, InIdx);
1100    return RValue::get(Builder.CreateExtractElement(Vec, Elt));
1101  }
1102
1103  // Always use shuffle vector to try to retain the original program structure
1104  unsigned NumResultElts = ExprVT->getNumElements();
1105
1106  SmallVector<llvm::Constant*, 4> Mask;
1107  for (unsigned i = 0; i != NumResultElts; ++i)
1108    Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
1109
1110  llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1111  Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
1112                                    MaskV);
1113  return RValue::get(Vec);
1114}
1115
1116
1117
1118/// EmitStoreThroughLValue - Store the specified rvalue into the specified
1119/// lvalue, where both are guaranteed to the have the same type, and that type
1120/// is 'Ty'.
1121void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit) {
1122  if (!Dst.isSimple()) {
1123    if (Dst.isVectorElt()) {
1124      // Read/modify/write the vector, inserting the new element.
1125      llvm::LoadInst *Load = Builder.CreateLoad(Dst.getVectorAddr(),
1126                                                Dst.isVolatileQualified());
1127      Load->setAlignment(Dst.getAlignment().getQuantity());
1128      llvm::Value *Vec = Load;
1129      Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
1130                                        Dst.getVectorIdx(), "vecins");
1131      llvm::StoreInst *Store = Builder.CreateStore(Vec, Dst.getVectorAddr(),
1132                                                   Dst.isVolatileQualified());
1133      Store->setAlignment(Dst.getAlignment().getQuantity());
1134      return;
1135    }
1136
1137    // If this is an update of extended vector elements, insert them as
1138    // appropriate.
1139    if (Dst.isExtVectorElt())
1140      return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
1141
1142    assert(Dst.isBitField() && "Unknown LValue type");
1143    return EmitStoreThroughBitfieldLValue(Src, Dst);
1144  }
1145
1146  // There's special magic for assigning into an ARC-qualified l-value.
1147  if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
1148    switch (Lifetime) {
1149    case Qualifiers::OCL_None:
1150      llvm_unreachable("present but none");
1151
1152    case Qualifiers::OCL_ExplicitNone:
1153      // nothing special
1154      break;
1155
1156    case Qualifiers::OCL_Strong:
1157      EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
1158      return;
1159
1160    case Qualifiers::OCL_Weak:
1161      EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
1162      return;
1163
1164    case Qualifiers::OCL_Autoreleasing:
1165      Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
1166                                                     Src.getScalarVal()));
1167      // fall into the normal path
1168      break;
1169    }
1170  }
1171
1172  if (Dst.isObjCWeak() && !Dst.isNonGC()) {
1173    // load of a __weak object.
1174    llvm::Value *LvalueDst = Dst.getAddress();
1175    llvm::Value *src = Src.getScalarVal();
1176     CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
1177    return;
1178  }
1179
1180  if (Dst.isObjCStrong() && !Dst.isNonGC()) {
1181    // load of a __strong object.
1182    llvm::Value *LvalueDst = Dst.getAddress();
1183    llvm::Value *src = Src.getScalarVal();
1184    if (Dst.isObjCIvar()) {
1185      assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
1186      llvm::Type *ResultType = ConvertType(getContext().LongTy);
1187      llvm::Value *RHS = EmitScalarExpr(Dst.getBaseIvarExp());
1188      llvm::Value *dst = RHS;
1189      RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1190      llvm::Value *LHS =
1191        Builder.CreatePtrToInt(LvalueDst, ResultType, "sub.ptr.lhs.cast");
1192      llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
1193      CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
1194                                              BytesBetween);
1195    } else if (Dst.isGlobalObjCRef()) {
1196      CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
1197                                                Dst.isThreadLocalRef());
1198    }
1199    else
1200      CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
1201    return;
1202  }
1203
1204  assert(Src.isScalar() && "Can't emit an agg store with this method");
1205  EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
1206}
1207
1208void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
1209                                                     llvm::Value **Result) {
1210  const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
1211
1212  // Get the output type.
1213  llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
1214  unsigned ResSizeInBits = CGM.getTargetData().getTypeSizeInBits(ResLTy);
1215
1216  // Get the source value, truncated to the width of the bit-field.
1217  llvm::Value *SrcVal = Src.getScalarVal();
1218
1219  if (hasBooleanRepresentation(Dst.getType()))
1220    SrcVal = Builder.CreateIntCast(SrcVal, ResLTy, /*IsSigned=*/false);
1221
1222  SrcVal = Builder.CreateAnd(SrcVal, llvm::APInt::getLowBitsSet(ResSizeInBits,
1223                                                                Info.getSize()),
1224                             "bf.value");
1225
1226  // Return the new value of the bit-field, if requested.
1227  if (Result) {
1228    // Cast back to the proper type for result.
1229    llvm::Type *SrcTy = Src.getScalarVal()->getType();
1230    llvm::Value *ReloadVal = Builder.CreateIntCast(SrcVal, SrcTy, false,
1231                                                   "bf.reload.val");
1232
1233    // Sign extend if necessary.
1234    if (Info.isSigned()) {
1235      unsigned ExtraBits = ResSizeInBits - Info.getSize();
1236      if (ExtraBits)
1237        ReloadVal = Builder.CreateAShr(Builder.CreateShl(ReloadVal, ExtraBits),
1238                                       ExtraBits, "bf.reload.sext");
1239    }
1240
1241    *Result = ReloadVal;
1242  }
1243
1244  // Iterate over the components, writing each piece to memory.
1245  for (unsigned i = 0, e = Info.getNumComponents(); i != e; ++i) {
1246    const CGBitFieldInfo::AccessInfo &AI = Info.getComponent(i);
1247
1248    // Get the field pointer.
1249    llvm::Value *Ptr = Dst.getBitFieldBaseAddr();
1250    unsigned addressSpace =
1251      cast<llvm::PointerType>(Ptr->getType())->getAddressSpace();
1252
1253    // Only offset by the field index if used, so that incoming values are not
1254    // required to be structures.
1255    if (AI.FieldIndex)
1256      Ptr = Builder.CreateStructGEP(Ptr, AI.FieldIndex, "bf.field");
1257
1258    // Offset by the byte offset, if used.
1259    if (!AI.FieldByteOffset.isZero()) {
1260      Ptr = EmitCastToVoidPtr(Ptr);
1261      Ptr = Builder.CreateConstGEP1_32(Ptr, AI.FieldByteOffset.getQuantity(),
1262                                       "bf.field.offs");
1263    }
1264
1265    // Cast to the access type.
1266    llvm::Type *AccessLTy =
1267      llvm::Type::getIntNTy(getLLVMContext(), AI.AccessWidth);
1268
1269    llvm::Type *PTy = AccessLTy->getPointerTo(addressSpace);
1270    Ptr = Builder.CreateBitCast(Ptr, PTy);
1271
1272    // Extract the piece of the bit-field value to write in this access, limited
1273    // to the values that are part of this access.
1274    llvm::Value *Val = SrcVal;
1275    if (AI.TargetBitOffset)
1276      Val = Builder.CreateLShr(Val, AI.TargetBitOffset);
1277    Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(ResSizeInBits,
1278                                                            AI.TargetBitWidth));
1279
1280    // Extend or truncate to the access size.
1281    if (ResSizeInBits < AI.AccessWidth)
1282      Val = Builder.CreateZExt(Val, AccessLTy);
1283    else if (ResSizeInBits > AI.AccessWidth)
1284      Val = Builder.CreateTrunc(Val, AccessLTy);
1285
1286    // Shift into the position in memory.
1287    if (AI.FieldBitStart)
1288      Val = Builder.CreateShl(Val, AI.FieldBitStart);
1289
1290    // If necessary, load and OR in bits that are outside of the bit-field.
1291    if (AI.TargetBitWidth != AI.AccessWidth) {
1292      llvm::LoadInst *Load = Builder.CreateLoad(Ptr, Dst.isVolatileQualified());
1293      if (!AI.AccessAlignment.isZero())
1294        Load->setAlignment(AI.AccessAlignment.getQuantity());
1295
1296      // Compute the mask for zeroing the bits that are part of the bit-field.
1297      llvm::APInt InvMask =
1298        ~llvm::APInt::getBitsSet(AI.AccessWidth, AI.FieldBitStart,
1299                                 AI.FieldBitStart + AI.TargetBitWidth);
1300
1301      // Apply the mask and OR in to the value to write.
1302      Val = Builder.CreateOr(Builder.CreateAnd(Load, InvMask), Val);
1303    }
1304
1305    // Write the value.
1306    llvm::StoreInst *Store = Builder.CreateStore(Val, Ptr,
1307                                                 Dst.isVolatileQualified());
1308    if (!AI.AccessAlignment.isZero())
1309      Store->setAlignment(AI.AccessAlignment.getQuantity());
1310  }
1311}
1312
1313void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
1314                                                               LValue Dst) {
1315  // This access turns into a read/modify/write of the vector.  Load the input
1316  // value now.
1317  llvm::LoadInst *Load = Builder.CreateLoad(Dst.getExtVectorAddr(),
1318                                            Dst.isVolatileQualified());
1319  Load->setAlignment(Dst.getAlignment().getQuantity());
1320  llvm::Value *Vec = Load;
1321  const llvm::Constant *Elts = Dst.getExtVectorElts();
1322
1323  llvm::Value *SrcVal = Src.getScalarVal();
1324
1325  if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
1326    unsigned NumSrcElts = VTy->getNumElements();
1327    unsigned NumDstElts =
1328       cast<llvm::VectorType>(Vec->getType())->getNumElements();
1329    if (NumDstElts == NumSrcElts) {
1330      // Use shuffle vector is the src and destination are the same number of
1331      // elements and restore the vector mask since it is on the side it will be
1332      // stored.
1333      SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
1334      for (unsigned i = 0; i != NumSrcElts; ++i)
1335        Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
1336
1337      llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1338      Vec = Builder.CreateShuffleVector(SrcVal,
1339                                        llvm::UndefValue::get(Vec->getType()),
1340                                        MaskV);
1341    } else if (NumDstElts > NumSrcElts) {
1342      // Extended the source vector to the same length and then shuffle it
1343      // into the destination.
1344      // FIXME: since we're shuffling with undef, can we just use the indices
1345      //        into that?  This could be simpler.
1346      SmallVector<llvm::Constant*, 4> ExtMask;
1347      for (unsigned i = 0; i != NumSrcElts; ++i)
1348        ExtMask.push_back(Builder.getInt32(i));
1349      ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
1350      llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
1351      llvm::Value *ExtSrcVal =
1352        Builder.CreateShuffleVector(SrcVal,
1353                                    llvm::UndefValue::get(SrcVal->getType()),
1354                                    ExtMaskV);
1355      // build identity
1356      SmallVector<llvm::Constant*, 4> Mask;
1357      for (unsigned i = 0; i != NumDstElts; ++i)
1358        Mask.push_back(Builder.getInt32(i));
1359
1360      // modify when what gets shuffled in
1361      for (unsigned i = 0; i != NumSrcElts; ++i)
1362        Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
1363      llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1364      Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
1365    } else {
1366      // We should never shorten the vector
1367      llvm_unreachable("unexpected shorten vector length");
1368    }
1369  } else {
1370    // If the Src is a scalar (not a vector) it must be updating one element.
1371    unsigned InIdx = getAccessedFieldNo(0, Elts);
1372    llvm::Value *Elt = llvm::ConstantInt::get(Int32Ty, InIdx);
1373    Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
1374  }
1375
1376  llvm::StoreInst *Store = Builder.CreateStore(Vec, Dst.getExtVectorAddr(),
1377                                               Dst.isVolatileQualified());
1378  Store->setAlignment(Dst.getAlignment().getQuantity());
1379}
1380
1381// setObjCGCLValueClass - sets class of he lvalue for the purpose of
1382// generating write-barries API. It is currently a global, ivar,
1383// or neither.
1384static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
1385                                 LValue &LV,
1386                                 bool IsMemberAccess=false) {
1387  if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
1388    return;
1389
1390  if (isa<ObjCIvarRefExpr>(E)) {
1391    QualType ExpTy = E->getType();
1392    if (IsMemberAccess && ExpTy->isPointerType()) {
1393      // If ivar is a structure pointer, assigning to field of
1394      // this struct follows gcc's behavior and makes it a non-ivar
1395      // writer-barrier conservatively.
1396      ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1397      if (ExpTy->isRecordType()) {
1398        LV.setObjCIvar(false);
1399        return;
1400      }
1401    }
1402    LV.setObjCIvar(true);
1403    ObjCIvarRefExpr *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr*>(E));
1404    LV.setBaseIvarExp(Exp->getBase());
1405    LV.setObjCArray(E->getType()->isArrayType());
1406    return;
1407  }
1408
1409  if (const DeclRefExpr *Exp = dyn_cast<DeclRefExpr>(E)) {
1410    if (const VarDecl *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
1411      if (VD->hasGlobalStorage()) {
1412        LV.setGlobalObjCRef(true);
1413        LV.setThreadLocalRef(VD->isThreadSpecified());
1414      }
1415    }
1416    LV.setObjCArray(E->getType()->isArrayType());
1417    return;
1418  }
1419
1420  if (const UnaryOperator *Exp = dyn_cast<UnaryOperator>(E)) {
1421    setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
1422    return;
1423  }
1424
1425  if (const ParenExpr *Exp = dyn_cast<ParenExpr>(E)) {
1426    setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
1427    if (LV.isObjCIvar()) {
1428      // If cast is to a structure pointer, follow gcc's behavior and make it
1429      // a non-ivar write-barrier.
1430      QualType ExpTy = E->getType();
1431      if (ExpTy->isPointerType())
1432        ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1433      if (ExpTy->isRecordType())
1434        LV.setObjCIvar(false);
1435    }
1436    return;
1437  }
1438
1439  if (const GenericSelectionExpr *Exp = dyn_cast<GenericSelectionExpr>(E)) {
1440    setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
1441    return;
1442  }
1443
1444  if (const ImplicitCastExpr *Exp = dyn_cast<ImplicitCastExpr>(E)) {
1445    setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
1446    return;
1447  }
1448
1449  if (const CStyleCastExpr *Exp = dyn_cast<CStyleCastExpr>(E)) {
1450    setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
1451    return;
1452  }
1453
1454  if (const ObjCBridgedCastExpr *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
1455    setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
1456    return;
1457  }
1458
1459  if (const ArraySubscriptExpr *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
1460    setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
1461    if (LV.isObjCIvar() && !LV.isObjCArray())
1462      // Using array syntax to assigning to what an ivar points to is not
1463      // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
1464      LV.setObjCIvar(false);
1465    else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
1466      // Using array syntax to assigning to what global points to is not
1467      // same as assigning to the global itself. {id *G;} G[i] = 0;
1468      LV.setGlobalObjCRef(false);
1469    return;
1470  }
1471
1472  if (const MemberExpr *Exp = dyn_cast<MemberExpr>(E)) {
1473    setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
1474    // We don't know if member is an 'ivar', but this flag is looked at
1475    // only in the context of LV.isObjCIvar().
1476    LV.setObjCArray(E->getType()->isArrayType());
1477    return;
1478  }
1479}
1480
1481static llvm::Value *
1482EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
1483                                llvm::Value *V, llvm::Type *IRType,
1484                                StringRef Name = StringRef()) {
1485  unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
1486  return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
1487}
1488
1489static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
1490                                      const Expr *E, const VarDecl *VD) {
1491  assert((VD->hasExternalStorage() || VD->isFileVarDecl()) &&
1492         "Var decl must have external storage or be a file var decl!");
1493
1494  llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
1495  llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
1496  V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
1497  CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
1498  QualType T = E->getType();
1499  LValue LV;
1500  if (VD->getType()->isReferenceType()) {
1501    llvm::LoadInst *LI = CGF.Builder.CreateLoad(V);
1502    LI->setAlignment(Alignment.getQuantity());
1503    V = LI;
1504    LV = CGF.MakeNaturalAlignAddrLValue(V, T);
1505  } else {
1506    LV = CGF.MakeAddrLValue(V, E->getType(), Alignment);
1507  }
1508  setObjCGCLValueClass(CGF.getContext(), E, LV);
1509  return LV;
1510}
1511
1512static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
1513                                     const Expr *E, const FunctionDecl *FD) {
1514  llvm::Value *V = CGF.CGM.GetAddrOfFunction(FD);
1515  if (!FD->hasPrototype()) {
1516    if (const FunctionProtoType *Proto =
1517            FD->getType()->getAs<FunctionProtoType>()) {
1518      // Ugly case: for a K&R-style definition, the type of the definition
1519      // isn't the same as the type of a use.  Correct for this with a
1520      // bitcast.
1521      QualType NoProtoType =
1522          CGF.getContext().getFunctionNoProtoType(Proto->getResultType());
1523      NoProtoType = CGF.getContext().getPointerType(NoProtoType);
1524      V = CGF.Builder.CreateBitCast(V, CGF.ConvertType(NoProtoType));
1525    }
1526  }
1527  CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
1528  return CGF.MakeAddrLValue(V, E->getType(), Alignment);
1529}
1530
1531LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
1532  const NamedDecl *ND = E->getDecl();
1533  CharUnits Alignment = getContext().getDeclAlign(ND);
1534  QualType T = E->getType();
1535
1536  // FIXME: We should be able to assert this for FunctionDecls as well!
1537  // FIXME: We should be able to assert this for all DeclRefExprs, not just
1538  // those with a valid source location.
1539  assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
1540          !E->getLocation().isValid()) &&
1541         "Should not use decl without marking it used!");
1542
1543  if (ND->hasAttr<WeakRefAttr>()) {
1544    const ValueDecl *VD = cast<ValueDecl>(ND);
1545    llvm::Constant *Aliasee = CGM.GetWeakRefReference(VD);
1546    return MakeAddrLValue(Aliasee, E->getType(), Alignment);
1547  }
1548
1549  if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1550    // Check if this is a global variable.
1551    if (VD->hasExternalStorage() || VD->isFileVarDecl())
1552      return EmitGlobalVarDeclLValue(*this, E, VD);
1553
1554    bool isBlockVariable = VD->hasAttr<BlocksAttr>();
1555
1556    bool NonGCable = VD->hasLocalStorage() &&
1557                     !VD->getType()->isReferenceType() &&
1558                     !isBlockVariable;
1559
1560    llvm::Value *V = LocalDeclMap[VD];
1561    if (!V && VD->isStaticLocal())
1562      V = CGM.getStaticLocalDeclAddress(VD);
1563
1564    // Use special handling for lambdas.
1565    if (!V) {
1566      if (FieldDecl *FD = LambdaCaptureFields.lookup(VD)) {
1567        QualType LambdaTagType = getContext().getTagDeclType(FD->getParent());
1568        LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue,
1569                                                     LambdaTagType);
1570        return EmitLValueForField(LambdaLV, FD);
1571      }
1572
1573      assert(isa<BlockDecl>(CurCodeDecl) && E->refersToEnclosingLocal());
1574      CharUnits alignment = getContext().getDeclAlign(VD);
1575      return MakeAddrLValue(GetAddrOfBlockDecl(VD, isBlockVariable),
1576                            E->getType(), alignment);
1577    }
1578
1579    assert(V && "DeclRefExpr not entered in LocalDeclMap?");
1580
1581    if (isBlockVariable)
1582      V = BuildBlockByrefAddress(V, VD);
1583
1584    LValue LV;
1585    if (VD->getType()->isReferenceType()) {
1586      llvm::LoadInst *LI = Builder.CreateLoad(V);
1587      LI->setAlignment(Alignment.getQuantity());
1588      V = LI;
1589      LV = MakeNaturalAlignAddrLValue(V, T);
1590    } else {
1591      LV = MakeAddrLValue(V, T, Alignment);
1592    }
1593
1594    if (NonGCable) {
1595      LV.getQuals().removeObjCGCAttr();
1596      LV.setNonGC(true);
1597    }
1598    setObjCGCLValueClass(getContext(), E, LV);
1599    return LV;
1600  }
1601
1602  if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(ND))
1603    return EmitFunctionDeclLValue(*this, E, fn);
1604
1605  llvm_unreachable("Unhandled DeclRefExpr");
1606}
1607
1608LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
1609  // __extension__ doesn't affect lvalue-ness.
1610  if (E->getOpcode() == UO_Extension)
1611    return EmitLValue(E->getSubExpr());
1612
1613  QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
1614  switch (E->getOpcode()) {
1615  default: llvm_unreachable("Unknown unary operator lvalue!");
1616  case UO_Deref: {
1617    QualType T = E->getSubExpr()->getType()->getPointeeType();
1618    assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
1619
1620    LValue LV = MakeNaturalAlignAddrLValue(EmitScalarExpr(E->getSubExpr()), T);
1621    LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
1622
1623    // We should not generate __weak write barrier on indirect reference
1624    // of a pointer to object; as in void foo (__weak id *param); *param = 0;
1625    // But, we continue to generate __strong write barrier on indirect write
1626    // into a pointer to object.
1627    if (getContext().getLangOpts().ObjC1 &&
1628        getContext().getLangOpts().getGC() != LangOptions::NonGC &&
1629        LV.isObjCWeak())
1630      LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
1631    return LV;
1632  }
1633  case UO_Real:
1634  case UO_Imag: {
1635    LValue LV = EmitLValue(E->getSubExpr());
1636    assert(LV.isSimple() && "real/imag on non-ordinary l-value");
1637    llvm::Value *Addr = LV.getAddress();
1638
1639    // __real is valid on scalars.  This is a faster way of testing that.
1640    // __imag can only produce an rvalue on scalars.
1641    if (E->getOpcode() == UO_Real &&
1642        !cast<llvm::PointerType>(Addr->getType())
1643           ->getElementType()->isStructTy()) {
1644      assert(E->getSubExpr()->getType()->isArithmeticType());
1645      return LV;
1646    }
1647
1648    assert(E->getSubExpr()->getType()->isAnyComplexType());
1649
1650    unsigned Idx = E->getOpcode() == UO_Imag;
1651    return MakeAddrLValue(Builder.CreateStructGEP(LV.getAddress(),
1652                                                  Idx, "idx"),
1653                          ExprTy);
1654  }
1655  case UO_PreInc:
1656  case UO_PreDec: {
1657    LValue LV = EmitLValue(E->getSubExpr());
1658    bool isInc = E->getOpcode() == UO_PreInc;
1659
1660    if (E->getType()->isAnyComplexType())
1661      EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
1662    else
1663      EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
1664    return LV;
1665  }
1666  }
1667}
1668
1669LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
1670  return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
1671                        E->getType());
1672}
1673
1674LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
1675  return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
1676                        E->getType());
1677}
1678
1679
1680LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
1681  switch (E->getIdentType()) {
1682  default:
1683    return EmitUnsupportedLValue(E, "predefined expression");
1684
1685  case PredefinedExpr::Func:
1686  case PredefinedExpr::Function:
1687  case PredefinedExpr::PrettyFunction: {
1688    unsigned Type = E->getIdentType();
1689    std::string GlobalVarName;
1690
1691    switch (Type) {
1692    default: llvm_unreachable("Invalid type");
1693    case PredefinedExpr::Func:
1694      GlobalVarName = "__func__.";
1695      break;
1696    case PredefinedExpr::Function:
1697      GlobalVarName = "__FUNCTION__.";
1698      break;
1699    case PredefinedExpr::PrettyFunction:
1700      GlobalVarName = "__PRETTY_FUNCTION__.";
1701      break;
1702    }
1703
1704    StringRef FnName = CurFn->getName();
1705    if (FnName.startswith("\01"))
1706      FnName = FnName.substr(1);
1707    GlobalVarName += FnName;
1708
1709    const Decl *CurDecl = CurCodeDecl;
1710    if (CurDecl == 0)
1711      CurDecl = getContext().getTranslationUnitDecl();
1712
1713    std::string FunctionName =
1714        (isa<BlockDecl>(CurDecl)
1715         ? FnName.str()
1716         : PredefinedExpr::ComputeName((PredefinedExpr::IdentType)Type, CurDecl));
1717
1718    llvm::Constant *C =
1719      CGM.GetAddrOfConstantCString(FunctionName, GlobalVarName.c_str());
1720    return MakeAddrLValue(C, E->getType());
1721  }
1722  }
1723}
1724
1725llvm::BasicBlock *CodeGenFunction::getTrapBB() {
1726  const CodeGenOptions &GCO = CGM.getCodeGenOpts();
1727
1728  // If we are not optimzing, don't collapse all calls to trap in the function
1729  // to the same call, that way, in the debugger they can see which operation
1730  // did in fact fail.  If we are optimizing, we collapse all calls to trap down
1731  // to just one per function to save on codesize.
1732  if (GCO.OptimizationLevel && TrapBB)
1733    return TrapBB;
1734
1735  llvm::BasicBlock *Cont = 0;
1736  if (HaveInsertPoint()) {
1737    Cont = createBasicBlock("cont");
1738    EmitBranch(Cont);
1739  }
1740  TrapBB = createBasicBlock("trap");
1741  EmitBlock(TrapBB);
1742
1743  llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::trap);
1744  llvm::CallInst *TrapCall = Builder.CreateCall(F);
1745  TrapCall->setDoesNotReturn();
1746  TrapCall->setDoesNotThrow();
1747  Builder.CreateUnreachable();
1748
1749  if (Cont)
1750    EmitBlock(Cont);
1751  return TrapBB;
1752}
1753
1754/// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
1755/// array to pointer, return the array subexpression.
1756static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
1757  // If this isn't just an array->pointer decay, bail out.
1758  const CastExpr *CE = dyn_cast<CastExpr>(E);
1759  if (CE == 0 || CE->getCastKind() != CK_ArrayToPointerDecay)
1760    return 0;
1761
1762  // If this is a decay from variable width array, bail out.
1763  const Expr *SubExpr = CE->getSubExpr();
1764  if (SubExpr->getType()->isVariableArrayType())
1765    return 0;
1766
1767  return SubExpr;
1768}
1769
1770LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
1771  // The index must always be an integer, which is not an aggregate.  Emit it.
1772  llvm::Value *Idx = EmitScalarExpr(E->getIdx());
1773  QualType IdxTy  = E->getIdx()->getType();
1774  bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
1775
1776  // If the base is a vector type, then we are forming a vector element lvalue
1777  // with this subscript.
1778  if (E->getBase()->getType()->isVectorType()) {
1779    // Emit the vector as an lvalue to get its address.
1780    LValue LHS = EmitLValue(E->getBase());
1781    assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
1782    Idx = Builder.CreateIntCast(Idx, Int32Ty, IdxSigned, "vidx");
1783    return LValue::MakeVectorElt(LHS.getAddress(), Idx,
1784                                 E->getBase()->getType(), LHS.getAlignment());
1785  }
1786
1787  // Extend or truncate the index type to 32 or 64-bits.
1788  if (Idx->getType() != IntPtrTy)
1789    Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
1790
1791  // We know that the pointer points to a type of the correct size, unless the
1792  // size is a VLA or Objective-C interface.
1793  llvm::Value *Address = 0;
1794  CharUnits ArrayAlignment;
1795  if (const VariableArrayType *vla =
1796        getContext().getAsVariableArrayType(E->getType())) {
1797    // The base must be a pointer, which is not an aggregate.  Emit
1798    // it.  It needs to be emitted first in case it's what captures
1799    // the VLA bounds.
1800    Address = EmitScalarExpr(E->getBase());
1801
1802    // The element count here is the total number of non-VLA elements.
1803    llvm::Value *numElements = getVLASize(vla).first;
1804
1805    // Effectively, the multiply by the VLA size is part of the GEP.
1806    // GEP indexes are signed, and scaling an index isn't permitted to
1807    // signed-overflow, so we use the same semantics for our explicit
1808    // multiply.  We suppress this if overflow is not undefined behavior.
1809    if (getLangOpts().isSignedOverflowDefined()) {
1810      Idx = Builder.CreateMul(Idx, numElements);
1811      Address = Builder.CreateGEP(Address, Idx, "arrayidx");
1812    } else {
1813      Idx = Builder.CreateNSWMul(Idx, numElements);
1814      Address = Builder.CreateInBoundsGEP(Address, Idx, "arrayidx");
1815    }
1816  } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
1817    // Indexing over an interface, as in "NSString *P; P[4];"
1818    llvm::Value *InterfaceSize =
1819      llvm::ConstantInt::get(Idx->getType(),
1820          getContext().getTypeSizeInChars(OIT).getQuantity());
1821
1822    Idx = Builder.CreateMul(Idx, InterfaceSize);
1823
1824    // The base must be a pointer, which is not an aggregate.  Emit it.
1825    llvm::Value *Base = EmitScalarExpr(E->getBase());
1826    Address = EmitCastToVoidPtr(Base);
1827    Address = Builder.CreateGEP(Address, Idx, "arrayidx");
1828    Address = Builder.CreateBitCast(Address, Base->getType());
1829  } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
1830    // If this is A[i] where A is an array, the frontend will have decayed the
1831    // base to be a ArrayToPointerDecay implicit cast.  While correct, it is
1832    // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
1833    // "gep x, i" here.  Emit one "gep A, 0, i".
1834    assert(Array->getType()->isArrayType() &&
1835           "Array to pointer decay must have array source type!");
1836    LValue ArrayLV = EmitLValue(Array);
1837    llvm::Value *ArrayPtr = ArrayLV.getAddress();
1838    llvm::Value *Zero = llvm::ConstantInt::get(Int32Ty, 0);
1839    llvm::Value *Args[] = { Zero, Idx };
1840
1841    // Propagate the alignment from the array itself to the result.
1842    ArrayAlignment = ArrayLV.getAlignment();
1843
1844    if (getContext().getLangOpts().isSignedOverflowDefined())
1845      Address = Builder.CreateGEP(ArrayPtr, Args, "arrayidx");
1846    else
1847      Address = Builder.CreateInBoundsGEP(ArrayPtr, Args, "arrayidx");
1848  } else {
1849    // The base must be a pointer, which is not an aggregate.  Emit it.
1850    llvm::Value *Base = EmitScalarExpr(E->getBase());
1851    if (getContext().getLangOpts().isSignedOverflowDefined())
1852      Address = Builder.CreateGEP(Base, Idx, "arrayidx");
1853    else
1854      Address = Builder.CreateInBoundsGEP(Base, Idx, "arrayidx");
1855  }
1856
1857  QualType T = E->getBase()->getType()->getPointeeType();
1858  assert(!T.isNull() &&
1859         "CodeGenFunction::EmitArraySubscriptExpr(): Illegal base type");
1860
1861
1862  // Limit the alignment to that of the result type.
1863  LValue LV;
1864  if (!ArrayAlignment.isZero()) {
1865    CharUnits Align = getContext().getTypeAlignInChars(T);
1866    ArrayAlignment = std::min(Align, ArrayAlignment);
1867    LV = MakeAddrLValue(Address, T, ArrayAlignment);
1868  } else {
1869    LV = MakeNaturalAlignAddrLValue(Address, T);
1870  }
1871
1872  LV.getQuals().setAddressSpace(E->getBase()->getType().getAddressSpace());
1873
1874  if (getContext().getLangOpts().ObjC1 &&
1875      getContext().getLangOpts().getGC() != LangOptions::NonGC) {
1876    LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
1877    setObjCGCLValueClass(getContext(), E, LV);
1878  }
1879  return LV;
1880}
1881
1882static
1883llvm::Constant *GenerateConstantVector(CGBuilderTy &Builder,
1884                                       SmallVector<unsigned, 4> &Elts) {
1885  SmallVector<llvm::Constant*, 4> CElts;
1886  for (unsigned i = 0, e = Elts.size(); i != e; ++i)
1887    CElts.push_back(Builder.getInt32(Elts[i]));
1888
1889  return llvm::ConstantVector::get(CElts);
1890}
1891
1892LValue CodeGenFunction::
1893EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
1894  // Emit the base vector as an l-value.
1895  LValue Base;
1896
1897  // ExtVectorElementExpr's base can either be a vector or pointer to vector.
1898  if (E->isArrow()) {
1899    // If it is a pointer to a vector, emit the address and form an lvalue with
1900    // it.
1901    llvm::Value *Ptr = EmitScalarExpr(E->getBase());
1902    const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
1903    Base = MakeAddrLValue(Ptr, PT->getPointeeType());
1904    Base.getQuals().removeObjCGCAttr();
1905  } else if (E->getBase()->isGLValue()) {
1906    // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
1907    // emit the base as an lvalue.
1908    assert(E->getBase()->getType()->isVectorType());
1909    Base = EmitLValue(E->getBase());
1910  } else {
1911    // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
1912    assert(E->getBase()->getType()->isVectorType() &&
1913           "Result must be a vector");
1914    llvm::Value *Vec = EmitScalarExpr(E->getBase());
1915
1916    // Store the vector to memory (because LValue wants an address).
1917    llvm::Value *VecMem = CreateMemTemp(E->getBase()->getType());
1918    Builder.CreateStore(Vec, VecMem);
1919    Base = MakeAddrLValue(VecMem, E->getBase()->getType());
1920  }
1921
1922  QualType type =
1923    E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
1924
1925  // Encode the element access list into a vector of unsigned indices.
1926  SmallVector<unsigned, 4> Indices;
1927  E->getEncodedElementAccess(Indices);
1928
1929  if (Base.isSimple()) {
1930    llvm::Constant *CV = GenerateConstantVector(Builder, Indices);
1931    return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
1932                                    Base.getAlignment());
1933  }
1934  assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
1935
1936  llvm::Constant *BaseElts = Base.getExtVectorElts();
1937  SmallVector<llvm::Constant *, 4> CElts;
1938
1939  for (unsigned i = 0, e = Indices.size(); i != e; ++i)
1940    CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
1941  llvm::Constant *CV = llvm::ConstantVector::get(CElts);
1942  return LValue::MakeExtVectorElt(Base.getExtVectorAddr(), CV, type,
1943                                  Base.getAlignment());
1944}
1945
1946LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
1947  Expr *BaseExpr = E->getBase();
1948
1949  // If this is s.x, emit s as an lvalue.  If it is s->x, emit s as a scalar.
1950  LValue BaseLV;
1951  if (E->isArrow())
1952    BaseLV = MakeNaturalAlignAddrLValue(EmitScalarExpr(BaseExpr),
1953                                        BaseExpr->getType()->getPointeeType());
1954  else
1955    BaseLV = EmitLValue(BaseExpr);
1956
1957  NamedDecl *ND = E->getMemberDecl();
1958  if (FieldDecl *Field = dyn_cast<FieldDecl>(ND)) {
1959    LValue LV = EmitLValueForField(BaseLV, Field);
1960    setObjCGCLValueClass(getContext(), E, LV);
1961    return LV;
1962  }
1963
1964  if (VarDecl *VD = dyn_cast<VarDecl>(ND))
1965    return EmitGlobalVarDeclLValue(*this, E, VD);
1966
1967  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
1968    return EmitFunctionDeclLValue(*this, E, FD);
1969
1970  llvm_unreachable("Unhandled member declaration!");
1971}
1972
1973LValue CodeGenFunction::EmitLValueForBitfield(llvm::Value *BaseValue,
1974                                              const FieldDecl *Field,
1975                                              unsigned CVRQualifiers) {
1976  const CGRecordLayout &RL =
1977    CGM.getTypes().getCGRecordLayout(Field->getParent());
1978  const CGBitFieldInfo &Info = RL.getBitFieldInfo(Field);
1979  return LValue::MakeBitfield(BaseValue, Info,
1980                          Field->getType().withCVRQualifiers(CVRQualifiers));
1981}
1982
1983/// EmitLValueForAnonRecordField - Given that the field is a member of
1984/// an anonymous struct or union buried inside a record, and given
1985/// that the base value is a pointer to the enclosing record, derive
1986/// an lvalue for the ultimate field.
1987LValue CodeGenFunction::EmitLValueForAnonRecordField(llvm::Value *BaseValue,
1988                                             const IndirectFieldDecl *Field,
1989                                                     unsigned CVRQualifiers) {
1990  IndirectFieldDecl::chain_iterator I = Field->chain_begin(),
1991    IEnd = Field->chain_end();
1992  while (true) {
1993    QualType RecordTy =
1994        getContext().getTypeDeclType(cast<FieldDecl>(*I)->getParent());
1995    LValue LV = EmitLValueForField(MakeAddrLValue(BaseValue, RecordTy),
1996                                   cast<FieldDecl>(*I));
1997    if (++I == IEnd) return LV;
1998
1999    assert(LV.isSimple());
2000    BaseValue = LV.getAddress();
2001    CVRQualifiers |= LV.getVRQualifiers();
2002  }
2003}
2004
2005LValue CodeGenFunction::EmitLValueForField(LValue base,
2006                                           const FieldDecl *field) {
2007  if (field->isBitField())
2008    return EmitLValueForBitfield(base.getAddress(), field,
2009                                 base.getVRQualifiers());
2010
2011  const RecordDecl *rec = field->getParent();
2012  QualType type = field->getType();
2013  CharUnits alignment = getContext().getDeclAlign(field);
2014
2015  // FIXME: It should be impossible to have an LValue without alignment for a
2016  // complete type.
2017  if (!base.getAlignment().isZero())
2018    alignment = std::min(alignment, base.getAlignment());
2019
2020  bool mayAlias = rec->hasAttr<MayAliasAttr>();
2021
2022  llvm::Value *addr = base.getAddress();
2023  unsigned cvr = base.getVRQualifiers();
2024  if (rec->isUnion()) {
2025    // For unions, there is no pointer adjustment.
2026    assert(!type->isReferenceType() && "union has reference member");
2027  } else {
2028    // For structs, we GEP to the field that the record layout suggests.
2029    unsigned idx = CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
2030    addr = Builder.CreateStructGEP(addr, idx, field->getName());
2031
2032    // If this is a reference field, load the reference right now.
2033    if (const ReferenceType *refType = type->getAs<ReferenceType>()) {
2034      llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
2035      if (cvr & Qualifiers::Volatile) load->setVolatile(true);
2036      load->setAlignment(alignment.getQuantity());
2037
2038      if (CGM.shouldUseTBAA()) {
2039        llvm::MDNode *tbaa;
2040        if (mayAlias)
2041          tbaa = CGM.getTBAAInfo(getContext().CharTy);
2042        else
2043          tbaa = CGM.getTBAAInfo(type);
2044        CGM.DecorateInstruction(load, tbaa);
2045      }
2046
2047      addr = load;
2048      mayAlias = false;
2049      type = refType->getPointeeType();
2050      if (type->isIncompleteType())
2051        alignment = CharUnits();
2052      else
2053        alignment = getContext().getTypeAlignInChars(type);
2054      cvr = 0; // qualifiers don't recursively apply to referencee
2055    }
2056  }
2057
2058  // Make sure that the address is pointing to the right type.  This is critical
2059  // for both unions and structs.  A union needs a bitcast, a struct element
2060  // will need a bitcast if the LLVM type laid out doesn't match the desired
2061  // type.
2062  addr = EmitBitCastOfLValueToProperType(*this, addr,
2063                                         CGM.getTypes().ConvertTypeForMem(type),
2064                                         field->getName());
2065
2066  if (field->hasAttr<AnnotateAttr>())
2067    addr = EmitFieldAnnotations(field, addr);
2068
2069  LValue LV = MakeAddrLValue(addr, type, alignment);
2070  LV.getQuals().addCVRQualifiers(cvr);
2071
2072  // __weak attribute on a field is ignored.
2073  if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
2074    LV.getQuals().removeObjCGCAttr();
2075
2076  // Fields of may_alias structs act like 'char' for TBAA purposes.
2077  // FIXME: this should get propagated down through anonymous structs
2078  // and unions.
2079  if (mayAlias && LV.getTBAAInfo())
2080    LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy));
2081
2082  return LV;
2083}
2084
2085LValue
2086CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
2087                                                  const FieldDecl *Field) {
2088  QualType FieldType = Field->getType();
2089
2090  if (!FieldType->isReferenceType())
2091    return EmitLValueForField(Base, Field);
2092
2093  const CGRecordLayout &RL =
2094    CGM.getTypes().getCGRecordLayout(Field->getParent());
2095  unsigned idx = RL.getLLVMFieldNo(Field);
2096  llvm::Value *V = Builder.CreateStructGEP(Base.getAddress(), idx);
2097  assert(!FieldType.getObjCGCAttr() && "fields cannot have GC attrs");
2098
2099  // Make sure that the address is pointing to the right type.  This is critical
2100  // for both unions and structs.  A union needs a bitcast, a struct element
2101  // will need a bitcast if the LLVM type laid out doesn't match the desired
2102  // type.
2103  llvm::Type *llvmType = ConvertTypeForMem(FieldType);
2104  V = EmitBitCastOfLValueToProperType(*this, V, llvmType, Field->getName());
2105
2106  CharUnits Alignment = getContext().getDeclAlign(Field);
2107
2108  // FIXME: It should be impossible to have an LValue without alignment for a
2109  // complete type.
2110  if (!Base.getAlignment().isZero())
2111    Alignment = std::min(Alignment, Base.getAlignment());
2112
2113  return MakeAddrLValue(V, FieldType, Alignment);
2114}
2115
2116LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
2117  if (E->isFileScope()) {
2118    llvm::Value *GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
2119    return MakeAddrLValue(GlobalPtr, E->getType());
2120  }
2121
2122  llvm::Value *DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
2123  const Expr *InitExpr = E->getInitializer();
2124  LValue Result = MakeAddrLValue(DeclPtr, E->getType());
2125
2126  EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
2127                   /*Init*/ true);
2128
2129  return Result;
2130}
2131
2132LValue CodeGenFunction::
2133EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
2134  if (!expr->isGLValue()) {
2135    // ?: here should be an aggregate.
2136    assert((hasAggregateLLVMType(expr->getType()) &&
2137            !expr->getType()->isAnyComplexType()) &&
2138           "Unexpected conditional operator!");
2139    return EmitAggExprToLValue(expr);
2140  }
2141
2142  OpaqueValueMapping binding(*this, expr);
2143
2144  const Expr *condExpr = expr->getCond();
2145  bool CondExprBool;
2146  if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
2147    const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
2148    if (!CondExprBool) std::swap(live, dead);
2149
2150    if (!ContainsLabel(dead))
2151      return EmitLValue(live);
2152  }
2153
2154  llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
2155  llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
2156  llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
2157
2158  ConditionalEvaluation eval(*this);
2159  EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock);
2160
2161  // Any temporaries created here are conditional.
2162  EmitBlock(lhsBlock);
2163  eval.begin(*this);
2164  LValue lhs = EmitLValue(expr->getTrueExpr());
2165  eval.end(*this);
2166
2167  if (!lhs.isSimple())
2168    return EmitUnsupportedLValue(expr, "conditional operator");
2169
2170  lhsBlock = Builder.GetInsertBlock();
2171  Builder.CreateBr(contBlock);
2172
2173  // Any temporaries created here are conditional.
2174  EmitBlock(rhsBlock);
2175  eval.begin(*this);
2176  LValue rhs = EmitLValue(expr->getFalseExpr());
2177  eval.end(*this);
2178  if (!rhs.isSimple())
2179    return EmitUnsupportedLValue(expr, "conditional operator");
2180  rhsBlock = Builder.GetInsertBlock();
2181
2182  EmitBlock(contBlock);
2183
2184  llvm::PHINode *phi = Builder.CreatePHI(lhs.getAddress()->getType(), 2,
2185                                         "cond-lvalue");
2186  phi->addIncoming(lhs.getAddress(), lhsBlock);
2187  phi->addIncoming(rhs.getAddress(), rhsBlock);
2188  return MakeAddrLValue(phi, expr->getType());
2189}
2190
2191/// EmitCastLValue - Casts are never lvalues unless that cast is a dynamic_cast.
2192/// If the cast is a dynamic_cast, we can have the usual lvalue result,
2193/// otherwise if a cast is needed by the code generator in an lvalue context,
2194/// then it must mean that we need the address of an aggregate in order to
2195/// access one of its fields.  This can happen for all the reasons that casts
2196/// are permitted with aggregate result, including noop aggregate casts, and
2197/// cast from scalar to union.
2198LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
2199  switch (E->getCastKind()) {
2200  case CK_ToVoid:
2201    return EmitUnsupportedLValue(E, "unexpected cast lvalue");
2202
2203  case CK_Dependent:
2204    llvm_unreachable("dependent cast kind in IR gen!");
2205
2206  // These two casts are currently treated as no-ops, although they could
2207  // potentially be real operations depending on the target's ABI.
2208  case CK_NonAtomicToAtomic:
2209  case CK_AtomicToNonAtomic:
2210
2211  case CK_NoOp:
2212  case CK_LValueToRValue:
2213    if (!E->getSubExpr()->Classify(getContext()).isPRValue()
2214        || E->getType()->isRecordType())
2215      return EmitLValue(E->getSubExpr());
2216    // Fall through to synthesize a temporary.
2217
2218  case CK_BitCast:
2219  case CK_ArrayToPointerDecay:
2220  case CK_FunctionToPointerDecay:
2221  case CK_NullToMemberPointer:
2222  case CK_NullToPointer:
2223  case CK_IntegralToPointer:
2224  case CK_PointerToIntegral:
2225  case CK_PointerToBoolean:
2226  case CK_VectorSplat:
2227  case CK_IntegralCast:
2228  case CK_IntegralToBoolean:
2229  case CK_IntegralToFloating:
2230  case CK_FloatingToIntegral:
2231  case CK_FloatingToBoolean:
2232  case CK_FloatingCast:
2233  case CK_FloatingRealToComplex:
2234  case CK_FloatingComplexToReal:
2235  case CK_FloatingComplexToBoolean:
2236  case CK_FloatingComplexCast:
2237  case CK_FloatingComplexToIntegralComplex:
2238  case CK_IntegralRealToComplex:
2239  case CK_IntegralComplexToReal:
2240  case CK_IntegralComplexToBoolean:
2241  case CK_IntegralComplexCast:
2242  case CK_IntegralComplexToFloatingComplex:
2243  case CK_DerivedToBaseMemberPointer:
2244  case CK_BaseToDerivedMemberPointer:
2245  case CK_MemberPointerToBoolean:
2246  case CK_ReinterpretMemberPointer:
2247  case CK_AnyPointerToBlockPointerCast:
2248  case CK_ARCProduceObject:
2249  case CK_ARCConsumeObject:
2250  case CK_ARCReclaimReturnedObject:
2251  case CK_ARCExtendBlockObject:
2252  case CK_CopyAndAutoreleaseBlockObject: {
2253    // These casts only produce lvalues when we're binding a reference to a
2254    // temporary realized from a (converted) pure rvalue. Emit the expression
2255    // as a value, copy it into a temporary, and return an lvalue referring to
2256    // that temporary.
2257    llvm::Value *V = CreateMemTemp(E->getType(), "ref.temp");
2258    EmitAnyExprToMem(E, V, E->getType().getQualifiers(), false);
2259    return MakeAddrLValue(V, E->getType());
2260  }
2261
2262  case CK_Dynamic: {
2263    LValue LV = EmitLValue(E->getSubExpr());
2264    llvm::Value *V = LV.getAddress();
2265    const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(E);
2266    return MakeAddrLValue(EmitDynamicCast(V, DCE), E->getType());
2267  }
2268
2269  case CK_ConstructorConversion:
2270  case CK_UserDefinedConversion:
2271  case CK_CPointerToObjCPointerCast:
2272  case CK_BlockPointerToObjCPointerCast:
2273    return EmitLValue(E->getSubExpr());
2274
2275  case CK_UncheckedDerivedToBase:
2276  case CK_DerivedToBase: {
2277    const RecordType *DerivedClassTy =
2278      E->getSubExpr()->getType()->getAs<RecordType>();
2279    CXXRecordDecl *DerivedClassDecl =
2280      cast<CXXRecordDecl>(DerivedClassTy->getDecl());
2281
2282    LValue LV = EmitLValue(E->getSubExpr());
2283    llvm::Value *This = LV.getAddress();
2284
2285    // Perform the derived-to-base conversion
2286    llvm::Value *Base =
2287      GetAddressOfBaseClass(This, DerivedClassDecl,
2288                            E->path_begin(), E->path_end(),
2289                            /*NullCheckValue=*/false);
2290
2291    return MakeAddrLValue(Base, E->getType());
2292  }
2293  case CK_ToUnion:
2294    return EmitAggExprToLValue(E);
2295  case CK_BaseToDerived: {
2296    const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
2297    CXXRecordDecl *DerivedClassDecl =
2298      cast<CXXRecordDecl>(DerivedClassTy->getDecl());
2299
2300    LValue LV = EmitLValue(E->getSubExpr());
2301
2302    // Perform the base-to-derived conversion
2303    llvm::Value *Derived =
2304      GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
2305                               E->path_begin(), E->path_end(),
2306                               /*NullCheckValue=*/false);
2307
2308    return MakeAddrLValue(Derived, E->getType());
2309  }
2310  case CK_LValueBitCast: {
2311    // This must be a reinterpret_cast (or c-style equivalent).
2312    const ExplicitCastExpr *CE = cast<ExplicitCastExpr>(E);
2313
2314    LValue LV = EmitLValue(E->getSubExpr());
2315    llvm::Value *V = Builder.CreateBitCast(LV.getAddress(),
2316                                           ConvertType(CE->getTypeAsWritten()));
2317    return MakeAddrLValue(V, E->getType());
2318  }
2319  case CK_ObjCObjectLValueCast: {
2320    LValue LV = EmitLValue(E->getSubExpr());
2321    QualType ToType = getContext().getLValueReferenceType(E->getType());
2322    llvm::Value *V = Builder.CreateBitCast(LV.getAddress(),
2323                                           ConvertType(ToType));
2324    return MakeAddrLValue(V, E->getType());
2325  }
2326  }
2327
2328  llvm_unreachable("Unhandled lvalue cast kind?");
2329}
2330
2331LValue CodeGenFunction::EmitNullInitializationLValue(
2332                                              const CXXScalarValueInitExpr *E) {
2333  QualType Ty = E->getType();
2334  LValue LV = MakeAddrLValue(CreateMemTemp(Ty), Ty);
2335  EmitNullInitialization(LV.getAddress(), Ty);
2336  return LV;
2337}
2338
2339LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
2340  assert(OpaqueValueMappingData::shouldBindAsLValue(e));
2341  return getOpaqueLValueMapping(e);
2342}
2343
2344LValue CodeGenFunction::EmitMaterializeTemporaryExpr(
2345                                           const MaterializeTemporaryExpr *E) {
2346  RValue RV = EmitReferenceBindingToExpr(E, /*InitializedDecl=*/0);
2347  return MakeAddrLValue(RV.getScalarVal(), E->getType());
2348}
2349
2350RValue CodeGenFunction::EmitRValueForField(LValue LV,
2351                                           const FieldDecl *FD) {
2352  QualType FT = FD->getType();
2353  LValue FieldLV = EmitLValueForField(LV, FD);
2354  if (FT->isAnyComplexType())
2355    return RValue::getComplex(
2356        LoadComplexFromAddr(FieldLV.getAddress(),
2357                            FieldLV.isVolatileQualified()));
2358  else if (CodeGenFunction::hasAggregateLLVMType(FT))
2359    return FieldLV.asAggregateRValue();
2360
2361  return EmitLoadOfLValue(FieldLV);
2362}
2363
2364//===--------------------------------------------------------------------===//
2365//                             Expression Emission
2366//===--------------------------------------------------------------------===//
2367
2368RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
2369                                     ReturnValueSlot ReturnValue) {
2370  if (CGDebugInfo *DI = getDebugInfo())
2371    DI->EmitLocation(Builder, E->getLocStart());
2372
2373  // Builtins never have block type.
2374  if (E->getCallee()->getType()->isBlockPointerType())
2375    return EmitBlockCallExpr(E, ReturnValue);
2376
2377  if (const CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(E))
2378    return EmitCXXMemberCallExpr(CE, ReturnValue);
2379
2380  if (const CUDAKernelCallExpr *CE = dyn_cast<CUDAKernelCallExpr>(E))
2381    return EmitCUDAKernelCallExpr(CE, ReturnValue);
2382
2383  const Decl *TargetDecl = E->getCalleeDecl();
2384  if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
2385    if (unsigned builtinID = FD->getBuiltinID())
2386      return EmitBuiltinExpr(FD, builtinID, E);
2387  }
2388
2389  if (const CXXOperatorCallExpr *CE = dyn_cast<CXXOperatorCallExpr>(E))
2390    if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(TargetDecl))
2391      return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
2392
2393  if (const CXXPseudoDestructorExpr *PseudoDtor
2394          = dyn_cast<CXXPseudoDestructorExpr>(E->getCallee()->IgnoreParens())) {
2395    QualType DestroyedType = PseudoDtor->getDestroyedType();
2396    if (getContext().getLangOpts().ObjCAutoRefCount &&
2397        DestroyedType->isObjCLifetimeType() &&
2398        (DestroyedType.getObjCLifetime() == Qualifiers::OCL_Strong ||
2399         DestroyedType.getObjCLifetime() == Qualifiers::OCL_Weak)) {
2400      // Automatic Reference Counting:
2401      //   If the pseudo-expression names a retainable object with weak or
2402      //   strong lifetime, the object shall be released.
2403      Expr *BaseExpr = PseudoDtor->getBase();
2404      llvm::Value *BaseValue = NULL;
2405      Qualifiers BaseQuals;
2406
2407      // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
2408      if (PseudoDtor->isArrow()) {
2409        BaseValue = EmitScalarExpr(BaseExpr);
2410        const PointerType *PTy = BaseExpr->getType()->getAs<PointerType>();
2411        BaseQuals = PTy->getPointeeType().getQualifiers();
2412      } else {
2413        LValue BaseLV = EmitLValue(BaseExpr);
2414        BaseValue = BaseLV.getAddress();
2415        QualType BaseTy = BaseExpr->getType();
2416        BaseQuals = BaseTy.getQualifiers();
2417      }
2418
2419      switch (PseudoDtor->getDestroyedType().getObjCLifetime()) {
2420      case Qualifiers::OCL_None:
2421      case Qualifiers::OCL_ExplicitNone:
2422      case Qualifiers::OCL_Autoreleasing:
2423        break;
2424
2425      case Qualifiers::OCL_Strong:
2426        EmitARCRelease(Builder.CreateLoad(BaseValue,
2427                          PseudoDtor->getDestroyedType().isVolatileQualified()),
2428                       /*precise*/ true);
2429        break;
2430
2431      case Qualifiers::OCL_Weak:
2432        EmitARCDestroyWeak(BaseValue);
2433        break;
2434      }
2435    } else {
2436      // C++ [expr.pseudo]p1:
2437      //   The result shall only be used as the operand for the function call
2438      //   operator (), and the result of such a call has type void. The only
2439      //   effect is the evaluation of the postfix-expression before the dot or
2440      //   arrow.
2441      EmitScalarExpr(E->getCallee());
2442    }
2443
2444    return RValue::get(0);
2445  }
2446
2447  llvm::Value *Callee = EmitScalarExpr(E->getCallee());
2448  return EmitCall(E->getCallee()->getType(), Callee, ReturnValue,
2449                  E->arg_begin(), E->arg_end(), TargetDecl);
2450}
2451
2452LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
2453  // Comma expressions just emit their LHS then their RHS as an l-value.
2454  if (E->getOpcode() == BO_Comma) {
2455    EmitIgnoredExpr(E->getLHS());
2456    EnsureInsertPoint();
2457    return EmitLValue(E->getRHS());
2458  }
2459
2460  if (E->getOpcode() == BO_PtrMemD ||
2461      E->getOpcode() == BO_PtrMemI)
2462    return EmitPointerToDataMemberBinaryExpr(E);
2463
2464  assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
2465
2466  // Note that in all of these cases, __block variables need the RHS
2467  // evaluated first just in case the variable gets moved by the RHS.
2468
2469  if (!hasAggregateLLVMType(E->getType())) {
2470    switch (E->getLHS()->getType().getObjCLifetime()) {
2471    case Qualifiers::OCL_Strong:
2472      return EmitARCStoreStrong(E, /*ignored*/ false).first;
2473
2474    case Qualifiers::OCL_Autoreleasing:
2475      return EmitARCStoreAutoreleasing(E).first;
2476
2477    // No reason to do any of these differently.
2478    case Qualifiers::OCL_None:
2479    case Qualifiers::OCL_ExplicitNone:
2480    case Qualifiers::OCL_Weak:
2481      break;
2482    }
2483
2484    RValue RV = EmitAnyExpr(E->getRHS());
2485    LValue LV = EmitLValue(E->getLHS());
2486    EmitStoreThroughLValue(RV, LV);
2487    return LV;
2488  }
2489
2490  if (E->getType()->isAnyComplexType())
2491    return EmitComplexAssignmentLValue(E);
2492
2493  return EmitAggExprToLValue(E);
2494}
2495
2496LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
2497  RValue RV = EmitCallExpr(E);
2498
2499  if (!RV.isScalar())
2500    return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
2501
2502  assert(E->getCallReturnType()->isReferenceType() &&
2503         "Can't have a scalar return unless the return type is a "
2504         "reference type!");
2505
2506  return MakeAddrLValue(RV.getScalarVal(), E->getType());
2507}
2508
2509LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
2510  // FIXME: This shouldn't require another copy.
2511  return EmitAggExprToLValue(E);
2512}
2513
2514LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
2515  assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
2516         && "binding l-value to type which needs a temporary");
2517  AggValueSlot Slot = CreateAggTemp(E->getType());
2518  EmitCXXConstructExpr(E, Slot);
2519  return MakeAddrLValue(Slot.getAddr(), E->getType());
2520}
2521
2522LValue
2523CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
2524  return MakeAddrLValue(EmitCXXTypeidExpr(E), E->getType());
2525}
2526
2527LValue
2528CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
2529  AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
2530  Slot.setExternallyDestructed();
2531  EmitAggExpr(E->getSubExpr(), Slot);
2532  EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddr());
2533  return MakeAddrLValue(Slot.getAddr(), E->getType());
2534}
2535
2536LValue
2537CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
2538  AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
2539  EmitLambdaExpr(E, Slot);
2540  return MakeAddrLValue(Slot.getAddr(), E->getType());
2541}
2542
2543LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
2544  RValue RV = EmitObjCMessageExpr(E);
2545
2546  if (!RV.isScalar())
2547    return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
2548
2549  assert(E->getMethodDecl()->getResultType()->isReferenceType() &&
2550         "Can't have a scalar return unless the return type is a "
2551         "reference type!");
2552
2553  return MakeAddrLValue(RV.getScalarVal(), E->getType());
2554}
2555
2556LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
2557  llvm::Value *V =
2558    CGM.getObjCRuntime().GetSelector(Builder, E->getSelector(), true);
2559  return MakeAddrLValue(V, E->getType());
2560}
2561
2562llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
2563                                             const ObjCIvarDecl *Ivar) {
2564  return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
2565}
2566
2567LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
2568                                          llvm::Value *BaseValue,
2569                                          const ObjCIvarDecl *Ivar,
2570                                          unsigned CVRQualifiers) {
2571  return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
2572                                                   Ivar, CVRQualifiers);
2573}
2574
2575LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
2576  // FIXME: A lot of the code below could be shared with EmitMemberExpr.
2577  llvm::Value *BaseValue = 0;
2578  const Expr *BaseExpr = E->getBase();
2579  Qualifiers BaseQuals;
2580  QualType ObjectTy;
2581  if (E->isArrow()) {
2582    BaseValue = EmitScalarExpr(BaseExpr);
2583    ObjectTy = BaseExpr->getType()->getPointeeType();
2584    BaseQuals = ObjectTy.getQualifiers();
2585  } else {
2586    LValue BaseLV = EmitLValue(BaseExpr);
2587    // FIXME: this isn't right for bitfields.
2588    BaseValue = BaseLV.getAddress();
2589    ObjectTy = BaseExpr->getType();
2590    BaseQuals = ObjectTy.getQualifiers();
2591  }
2592
2593  LValue LV =
2594    EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
2595                      BaseQuals.getCVRQualifiers());
2596  setObjCGCLValueClass(getContext(), E, LV);
2597  return LV;
2598}
2599
2600LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
2601  // Can only get l-value for message expression returning aggregate type
2602  RValue RV = EmitAnyExprToTemp(E);
2603  return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
2604}
2605
2606RValue CodeGenFunction::EmitCall(QualType CalleeType, llvm::Value *Callee,
2607                                 ReturnValueSlot ReturnValue,
2608                                 CallExpr::const_arg_iterator ArgBeg,
2609                                 CallExpr::const_arg_iterator ArgEnd,
2610                                 const Decl *TargetDecl) {
2611  // Get the actual function type. The callee type will always be a pointer to
2612  // function type or a block pointer type.
2613  assert(CalleeType->isFunctionPointerType() &&
2614         "Call must have function pointer type!");
2615
2616  CalleeType = getContext().getCanonicalType(CalleeType);
2617
2618  const FunctionType *FnType
2619    = cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
2620
2621  CallArgList Args;
2622  EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), ArgBeg, ArgEnd);
2623
2624  const CGFunctionInfo &FnInfo =
2625    CGM.getTypes().arrangeFunctionCall(Args, FnType);
2626
2627  // C99 6.5.2.2p6:
2628  //   If the expression that denotes the called function has a type
2629  //   that does not include a prototype, [the default argument
2630  //   promotions are performed]. If the number of arguments does not
2631  //   equal the number of parameters, the behavior is undefined. If
2632  //   the function is defined with a type that includes a prototype,
2633  //   and either the prototype ends with an ellipsis (, ...) or the
2634  //   types of the arguments after promotion are not compatible with
2635  //   the types of the parameters, the behavior is undefined. If the
2636  //   function is defined with a type that does not include a
2637  //   prototype, and the types of the arguments after promotion are
2638  //   not compatible with those of the parameters after promotion,
2639  //   the behavior is undefined [except in some trivial cases].
2640  // That is, in the general case, we should assume that a call
2641  // through an unprototyped function type works like a *non-variadic*
2642  // call.  The way we make this work is to cast to the exact type
2643  // of the promoted arguments.
2644  if (isa<FunctionNoProtoType>(FnType) && !FnInfo.isVariadic()) {
2645    llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
2646    CalleeTy = CalleeTy->getPointerTo();
2647    Callee = Builder.CreateBitCast(Callee, CalleeTy, "callee.knr.cast");
2648  }
2649
2650  return EmitCall(FnInfo, Callee, ReturnValue, Args, TargetDecl);
2651}
2652
2653LValue CodeGenFunction::
2654EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
2655  llvm::Value *BaseV;
2656  if (E->getOpcode() == BO_PtrMemI)
2657    BaseV = EmitScalarExpr(E->getLHS());
2658  else
2659    BaseV = EmitLValue(E->getLHS()).getAddress();
2660
2661  llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
2662
2663  const MemberPointerType *MPT
2664    = E->getRHS()->getType()->getAs<MemberPointerType>();
2665
2666  llvm::Value *AddV =
2667    CGM.getCXXABI().EmitMemberDataPointerAddress(*this, BaseV, OffsetV, MPT);
2668
2669  return MakeAddrLValue(AddV, MPT->getPointeeType());
2670}
2671
2672static void
2673EmitAtomicOp(CodeGenFunction &CGF, AtomicExpr *E, llvm::Value *Dest,
2674             llvm::Value *Ptr, llvm::Value *Val1, llvm::Value *Val2,
2675             uint64_t Size, unsigned Align, llvm::AtomicOrdering Order) {
2676  llvm::AtomicRMWInst::BinOp Op = llvm::AtomicRMWInst::Add;
2677  llvm::Instruction::BinaryOps PostOp = (llvm::Instruction::BinaryOps)0;
2678
2679  switch (E->getOp()) {
2680  case AtomicExpr::AO__c11_atomic_init:
2681    llvm_unreachable("Already handled!");
2682
2683  case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2684  case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2685  case AtomicExpr::AO__atomic_compare_exchange:
2686  case AtomicExpr::AO__atomic_compare_exchange_n: {
2687    // Note that cmpxchg only supports specifying one ordering and
2688    // doesn't support weak cmpxchg, at least at the moment.
2689    llvm::LoadInst *LoadVal1 = CGF.Builder.CreateLoad(Val1);
2690    LoadVal1->setAlignment(Align);
2691    llvm::LoadInst *LoadVal2 = CGF.Builder.CreateLoad(Val2);
2692    LoadVal2->setAlignment(Align);
2693    llvm::AtomicCmpXchgInst *CXI =
2694        CGF.Builder.CreateAtomicCmpXchg(Ptr, LoadVal1, LoadVal2, Order);
2695    CXI->setVolatile(E->isVolatile());
2696    llvm::StoreInst *StoreVal1 = CGF.Builder.CreateStore(CXI, Val1);
2697    StoreVal1->setAlignment(Align);
2698    llvm::Value *Cmp = CGF.Builder.CreateICmpEQ(CXI, LoadVal1);
2699    CGF.EmitStoreOfScalar(Cmp, CGF.MakeAddrLValue(Dest, E->getType()));
2700    return;
2701  }
2702
2703  case AtomicExpr::AO__c11_atomic_load:
2704  case AtomicExpr::AO__atomic_load_n:
2705  case AtomicExpr::AO__atomic_load: {
2706    llvm::LoadInst *Load = CGF.Builder.CreateLoad(Ptr);
2707    Load->setAtomic(Order);
2708    Load->setAlignment(Size);
2709    Load->setVolatile(E->isVolatile());
2710    llvm::StoreInst *StoreDest = CGF.Builder.CreateStore(Load, Dest);
2711    StoreDest->setAlignment(Align);
2712    return;
2713  }
2714
2715  case AtomicExpr::AO__c11_atomic_store:
2716  case AtomicExpr::AO__atomic_store:
2717  case AtomicExpr::AO__atomic_store_n: {
2718    assert(!Dest && "Store does not return a value");
2719    llvm::LoadInst *LoadVal1 = CGF.Builder.CreateLoad(Val1);
2720    LoadVal1->setAlignment(Align);
2721    llvm::StoreInst *Store = CGF.Builder.CreateStore(LoadVal1, Ptr);
2722    Store->setAtomic(Order);
2723    Store->setAlignment(Size);
2724    Store->setVolatile(E->isVolatile());
2725    return;
2726  }
2727
2728  case AtomicExpr::AO__c11_atomic_exchange:
2729  case AtomicExpr::AO__atomic_exchange_n:
2730  case AtomicExpr::AO__atomic_exchange:
2731    Op = llvm::AtomicRMWInst::Xchg;
2732    break;
2733
2734  case AtomicExpr::AO__atomic_add_fetch:
2735    PostOp = llvm::Instruction::Add;
2736    // Fall through.
2737  case AtomicExpr::AO__c11_atomic_fetch_add:
2738  case AtomicExpr::AO__atomic_fetch_add:
2739    Op = llvm::AtomicRMWInst::Add;
2740    break;
2741
2742  case AtomicExpr::AO__atomic_sub_fetch:
2743    PostOp = llvm::Instruction::Sub;
2744    // Fall through.
2745  case AtomicExpr::AO__c11_atomic_fetch_sub:
2746  case AtomicExpr::AO__atomic_fetch_sub:
2747    Op = llvm::AtomicRMWInst::Sub;
2748    break;
2749
2750  case AtomicExpr::AO__atomic_and_fetch:
2751    PostOp = llvm::Instruction::And;
2752    // Fall through.
2753  case AtomicExpr::AO__c11_atomic_fetch_and:
2754  case AtomicExpr::AO__atomic_fetch_and:
2755    Op = llvm::AtomicRMWInst::And;
2756    break;
2757
2758  case AtomicExpr::AO__atomic_or_fetch:
2759    PostOp = llvm::Instruction::Or;
2760    // Fall through.
2761  case AtomicExpr::AO__c11_atomic_fetch_or:
2762  case AtomicExpr::AO__atomic_fetch_or:
2763    Op = llvm::AtomicRMWInst::Or;
2764    break;
2765
2766  case AtomicExpr::AO__atomic_xor_fetch:
2767    PostOp = llvm::Instruction::Xor;
2768    // Fall through.
2769  case AtomicExpr::AO__c11_atomic_fetch_xor:
2770  case AtomicExpr::AO__atomic_fetch_xor:
2771    Op = llvm::AtomicRMWInst::Xor;
2772    break;
2773
2774  case AtomicExpr::AO__atomic_nand_fetch:
2775    PostOp = llvm::Instruction::And;
2776    // Fall through.
2777  case AtomicExpr::AO__atomic_fetch_nand:
2778    Op = llvm::AtomicRMWInst::Nand;
2779    break;
2780  }
2781
2782  llvm::LoadInst *LoadVal1 = CGF.Builder.CreateLoad(Val1);
2783  LoadVal1->setAlignment(Align);
2784  llvm::AtomicRMWInst *RMWI =
2785      CGF.Builder.CreateAtomicRMW(Op, Ptr, LoadVal1, Order);
2786  RMWI->setVolatile(E->isVolatile());
2787
2788  // For __atomic_*_fetch operations, perform the operation again to
2789  // determine the value which was written.
2790  llvm::Value *Result = RMWI;
2791  if (PostOp)
2792    Result = CGF.Builder.CreateBinOp(PostOp, RMWI, LoadVal1);
2793  if (E->getOp() == AtomicExpr::AO__atomic_nand_fetch)
2794    Result = CGF.Builder.CreateNot(Result);
2795  llvm::StoreInst *StoreDest = CGF.Builder.CreateStore(Result, Dest);
2796  StoreDest->setAlignment(Align);
2797}
2798
2799// This function emits any expression (scalar, complex, or aggregate)
2800// into a temporary alloca.
2801static llvm::Value *
2802EmitValToTemp(CodeGenFunction &CGF, Expr *E) {
2803  llvm::Value *DeclPtr = CGF.CreateMemTemp(E->getType(), ".atomictmp");
2804  CGF.EmitAnyExprToMem(E, DeclPtr, E->getType().getQualifiers(),
2805                       /*Init*/ true);
2806  return DeclPtr;
2807}
2808
2809static RValue ConvertTempToRValue(CodeGenFunction &CGF, QualType Ty,
2810                                  llvm::Value *Dest) {
2811  if (Ty->isAnyComplexType())
2812    return RValue::getComplex(CGF.LoadComplexFromAddr(Dest, false));
2813  if (CGF.hasAggregateLLVMType(Ty))
2814    return RValue::getAggregate(Dest);
2815  return RValue::get(CGF.EmitLoadOfScalar(CGF.MakeAddrLValue(Dest, Ty)));
2816}
2817
2818RValue CodeGenFunction::EmitAtomicExpr(AtomicExpr *E, llvm::Value *Dest) {
2819  QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
2820  QualType MemTy = AtomicTy;
2821  if (const AtomicType *AT = AtomicTy->getAs<AtomicType>())
2822    MemTy = AT->getValueType();
2823  CharUnits sizeChars = getContext().getTypeSizeInChars(AtomicTy);
2824  uint64_t Size = sizeChars.getQuantity();
2825  CharUnits alignChars = getContext().getTypeAlignInChars(AtomicTy);
2826  unsigned Align = alignChars.getQuantity();
2827  unsigned MaxInlineWidth =
2828      getContext().getTargetInfo().getMaxAtomicInlineWidth();
2829  bool UseLibcall = (Size != Align || Size > MaxInlineWidth);
2830
2831
2832
2833  llvm::Value *Ptr, *Order, *OrderFail = 0, *Val1 = 0, *Val2 = 0;
2834  Ptr = EmitScalarExpr(E->getPtr());
2835
2836  if (E->getOp() == AtomicExpr::AO__c11_atomic_init) {
2837    assert(!Dest && "Init does not return a value");
2838    if (!hasAggregateLLVMType(E->getVal1()->getType())) {
2839      QualType PointeeType
2840        = E->getPtr()->getType()->getAs<PointerType>()->getPointeeType();
2841      EmitScalarInit(EmitScalarExpr(E->getVal1()),
2842                     LValue::MakeAddr(Ptr, PointeeType, alignChars,
2843                                      getContext()));
2844    } else if (E->getType()->isAnyComplexType()) {
2845      EmitComplexExprIntoAddr(E->getVal1(), Ptr, E->isVolatile());
2846    } else {
2847      AggValueSlot Slot = AggValueSlot::forAddr(Ptr, alignChars,
2848                                        AtomicTy.getQualifiers(),
2849                                        AggValueSlot::IsNotDestructed,
2850                                        AggValueSlot::DoesNotNeedGCBarriers,
2851                                        AggValueSlot::IsNotAliased);
2852      EmitAggExpr(E->getVal1(), Slot);
2853    }
2854    return RValue::get(0);
2855  }
2856
2857  Order = EmitScalarExpr(E->getOrder());
2858
2859  switch (E->getOp()) {
2860  case AtomicExpr::AO__c11_atomic_init:
2861    llvm_unreachable("Already handled!");
2862
2863  case AtomicExpr::AO__c11_atomic_load:
2864  case AtomicExpr::AO__atomic_load_n:
2865    break;
2866
2867  case AtomicExpr::AO__atomic_load:
2868    Dest = EmitScalarExpr(E->getVal1());
2869    break;
2870
2871  case AtomicExpr::AO__atomic_store:
2872    Val1 = EmitScalarExpr(E->getVal1());
2873    break;
2874
2875  case AtomicExpr::AO__atomic_exchange:
2876    Val1 = EmitScalarExpr(E->getVal1());
2877    Dest = EmitScalarExpr(E->getVal2());
2878    break;
2879
2880  case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2881  case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2882  case AtomicExpr::AO__atomic_compare_exchange_n:
2883  case AtomicExpr::AO__atomic_compare_exchange:
2884    Val1 = EmitScalarExpr(E->getVal1());
2885    if (E->getOp() == AtomicExpr::AO__atomic_compare_exchange)
2886      Val2 = EmitScalarExpr(E->getVal2());
2887    else
2888      Val2 = EmitValToTemp(*this, E->getVal2());
2889    OrderFail = EmitScalarExpr(E->getOrderFail());
2890    // Evaluate and discard the 'weak' argument.
2891    if (E->getNumSubExprs() == 6)
2892      EmitScalarExpr(E->getWeak());
2893    break;
2894
2895  case AtomicExpr::AO__c11_atomic_fetch_add:
2896  case AtomicExpr::AO__c11_atomic_fetch_sub:
2897    if (MemTy->isPointerType()) {
2898      // For pointer arithmetic, we're required to do a bit of math:
2899      // adding 1 to an int* is not the same as adding 1 to a uintptr_t.
2900      // ... but only for the C11 builtins. The GNU builtins expect the
2901      // user to multiply by sizeof(T).
2902      QualType Val1Ty = E->getVal1()->getType();
2903      llvm::Value *Val1Scalar = EmitScalarExpr(E->getVal1());
2904      CharUnits PointeeIncAmt =
2905          getContext().getTypeSizeInChars(MemTy->getPointeeType());
2906      Val1Scalar = Builder.CreateMul(Val1Scalar, CGM.getSize(PointeeIncAmt));
2907      Val1 = CreateMemTemp(Val1Ty, ".atomictmp");
2908      EmitStoreOfScalar(Val1Scalar, MakeAddrLValue(Val1, Val1Ty));
2909      break;
2910    }
2911    // Fall through.
2912  case AtomicExpr::AO__atomic_fetch_add:
2913  case AtomicExpr::AO__atomic_fetch_sub:
2914  case AtomicExpr::AO__atomic_add_fetch:
2915  case AtomicExpr::AO__atomic_sub_fetch:
2916  case AtomicExpr::AO__c11_atomic_store:
2917  case AtomicExpr::AO__c11_atomic_exchange:
2918  case AtomicExpr::AO__atomic_store_n:
2919  case AtomicExpr::AO__atomic_exchange_n:
2920  case AtomicExpr::AO__c11_atomic_fetch_and:
2921  case AtomicExpr::AO__c11_atomic_fetch_or:
2922  case AtomicExpr::AO__c11_atomic_fetch_xor:
2923  case AtomicExpr::AO__atomic_fetch_and:
2924  case AtomicExpr::AO__atomic_fetch_or:
2925  case AtomicExpr::AO__atomic_fetch_xor:
2926  case AtomicExpr::AO__atomic_fetch_nand:
2927  case AtomicExpr::AO__atomic_and_fetch:
2928  case AtomicExpr::AO__atomic_or_fetch:
2929  case AtomicExpr::AO__atomic_xor_fetch:
2930  case AtomicExpr::AO__atomic_nand_fetch:
2931    Val1 = EmitValToTemp(*this, E->getVal1());
2932    break;
2933  }
2934
2935  if (!E->getType()->isVoidType() && !Dest)
2936    Dest = CreateMemTemp(E->getType(), ".atomicdst");
2937
2938  // Use a library call.  See: http://gcc.gnu.org/wiki/Atomic/GCCMM/LIbrary .
2939  if (UseLibcall) {
2940
2941    llvm::SmallVector<QualType, 5> Params;
2942    CallArgList Args;
2943    // Size is always the first parameter
2944    Args.add(RValue::get(llvm::ConstantInt::get(SizeTy, Size)),
2945             getContext().getSizeType());
2946    // Atomic address is always the second parameter
2947    Args.add(RValue::get(EmitCastToVoidPtr(Ptr)),
2948             getContext().VoidPtrTy);
2949
2950    const char* LibCallName;
2951    QualType RetTy = getContext().VoidTy;
2952    switch (E->getOp()) {
2953    // There is only one libcall for compare an exchange, because there is no
2954    // optimisation benefit possible from a libcall version of a weak compare
2955    // and exchange.
2956    // bool __atomic_compare_exchange(size_t size, void *obj, void *expected,
2957    //                                void *desired, int success, int failure)
2958    case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2959    case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2960    case AtomicExpr::AO__atomic_compare_exchange:
2961    case AtomicExpr::AO__atomic_compare_exchange_n:
2962      LibCallName = "__atomic_compare_exchange";
2963      RetTy = getContext().BoolTy;
2964      Args.add(RValue::get(EmitCastToVoidPtr(Val1)),
2965               getContext().VoidPtrTy);
2966      Args.add(RValue::get(EmitCastToVoidPtr(Val2)),
2967               getContext().VoidPtrTy);
2968      Args.add(RValue::get(Order),
2969               getContext().IntTy);
2970      Order = OrderFail;
2971      break;
2972    // void __atomic_exchange(size_t size, void *mem, void *val, void *return,
2973    //                        int order)
2974    case AtomicExpr::AO__c11_atomic_exchange:
2975    case AtomicExpr::AO__atomic_exchange_n:
2976    case AtomicExpr::AO__atomic_exchange:
2977      LibCallName = "__atomic_exchange";
2978      Args.add(RValue::get(EmitCastToVoidPtr(Val1)),
2979               getContext().VoidPtrTy);
2980      Args.add(RValue::get(EmitCastToVoidPtr(Dest)),
2981               getContext().VoidPtrTy);
2982      break;
2983    // void __atomic_store(size_t size, void *mem, void *val, int order)
2984    case AtomicExpr::AO__c11_atomic_store:
2985    case AtomicExpr::AO__atomic_store:
2986    case AtomicExpr::AO__atomic_store_n:
2987      LibCallName = "__atomic_store";
2988      Args.add(RValue::get(EmitCastToVoidPtr(Val1)),
2989               getContext().VoidPtrTy);
2990      break;
2991    // void __atomic_load(size_t size, void *mem, void *return, int order)
2992    case AtomicExpr::AO__c11_atomic_load:
2993    case AtomicExpr::AO__atomic_load:
2994    case AtomicExpr::AO__atomic_load_n:
2995      LibCallName = "__atomic_load";
2996      Args.add(RValue::get(EmitCastToVoidPtr(Dest)),
2997               getContext().VoidPtrTy);
2998      break;
2999#if 0
3000    // These are only defined for 1-16 byte integers.  It is not clear what
3001    // their semantics would be on anything else...
3002    case AtomicExpr::Add:   LibCallName = "__atomic_fetch_add_generic"; break;
3003    case AtomicExpr::Sub:   LibCallName = "__atomic_fetch_sub_generic"; break;
3004    case AtomicExpr::And:   LibCallName = "__atomic_fetch_and_generic"; break;
3005    case AtomicExpr::Or:    LibCallName = "__atomic_fetch_or_generic"; break;
3006    case AtomicExpr::Xor:   LibCallName = "__atomic_fetch_xor_generic"; break;
3007#endif
3008    default: return EmitUnsupportedRValue(E, "atomic library call");
3009    }
3010    // order is always the last parameter
3011    Args.add(RValue::get(Order),
3012             getContext().IntTy);
3013
3014    const CGFunctionInfo &FuncInfo =
3015        CGM.getTypes().arrangeFunctionCall(RetTy, Args,
3016            FunctionType::ExtInfo(), RequiredArgs::All);
3017    llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FuncInfo);
3018    llvm::Constant *Func = CGM.CreateRuntimeFunction(FTy, LibCallName);
3019    RValue Res = EmitCall(FuncInfo, Func, ReturnValueSlot(), Args);
3020    if (E->isCmpXChg())
3021      return Res;
3022    if (E->getType()->isVoidType())
3023      return RValue::get(0);
3024    return ConvertTempToRValue(*this, E->getType(), Dest);
3025  }
3026
3027  llvm::Type *IPtrTy =
3028      llvm::IntegerType::get(getLLVMContext(), Size * 8)->getPointerTo();
3029  llvm::Value *OrigDest = Dest;
3030  Ptr = Builder.CreateBitCast(Ptr, IPtrTy);
3031  if (Val1) Val1 = Builder.CreateBitCast(Val1, IPtrTy);
3032  if (Val2) Val2 = Builder.CreateBitCast(Val2, IPtrTy);
3033  if (Dest && !E->isCmpXChg()) Dest = Builder.CreateBitCast(Dest, IPtrTy);
3034
3035  if (isa<llvm::ConstantInt>(Order)) {
3036    int ord = cast<llvm::ConstantInt>(Order)->getZExtValue();
3037    switch (ord) {
3038    case 0:  // memory_order_relaxed
3039      EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3040                   llvm::Monotonic);
3041      break;
3042    case 1:  // memory_order_consume
3043    case 2:  // memory_order_acquire
3044      EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3045                   llvm::Acquire);
3046      break;
3047    case 3:  // memory_order_release
3048      EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3049                   llvm::Release);
3050      break;
3051    case 4:  // memory_order_acq_rel
3052      EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3053                   llvm::AcquireRelease);
3054      break;
3055    case 5:  // memory_order_seq_cst
3056      EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3057                   llvm::SequentiallyConsistent);
3058      break;
3059    default: // invalid order
3060      // We should not ever get here normally, but it's hard to
3061      // enforce that in general.
3062      break;
3063    }
3064    if (E->getType()->isVoidType())
3065      return RValue::get(0);
3066    return ConvertTempToRValue(*this, E->getType(), OrigDest);
3067  }
3068
3069  // Long case, when Order isn't obviously constant.
3070
3071  bool IsStore = E->getOp() == AtomicExpr::AO__c11_atomic_store ||
3072                 E->getOp() == AtomicExpr::AO__atomic_store ||
3073                 E->getOp() == AtomicExpr::AO__atomic_store_n;
3074  bool IsLoad = E->getOp() == AtomicExpr::AO__c11_atomic_load ||
3075                E->getOp() == AtomicExpr::AO__atomic_load ||
3076                E->getOp() == AtomicExpr::AO__atomic_load_n;
3077
3078  // Create all the relevant BB's
3079  llvm::BasicBlock *MonotonicBB = 0, *AcquireBB = 0, *ReleaseBB = 0,
3080                   *AcqRelBB = 0, *SeqCstBB = 0;
3081  MonotonicBB = createBasicBlock("monotonic", CurFn);
3082  if (!IsStore)
3083    AcquireBB = createBasicBlock("acquire", CurFn);
3084  if (!IsLoad)
3085    ReleaseBB = createBasicBlock("release", CurFn);
3086  if (!IsLoad && !IsStore)
3087    AcqRelBB = createBasicBlock("acqrel", CurFn);
3088  SeqCstBB = createBasicBlock("seqcst", CurFn);
3089  llvm::BasicBlock *ContBB = createBasicBlock("atomic.continue", CurFn);
3090
3091  // Create the switch for the split
3092  // MonotonicBB is arbitrarily chosen as the default case; in practice, this
3093  // doesn't matter unless someone is crazy enough to use something that
3094  // doesn't fold to a constant for the ordering.
3095  Order = Builder.CreateIntCast(Order, Builder.getInt32Ty(), false);
3096  llvm::SwitchInst *SI = Builder.CreateSwitch(Order, MonotonicBB);
3097
3098  // Emit all the different atomics
3099  Builder.SetInsertPoint(MonotonicBB);
3100  EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3101               llvm::Monotonic);
3102  Builder.CreateBr(ContBB);
3103  if (!IsStore) {
3104    Builder.SetInsertPoint(AcquireBB);
3105    EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3106                 llvm::Acquire);
3107    Builder.CreateBr(ContBB);
3108    SI->addCase(Builder.getInt32(1), AcquireBB);
3109    SI->addCase(Builder.getInt32(2), AcquireBB);
3110  }
3111  if (!IsLoad) {
3112    Builder.SetInsertPoint(ReleaseBB);
3113    EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3114                 llvm::Release);
3115    Builder.CreateBr(ContBB);
3116    SI->addCase(Builder.getInt32(3), ReleaseBB);
3117  }
3118  if (!IsLoad && !IsStore) {
3119    Builder.SetInsertPoint(AcqRelBB);
3120    EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3121                 llvm::AcquireRelease);
3122    Builder.CreateBr(ContBB);
3123    SI->addCase(Builder.getInt32(4), AcqRelBB);
3124  }
3125  Builder.SetInsertPoint(SeqCstBB);
3126  EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3127               llvm::SequentiallyConsistent);
3128  Builder.CreateBr(ContBB);
3129  SI->addCase(Builder.getInt32(5), SeqCstBB);
3130
3131  // Cleanup and return
3132  Builder.SetInsertPoint(ContBB);
3133  if (E->getType()->isVoidType())
3134    return RValue::get(0);
3135  return ConvertTempToRValue(*this, E->getType(), OrigDest);
3136}
3137
3138void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
3139  assert(Val->getType()->isFPOrFPVectorTy());
3140  if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
3141    return;
3142
3143  llvm::MDBuilder MDHelper(getLLVMContext());
3144  llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
3145
3146  cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
3147}
3148
3149namespace {
3150  struct LValueOrRValue {
3151    LValue LV;
3152    RValue RV;
3153  };
3154}
3155
3156static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
3157                                           const PseudoObjectExpr *E,
3158                                           bool forLValue,
3159                                           AggValueSlot slot) {
3160  llvm::SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
3161
3162  // Find the result expression, if any.
3163  const Expr *resultExpr = E->getResultExpr();
3164  LValueOrRValue result;
3165
3166  for (PseudoObjectExpr::const_semantics_iterator
3167         i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
3168    const Expr *semantic = *i;
3169
3170    // If this semantic expression is an opaque value, bind it
3171    // to the result of its source expression.
3172    if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
3173
3174      // If this is the result expression, we may need to evaluate
3175      // directly into the slot.
3176      typedef CodeGenFunction::OpaqueValueMappingData OVMA;
3177      OVMA opaqueData;
3178      if (ov == resultExpr && ov->isRValue() && !forLValue &&
3179          CodeGenFunction::hasAggregateLLVMType(ov->getType()) &&
3180          !ov->getType()->isAnyComplexType()) {
3181        CGF.EmitAggExpr(ov->getSourceExpr(), slot);
3182
3183        LValue LV = CGF.MakeAddrLValue(slot.getAddr(), ov->getType());
3184        opaqueData = OVMA::bind(CGF, ov, LV);
3185        result.RV = slot.asRValue();
3186
3187      // Otherwise, emit as normal.
3188      } else {
3189        opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
3190
3191        // If this is the result, also evaluate the result now.
3192        if (ov == resultExpr) {
3193          if (forLValue)
3194            result.LV = CGF.EmitLValue(ov);
3195          else
3196            result.RV = CGF.EmitAnyExpr(ov, slot);
3197        }
3198      }
3199
3200      opaques.push_back(opaqueData);
3201
3202    // Otherwise, if the expression is the result, evaluate it
3203    // and remember the result.
3204    } else if (semantic == resultExpr) {
3205      if (forLValue)
3206        result.LV = CGF.EmitLValue(semantic);
3207      else
3208        result.RV = CGF.EmitAnyExpr(semantic, slot);
3209
3210    // Otherwise, evaluate the expression in an ignored context.
3211    } else {
3212      CGF.EmitIgnoredExpr(semantic);
3213    }
3214  }
3215
3216  // Unbind all the opaques now.
3217  for (unsigned i = 0, e = opaques.size(); i != e; ++i)
3218    opaques[i].unbind(CGF);
3219
3220  return result;
3221}
3222
3223RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
3224                                               AggValueSlot slot) {
3225  return emitPseudoObjectExpr(*this, E, false, slot).RV;
3226}
3227
3228LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
3229  return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
3230}
3231