CGExpr.cpp 109 KB

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