CGObjC.cpp 114 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022
  1. //===---- CGBuiltin.cpp - Emit LLVM Code for builtins ---------------------===//
  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 Objective-C code as LLVM code.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CGDebugInfo.h"
  14. #include "CGObjCRuntime.h"
  15. #include "CodeGenFunction.h"
  16. #include "CodeGenModule.h"
  17. #include "TargetInfo.h"
  18. #include "clang/AST/ASTContext.h"
  19. #include "clang/AST/DeclObjC.h"
  20. #include "clang/AST/StmtObjC.h"
  21. #include "clang/Basic/Diagnostic.h"
  22. #include "llvm/ADT/STLExtras.h"
  23. #include "llvm/IR/DataLayout.h"
  24. #include "llvm/IR/InlineAsm.h"
  25. using namespace clang;
  26. using namespace CodeGen;
  27. typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult;
  28. static TryEmitResult
  29. tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e);
  30. static RValue AdjustRelatedResultType(CodeGenFunction &CGF,
  31. QualType ET,
  32. const ObjCMethodDecl *Method,
  33. RValue Result);
  34. /// Given the address of a variable of pointer type, find the correct
  35. /// null to store into it.
  36. static llvm::Constant *getNullForVariable(llvm::Value *addr) {
  37. llvm::Type *type =
  38. cast<llvm::PointerType>(addr->getType())->getElementType();
  39. return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type));
  40. }
  41. /// Emits an instance of NSConstantString representing the object.
  42. llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
  43. {
  44. llvm::Constant *C =
  45. CGM.getObjCRuntime().GenerateConstantString(E->getString());
  46. // FIXME: This bitcast should just be made an invariant on the Runtime.
  47. return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
  48. }
  49. /// EmitObjCBoxedExpr - This routine generates code to call
  50. /// the appropriate expression boxing method. This will either be
  51. /// one of +[NSNumber numberWith<Type>:], or +[NSString stringWithUTF8String:].
  52. ///
  53. llvm::Value *
  54. CodeGenFunction::EmitObjCBoxedExpr(const ObjCBoxedExpr *E) {
  55. // Generate the correct selector for this literal's concrete type.
  56. const Expr *SubExpr = E->getSubExpr();
  57. // Get the method.
  58. const ObjCMethodDecl *BoxingMethod = E->getBoxingMethod();
  59. assert(BoxingMethod && "BoxingMethod is null");
  60. assert(BoxingMethod->isClassMethod() && "BoxingMethod must be a class method");
  61. Selector Sel = BoxingMethod->getSelector();
  62. // Generate a reference to the class pointer, which will be the receiver.
  63. // Assumes that the method was introduced in the class that should be
  64. // messaged (avoids pulling it out of the result type).
  65. CGObjCRuntime &Runtime = CGM.getObjCRuntime();
  66. const ObjCInterfaceDecl *ClassDecl = BoxingMethod->getClassInterface();
  67. llvm::Value *Receiver = Runtime.GetClass(Builder, ClassDecl);
  68. const ParmVarDecl *argDecl = *BoxingMethod->param_begin();
  69. QualType ArgQT = argDecl->getType().getUnqualifiedType();
  70. RValue RV = EmitAnyExpr(SubExpr);
  71. CallArgList Args;
  72. Args.add(RV, ArgQT);
  73. RValue result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
  74. BoxingMethod->getResultType(), Sel, Receiver, Args,
  75. ClassDecl, BoxingMethod);
  76. return Builder.CreateBitCast(result.getScalarVal(),
  77. ConvertType(E->getType()));
  78. }
  79. llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E,
  80. const ObjCMethodDecl *MethodWithObjects) {
  81. ASTContext &Context = CGM.getContext();
  82. const ObjCDictionaryLiteral *DLE = 0;
  83. const ObjCArrayLiteral *ALE = dyn_cast<ObjCArrayLiteral>(E);
  84. if (!ALE)
  85. DLE = cast<ObjCDictionaryLiteral>(E);
  86. // Compute the type of the array we're initializing.
  87. uint64_t NumElements =
  88. ALE ? ALE->getNumElements() : DLE->getNumElements();
  89. llvm::APInt APNumElements(Context.getTypeSize(Context.getSizeType()),
  90. NumElements);
  91. QualType ElementType = Context.getObjCIdType().withConst();
  92. QualType ElementArrayType
  93. = Context.getConstantArrayType(ElementType, APNumElements,
  94. ArrayType::Normal, /*IndexTypeQuals=*/0);
  95. // Allocate the temporary array(s).
  96. llvm::Value *Objects = CreateMemTemp(ElementArrayType, "objects");
  97. llvm::Value *Keys = 0;
  98. if (DLE)
  99. Keys = CreateMemTemp(ElementArrayType, "keys");
  100. // Perform the actual initialialization of the array(s).
  101. for (uint64_t i = 0; i < NumElements; i++) {
  102. if (ALE) {
  103. // Emit the initializer.
  104. const Expr *Rhs = ALE->getElement(i);
  105. LValue LV = LValue::MakeAddr(Builder.CreateStructGEP(Objects, i),
  106. ElementType,
  107. Context.getTypeAlignInChars(Rhs->getType()),
  108. Context);
  109. EmitScalarInit(Rhs, /*D=*/0, LV, /*capturedByInit=*/false);
  110. } else {
  111. // Emit the key initializer.
  112. const Expr *Key = DLE->getKeyValueElement(i).Key;
  113. LValue KeyLV = LValue::MakeAddr(Builder.CreateStructGEP(Keys, i),
  114. ElementType,
  115. Context.getTypeAlignInChars(Key->getType()),
  116. Context);
  117. EmitScalarInit(Key, /*D=*/0, KeyLV, /*capturedByInit=*/false);
  118. // Emit the value initializer.
  119. const Expr *Value = DLE->getKeyValueElement(i).Value;
  120. LValue ValueLV = LValue::MakeAddr(Builder.CreateStructGEP(Objects, i),
  121. ElementType,
  122. Context.getTypeAlignInChars(Value->getType()),
  123. Context);
  124. EmitScalarInit(Value, /*D=*/0, ValueLV, /*capturedByInit=*/false);
  125. }
  126. }
  127. // Generate the argument list.
  128. CallArgList Args;
  129. ObjCMethodDecl::param_const_iterator PI = MethodWithObjects->param_begin();
  130. const ParmVarDecl *argDecl = *PI++;
  131. QualType ArgQT = argDecl->getType().getUnqualifiedType();
  132. Args.add(RValue::get(Objects), ArgQT);
  133. if (DLE) {
  134. argDecl = *PI++;
  135. ArgQT = argDecl->getType().getUnqualifiedType();
  136. Args.add(RValue::get(Keys), ArgQT);
  137. }
  138. argDecl = *PI;
  139. ArgQT = argDecl->getType().getUnqualifiedType();
  140. llvm::Value *Count =
  141. llvm::ConstantInt::get(CGM.getTypes().ConvertType(ArgQT), NumElements);
  142. Args.add(RValue::get(Count), ArgQT);
  143. // Generate a reference to the class pointer, which will be the receiver.
  144. Selector Sel = MethodWithObjects->getSelector();
  145. QualType ResultType = E->getType();
  146. const ObjCObjectPointerType *InterfacePointerType
  147. = ResultType->getAsObjCInterfacePointerType();
  148. ObjCInterfaceDecl *Class
  149. = InterfacePointerType->getObjectType()->getInterface();
  150. CGObjCRuntime &Runtime = CGM.getObjCRuntime();
  151. llvm::Value *Receiver = Runtime.GetClass(Builder, Class);
  152. // Generate the message send.
  153. RValue result
  154. = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
  155. MethodWithObjects->getResultType(),
  156. Sel,
  157. Receiver, Args, Class,
  158. MethodWithObjects);
  159. return Builder.CreateBitCast(result.getScalarVal(),
  160. ConvertType(E->getType()));
  161. }
  162. llvm::Value *CodeGenFunction::EmitObjCArrayLiteral(const ObjCArrayLiteral *E) {
  163. return EmitObjCCollectionLiteral(E, E->getArrayWithObjectsMethod());
  164. }
  165. llvm::Value *CodeGenFunction::EmitObjCDictionaryLiteral(
  166. const ObjCDictionaryLiteral *E) {
  167. return EmitObjCCollectionLiteral(E, E->getDictWithObjectsMethod());
  168. }
  169. /// Emit a selector.
  170. llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
  171. // Untyped selector.
  172. // Note that this implementation allows for non-constant strings to be passed
  173. // as arguments to @selector(). Currently, the only thing preventing this
  174. // behaviour is the type checking in the front end.
  175. return CGM.getObjCRuntime().GetSelector(Builder, E->getSelector());
  176. }
  177. llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
  178. // FIXME: This should pass the Decl not the name.
  179. return CGM.getObjCRuntime().GenerateProtocolRef(Builder, E->getProtocol());
  180. }
  181. /// \brief Adjust the type of the result of an Objective-C message send
  182. /// expression when the method has a related result type.
  183. static RValue AdjustRelatedResultType(CodeGenFunction &CGF,
  184. QualType ExpT,
  185. const ObjCMethodDecl *Method,
  186. RValue Result) {
  187. if (!Method)
  188. return Result;
  189. if (!Method->hasRelatedResultType() ||
  190. CGF.getContext().hasSameType(ExpT, Method->getResultType()) ||
  191. !Result.isScalar())
  192. return Result;
  193. // We have applied a related result type. Cast the rvalue appropriately.
  194. return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(),
  195. CGF.ConvertType(ExpT)));
  196. }
  197. /// Decide whether to extend the lifetime of the receiver of a
  198. /// returns-inner-pointer message.
  199. static bool
  200. shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr *message) {
  201. switch (message->getReceiverKind()) {
  202. // For a normal instance message, we should extend unless the
  203. // receiver is loaded from a variable with precise lifetime.
  204. case ObjCMessageExpr::Instance: {
  205. const Expr *receiver = message->getInstanceReceiver();
  206. const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(receiver);
  207. if (!ice || ice->getCastKind() != CK_LValueToRValue) return true;
  208. receiver = ice->getSubExpr()->IgnoreParens();
  209. // Only __strong variables.
  210. if (receiver->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  211. return true;
  212. // All ivars and fields have precise lifetime.
  213. if (isa<MemberExpr>(receiver) || isa<ObjCIvarRefExpr>(receiver))
  214. return false;
  215. // Otherwise, check for variables.
  216. const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(ice->getSubExpr());
  217. if (!declRef) return true;
  218. const VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl());
  219. if (!var) return true;
  220. // All variables have precise lifetime except local variables with
  221. // automatic storage duration that aren't specially marked.
  222. return (var->hasLocalStorage() &&
  223. !var->hasAttr<ObjCPreciseLifetimeAttr>());
  224. }
  225. case ObjCMessageExpr::Class:
  226. case ObjCMessageExpr::SuperClass:
  227. // It's never necessary for class objects.
  228. return false;
  229. case ObjCMessageExpr::SuperInstance:
  230. // We generally assume that 'self' lives throughout a method call.
  231. return false;
  232. }
  233. llvm_unreachable("invalid receiver kind");
  234. }
  235. RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
  236. ReturnValueSlot Return) {
  237. // Only the lookup mechanism and first two arguments of the method
  238. // implementation vary between runtimes. We can get the receiver and
  239. // arguments in generic code.
  240. bool isDelegateInit = E->isDelegateInitCall();
  241. const ObjCMethodDecl *method = E->getMethodDecl();
  242. // We don't retain the receiver in delegate init calls, and this is
  243. // safe because the receiver value is always loaded from 'self',
  244. // which we zero out. We don't want to Block_copy block receivers,
  245. // though.
  246. bool retainSelf =
  247. (!isDelegateInit &&
  248. CGM.getLangOpts().ObjCAutoRefCount &&
  249. method &&
  250. method->hasAttr<NSConsumesSelfAttr>());
  251. CGObjCRuntime &Runtime = CGM.getObjCRuntime();
  252. bool isSuperMessage = false;
  253. bool isClassMessage = false;
  254. ObjCInterfaceDecl *OID = 0;
  255. // Find the receiver
  256. QualType ReceiverType;
  257. llvm::Value *Receiver = 0;
  258. switch (E->getReceiverKind()) {
  259. case ObjCMessageExpr::Instance:
  260. ReceiverType = E->getInstanceReceiver()->getType();
  261. if (retainSelf) {
  262. TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
  263. E->getInstanceReceiver());
  264. Receiver = ter.getPointer();
  265. if (ter.getInt()) retainSelf = false;
  266. } else
  267. Receiver = EmitScalarExpr(E->getInstanceReceiver());
  268. break;
  269. case ObjCMessageExpr::Class: {
  270. ReceiverType = E->getClassReceiver();
  271. const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
  272. assert(ObjTy && "Invalid Objective-C class message send");
  273. OID = ObjTy->getInterface();
  274. assert(OID && "Invalid Objective-C class message send");
  275. Receiver = Runtime.GetClass(Builder, OID);
  276. isClassMessage = true;
  277. break;
  278. }
  279. case ObjCMessageExpr::SuperInstance:
  280. ReceiverType = E->getSuperType();
  281. Receiver = LoadObjCSelf();
  282. isSuperMessage = true;
  283. break;
  284. case ObjCMessageExpr::SuperClass:
  285. ReceiverType = E->getSuperType();
  286. Receiver = LoadObjCSelf();
  287. isSuperMessage = true;
  288. isClassMessage = true;
  289. break;
  290. }
  291. if (retainSelf)
  292. Receiver = EmitARCRetainNonBlock(Receiver);
  293. // In ARC, we sometimes want to "extend the lifetime"
  294. // (i.e. retain+autorelease) of receivers of returns-inner-pointer
  295. // messages.
  296. if (getLangOpts().ObjCAutoRefCount && method &&
  297. method->hasAttr<ObjCReturnsInnerPointerAttr>() &&
  298. shouldExtendReceiverForInnerPointerMessage(E))
  299. Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver);
  300. QualType ResultType =
  301. method ? method->getResultType() : E->getType();
  302. CallArgList Args;
  303. EmitCallArgs(Args, method, E->arg_begin(), E->arg_end());
  304. // For delegate init calls in ARC, do an unsafe store of null into
  305. // self. This represents the call taking direct ownership of that
  306. // value. We have to do this after emitting the other call
  307. // arguments because they might also reference self, but we don't
  308. // have to worry about any of them modifying self because that would
  309. // be an undefined read and write of an object in unordered
  310. // expressions.
  311. if (isDelegateInit) {
  312. assert(getLangOpts().ObjCAutoRefCount &&
  313. "delegate init calls should only be marked in ARC");
  314. // Do an unsafe store of null into self.
  315. llvm::Value *selfAddr =
  316. LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
  317. assert(selfAddr && "no self entry for a delegate init call?");
  318. Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
  319. }
  320. RValue result;
  321. if (isSuperMessage) {
  322. // super is only valid in an Objective-C method
  323. const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
  324. bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
  325. result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
  326. E->getSelector(),
  327. OMD->getClassInterface(),
  328. isCategoryImpl,
  329. Receiver,
  330. isClassMessage,
  331. Args,
  332. method);
  333. } else {
  334. result = Runtime.GenerateMessageSend(*this, Return, ResultType,
  335. E->getSelector(),
  336. Receiver, Args, OID,
  337. method);
  338. }
  339. // For delegate init calls in ARC, implicitly store the result of
  340. // the call back into self. This takes ownership of the value.
  341. if (isDelegateInit) {
  342. llvm::Value *selfAddr =
  343. LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
  344. llvm::Value *newSelf = result.getScalarVal();
  345. // The delegate return type isn't necessarily a matching type; in
  346. // fact, it's quite likely to be 'id'.
  347. llvm::Type *selfTy =
  348. cast<llvm::PointerType>(selfAddr->getType())->getElementType();
  349. newSelf = Builder.CreateBitCast(newSelf, selfTy);
  350. Builder.CreateStore(newSelf, selfAddr);
  351. }
  352. return AdjustRelatedResultType(*this, E->getType(), method, result);
  353. }
  354. namespace {
  355. struct FinishARCDealloc : EHScopeStack::Cleanup {
  356. void Emit(CodeGenFunction &CGF, Flags flags) {
  357. const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
  358. const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
  359. const ObjCInterfaceDecl *iface = impl->getClassInterface();
  360. if (!iface->getSuperClass()) return;
  361. bool isCategory = isa<ObjCCategoryImplDecl>(impl);
  362. // Call [super dealloc] if we have a superclass.
  363. llvm::Value *self = CGF.LoadObjCSelf();
  364. CallArgList args;
  365. CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
  366. CGF.getContext().VoidTy,
  367. method->getSelector(),
  368. iface,
  369. isCategory,
  370. self,
  371. /*is class msg*/ false,
  372. args,
  373. method);
  374. }
  375. };
  376. }
  377. /// StartObjCMethod - Begin emission of an ObjCMethod. This generates
  378. /// the LLVM function and sets the other context used by
  379. /// CodeGenFunction.
  380. void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
  381. const ObjCContainerDecl *CD,
  382. SourceLocation StartLoc) {
  383. FunctionArgList args;
  384. // Check if we should generate debug info for this method.
  385. if (!OMD->hasAttr<NoDebugAttr>())
  386. maybeInitializeDebugInfo();
  387. llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
  388. const CGFunctionInfo &FI = CGM.getTypes().arrangeObjCMethodDeclaration(OMD);
  389. CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
  390. args.push_back(OMD->getSelfDecl());
  391. args.push_back(OMD->getCmdDecl());
  392. for (ObjCMethodDecl::param_const_iterator PI = OMD->param_begin(),
  393. E = OMD->param_end(); PI != E; ++PI)
  394. args.push_back(*PI);
  395. CurGD = OMD;
  396. StartFunction(OMD, OMD->getResultType(), Fn, FI, args, StartLoc);
  397. // In ARC, certain methods get an extra cleanup.
  398. if (CGM.getLangOpts().ObjCAutoRefCount &&
  399. OMD->isInstanceMethod() &&
  400. OMD->getSelector().isUnarySelector()) {
  401. const IdentifierInfo *ident =
  402. OMD->getSelector().getIdentifierInfoForSlot(0);
  403. if (ident->isStr("dealloc"))
  404. EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
  405. }
  406. }
  407. static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
  408. LValue lvalue, QualType type);
  409. /// Generate an Objective-C method. An Objective-C method is a C function with
  410. /// its pointer, name, and types registered in the class struture.
  411. void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
  412. StartObjCMethod(OMD, OMD->getClassInterface(), OMD->getLocStart());
  413. EmitStmt(OMD->getBody());
  414. FinishFunction(OMD->getBodyRBrace());
  415. }
  416. /// emitStructGetterCall - Call the runtime function to load a property
  417. /// into the return value slot.
  418. static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
  419. bool isAtomic, bool hasStrong) {
  420. ASTContext &Context = CGF.getContext();
  421. llvm::Value *src =
  422. CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(),
  423. ivar, 0).getAddress();
  424. // objc_copyStruct (ReturnValue, &structIvar,
  425. // sizeof (Type of Ivar), isAtomic, false);
  426. CallArgList args;
  427. llvm::Value *dest = CGF.Builder.CreateBitCast(CGF.ReturnValue, CGF.VoidPtrTy);
  428. args.add(RValue::get(dest), Context.VoidPtrTy);
  429. src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy);
  430. args.add(RValue::get(src), Context.VoidPtrTy);
  431. CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType());
  432. args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType());
  433. args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy);
  434. args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);
  435. llvm::Value *fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();
  436. CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(Context.VoidTy, args,
  437. FunctionType::ExtInfo(),
  438. RequiredArgs::All),
  439. fn, ReturnValueSlot(), args);
  440. }
  441. /// Determine whether the given architecture supports unaligned atomic
  442. /// accesses. They don't have to be fast, just faster than a function
  443. /// call and a mutex.
  444. static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) {
  445. // FIXME: Allow unaligned atomic load/store on x86. (It is not
  446. // currently supported by the backend.)
  447. return 0;
  448. }
  449. /// Return the maximum size that permits atomic accesses for the given
  450. /// architecture.
  451. static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM,
  452. llvm::Triple::ArchType arch) {
  453. // ARM has 8-byte atomic accesses, but it's not clear whether we
  454. // want to rely on them here.
  455. // In the default case, just assume that any size up to a pointer is
  456. // fine given adequate alignment.
  457. return CharUnits::fromQuantity(CGM.PointerSizeInBytes);
  458. }
  459. namespace {
  460. class PropertyImplStrategy {
  461. public:
  462. enum StrategyKind {
  463. /// The 'native' strategy is to use the architecture's provided
  464. /// reads and writes.
  465. Native,
  466. /// Use objc_setProperty and objc_getProperty.
  467. GetSetProperty,
  468. /// Use objc_setProperty for the setter, but use expression
  469. /// evaluation for the getter.
  470. SetPropertyAndExpressionGet,
  471. /// Use objc_copyStruct.
  472. CopyStruct,
  473. /// The 'expression' strategy is to emit normal assignment or
  474. /// lvalue-to-rvalue expressions.
  475. Expression
  476. };
  477. StrategyKind getKind() const { return StrategyKind(Kind); }
  478. bool hasStrongMember() const { return HasStrong; }
  479. bool isAtomic() const { return IsAtomic; }
  480. bool isCopy() const { return IsCopy; }
  481. CharUnits getIvarSize() const { return IvarSize; }
  482. CharUnits getIvarAlignment() const { return IvarAlignment; }
  483. PropertyImplStrategy(CodeGenModule &CGM,
  484. const ObjCPropertyImplDecl *propImpl);
  485. private:
  486. unsigned Kind : 8;
  487. unsigned IsAtomic : 1;
  488. unsigned IsCopy : 1;
  489. unsigned HasStrong : 1;
  490. CharUnits IvarSize;
  491. CharUnits IvarAlignment;
  492. };
  493. }
  494. /// Pick an implementation strategy for the given property synthesis.
  495. PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
  496. const ObjCPropertyImplDecl *propImpl) {
  497. const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
  498. ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
  499. IsCopy = (setterKind == ObjCPropertyDecl::Copy);
  500. IsAtomic = prop->isAtomic();
  501. HasStrong = false; // doesn't matter here.
  502. // Evaluate the ivar's size and alignment.
  503. ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
  504. QualType ivarType = ivar->getType();
  505. llvm::tie(IvarSize, IvarAlignment)
  506. = CGM.getContext().getTypeInfoInChars(ivarType);
  507. // If we have a copy property, we always have to use getProperty/setProperty.
  508. // TODO: we could actually use setProperty and an expression for non-atomics.
  509. if (IsCopy) {
  510. Kind = GetSetProperty;
  511. return;
  512. }
  513. // Handle retain.
  514. if (setterKind == ObjCPropertyDecl::Retain) {
  515. // In GC-only, there's nothing special that needs to be done.
  516. if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
  517. // fallthrough
  518. // In ARC, if the property is non-atomic, use expression emission,
  519. // which translates to objc_storeStrong. This isn't required, but
  520. // it's slightly nicer.
  521. } else if (CGM.getLangOpts().ObjCAutoRefCount && !IsAtomic) {
  522. // Using standard expression emission for the setter is only
  523. // acceptable if the ivar is __strong, which won't be true if
  524. // the property is annotated with __attribute__((NSObject)).
  525. // TODO: falling all the way back to objc_setProperty here is
  526. // just laziness, though; we could still use objc_storeStrong
  527. // if we hacked it right.
  528. if (ivarType.getObjCLifetime() == Qualifiers::OCL_Strong)
  529. Kind = Expression;
  530. else
  531. Kind = SetPropertyAndExpressionGet;
  532. return;
  533. // Otherwise, we need to at least use setProperty. However, if
  534. // the property isn't atomic, we can use normal expression
  535. // emission for the getter.
  536. } else if (!IsAtomic) {
  537. Kind = SetPropertyAndExpressionGet;
  538. return;
  539. // Otherwise, we have to use both setProperty and getProperty.
  540. } else {
  541. Kind = GetSetProperty;
  542. return;
  543. }
  544. }
  545. // If we're not atomic, just use expression accesses.
  546. if (!IsAtomic) {
  547. Kind = Expression;
  548. return;
  549. }
  550. // Properties on bitfield ivars need to be emitted using expression
  551. // accesses even if they're nominally atomic.
  552. if (ivar->isBitField()) {
  553. Kind = Expression;
  554. return;
  555. }
  556. // GC-qualified or ARC-qualified ivars need to be emitted as
  557. // expressions. This actually works out to being atomic anyway,
  558. // except for ARC __strong, but that should trigger the above code.
  559. if (ivarType.hasNonTrivialObjCLifetime() ||
  560. (CGM.getLangOpts().getGC() &&
  561. CGM.getContext().getObjCGCAttrKind(ivarType))) {
  562. Kind = Expression;
  563. return;
  564. }
  565. // Compute whether the ivar has strong members.
  566. if (CGM.getLangOpts().getGC())
  567. if (const RecordType *recordType = ivarType->getAs<RecordType>())
  568. HasStrong = recordType->getDecl()->hasObjectMember();
  569. // We can never access structs with object members with a native
  570. // access, because we need to use write barriers. This is what
  571. // objc_copyStruct is for.
  572. if (HasStrong) {
  573. Kind = CopyStruct;
  574. return;
  575. }
  576. // Otherwise, this is target-dependent and based on the size and
  577. // alignment of the ivar.
  578. // If the size of the ivar is not a power of two, give up. We don't
  579. // want to get into the business of doing compare-and-swaps.
  580. if (!IvarSize.isPowerOfTwo()) {
  581. Kind = CopyStruct;
  582. return;
  583. }
  584. llvm::Triple::ArchType arch =
  585. CGM.getContext().getTargetInfo().getTriple().getArch();
  586. // Most architectures require memory to fit within a single cache
  587. // line, so the alignment has to be at least the size of the access.
  588. // Otherwise we have to grab a lock.
  589. if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
  590. Kind = CopyStruct;
  591. return;
  592. }
  593. // If the ivar's size exceeds the architecture's maximum atomic
  594. // access size, we have to use CopyStruct.
  595. if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
  596. Kind = CopyStruct;
  597. return;
  598. }
  599. // Otherwise, we can use native loads and stores.
  600. Kind = Native;
  601. }
  602. /// \brief Generate an Objective-C property getter function.
  603. ///
  604. /// The given Decl must be an ObjCImplementationDecl. \@synthesize
  605. /// is illegal within a category.
  606. void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
  607. const ObjCPropertyImplDecl *PID) {
  608. llvm::Constant *AtomicHelperFn =
  609. GenerateObjCAtomicGetterCopyHelperFunction(PID);
  610. const ObjCPropertyDecl *PD = PID->getPropertyDecl();
  611. ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
  612. assert(OMD && "Invalid call to generate getter (empty method)");
  613. StartObjCMethod(OMD, IMP->getClassInterface(), OMD->getLocStart());
  614. generateObjCGetterBody(IMP, PID, OMD, AtomicHelperFn);
  615. FinishFunction();
  616. }
  617. static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
  618. const Expr *getter = propImpl->getGetterCXXConstructor();
  619. if (!getter) return true;
  620. // Sema only makes only of these when the ivar has a C++ class type,
  621. // so the form is pretty constrained.
  622. // If the property has a reference type, we might just be binding a
  623. // reference, in which case the result will be a gl-value. We should
  624. // treat this as a non-trivial operation.
  625. if (getter->isGLValue())
  626. return false;
  627. // If we selected a trivial copy-constructor, we're okay.
  628. if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
  629. return (construct->getConstructor()->isTrivial());
  630. // The constructor might require cleanups (in which case it's never
  631. // trivial).
  632. assert(isa<ExprWithCleanups>(getter));
  633. return false;
  634. }
  635. /// emitCPPObjectAtomicGetterCall - Call the runtime function to
  636. /// copy the ivar into the resturn slot.
  637. static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF,
  638. llvm::Value *returnAddr,
  639. ObjCIvarDecl *ivar,
  640. llvm::Constant *AtomicHelperFn) {
  641. // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,
  642. // AtomicHelperFn);
  643. CallArgList args;
  644. // The 1st argument is the return Slot.
  645. args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy);
  646. // The 2nd argument is the address of the ivar.
  647. llvm::Value *ivarAddr =
  648. CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
  649. CGF.LoadObjCSelf(), ivar, 0).getAddress();
  650. ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
  651. args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
  652. // Third argument is the helper function.
  653. args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
  654. llvm::Value *copyCppAtomicObjectFn =
  655. CGF.CGM.getObjCRuntime().GetCppAtomicObjectGetFunction();
  656. CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
  657. args,
  658. FunctionType::ExtInfo(),
  659. RequiredArgs::All),
  660. copyCppAtomicObjectFn, ReturnValueSlot(), args);
  661. }
  662. void
  663. CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
  664. const ObjCPropertyImplDecl *propImpl,
  665. const ObjCMethodDecl *GetterMethodDecl,
  666. llvm::Constant *AtomicHelperFn) {
  667. // If there's a non-trivial 'get' expression, we just have to emit that.
  668. if (!hasTrivialGetExpr(propImpl)) {
  669. if (!AtomicHelperFn) {
  670. ReturnStmt ret(SourceLocation(), propImpl->getGetterCXXConstructor(),
  671. /*nrvo*/ 0);
  672. EmitReturnStmt(ret);
  673. }
  674. else {
  675. ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
  676. emitCPPObjectAtomicGetterCall(*this, ReturnValue,
  677. ivar, AtomicHelperFn);
  678. }
  679. return;
  680. }
  681. const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
  682. QualType propType = prop->getType();
  683. ObjCMethodDecl *getterMethod = prop->getGetterMethodDecl();
  684. ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
  685. // Pick an implementation strategy.
  686. PropertyImplStrategy strategy(CGM, propImpl);
  687. switch (strategy.getKind()) {
  688. case PropertyImplStrategy::Native: {
  689. // We don't need to do anything for a zero-size struct.
  690. if (strategy.getIvarSize().isZero())
  691. return;
  692. LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
  693. // Currently, all atomic accesses have to be through integer
  694. // types, so there's no point in trying to pick a prettier type.
  695. llvm::Type *bitcastType =
  696. llvm::Type::getIntNTy(getLLVMContext(),
  697. getContext().toBits(strategy.getIvarSize()));
  698. bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
  699. // Perform an atomic load. This does not impose ordering constraints.
  700. llvm::Value *ivarAddr = LV.getAddress();
  701. ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
  702. llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
  703. load->setAlignment(strategy.getIvarAlignment().getQuantity());
  704. load->setAtomic(llvm::Unordered);
  705. // Store that value into the return address. Doing this with a
  706. // bitcast is likely to produce some pretty ugly IR, but it's not
  707. // the *most* terrible thing in the world.
  708. Builder.CreateStore(load, Builder.CreateBitCast(ReturnValue, bitcastType));
  709. // Make sure we don't do an autorelease.
  710. AutoreleaseResult = false;
  711. return;
  712. }
  713. case PropertyImplStrategy::GetSetProperty: {
  714. llvm::Value *getPropertyFn =
  715. CGM.getObjCRuntime().GetPropertyGetFunction();
  716. if (!getPropertyFn) {
  717. CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
  718. return;
  719. }
  720. // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
  721. // FIXME: Can't this be simpler? This might even be worse than the
  722. // corresponding gcc code.
  723. llvm::Value *cmd =
  724. Builder.CreateLoad(LocalDeclMap[getterMethod->getCmdDecl()], "cmd");
  725. llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
  726. llvm::Value *ivarOffset =
  727. EmitIvarOffset(classImpl->getClassInterface(), ivar);
  728. CallArgList args;
  729. args.add(RValue::get(self), getContext().getObjCIdType());
  730. args.add(RValue::get(cmd), getContext().getObjCSelType());
  731. args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
  732. args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
  733. getContext().BoolTy);
  734. // FIXME: We shouldn't need to get the function info here, the
  735. // runtime already should have computed it to build the function.
  736. RValue RV = EmitCall(getTypes().arrangeFreeFunctionCall(propType, args,
  737. FunctionType::ExtInfo(),
  738. RequiredArgs::All),
  739. getPropertyFn, ReturnValueSlot(), args);
  740. // We need to fix the type here. Ivars with copy & retain are
  741. // always objects so we don't need to worry about complex or
  742. // aggregates.
  743. RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(),
  744. getTypes().ConvertType(getterMethod->getResultType())));
  745. EmitReturnOfRValue(RV, propType);
  746. // objc_getProperty does an autorelease, so we should suppress ours.
  747. AutoreleaseResult = false;
  748. return;
  749. }
  750. case PropertyImplStrategy::CopyStruct:
  751. emitStructGetterCall(*this, ivar, strategy.isAtomic(),
  752. strategy.hasStrongMember());
  753. return;
  754. case PropertyImplStrategy::Expression:
  755. case PropertyImplStrategy::SetPropertyAndExpressionGet: {
  756. LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
  757. QualType ivarType = ivar->getType();
  758. if (ivarType->isAnyComplexType()) {
  759. ComplexPairTy pair = LoadComplexFromAddr(LV.getAddress(),
  760. LV.isVolatileQualified());
  761. StoreComplexToAddr(pair, ReturnValue, LV.isVolatileQualified());
  762. } else if (hasAggregateLLVMType(ivarType)) {
  763. // The return value slot is guaranteed to not be aliased, but
  764. // that's not necessarily the same as "on the stack", so
  765. // we still potentially need objc_memmove_collectable.
  766. EmitAggregateCopy(ReturnValue, LV.getAddress(), ivarType);
  767. } else {
  768. llvm::Value *value;
  769. if (propType->isReferenceType()) {
  770. value = LV.getAddress();
  771. } else {
  772. // We want to load and autoreleaseReturnValue ARC __weak ivars.
  773. if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
  774. value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
  775. // Otherwise we want to do a simple load, suppressing the
  776. // final autorelease.
  777. } else {
  778. value = EmitLoadOfLValue(LV).getScalarVal();
  779. AutoreleaseResult = false;
  780. }
  781. value = Builder.CreateBitCast(value, ConvertType(propType));
  782. value = Builder.CreateBitCast(value,
  783. ConvertType(GetterMethodDecl->getResultType()));
  784. }
  785. EmitReturnOfRValue(RValue::get(value), propType);
  786. }
  787. return;
  788. }
  789. }
  790. llvm_unreachable("bad @property implementation strategy!");
  791. }
  792. /// emitStructSetterCall - Call the runtime function to store the value
  793. /// from the first formal parameter into the given ivar.
  794. static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
  795. ObjCIvarDecl *ivar) {
  796. // objc_copyStruct (&structIvar, &Arg,
  797. // sizeof (struct something), true, false);
  798. CallArgList args;
  799. // The first argument is the address of the ivar.
  800. llvm::Value *ivarAddr = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
  801. CGF.LoadObjCSelf(), ivar, 0)
  802. .getAddress();
  803. ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
  804. args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
  805. // The second argument is the address of the parameter variable.
  806. ParmVarDecl *argVar = *OMD->param_begin();
  807. DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
  808. VK_LValue, SourceLocation());
  809. llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
  810. argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
  811. args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
  812. // The third argument is the sizeof the type.
  813. llvm::Value *size =
  814. CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
  815. args.add(RValue::get(size), CGF.getContext().getSizeType());
  816. // The fourth argument is the 'isAtomic' flag.
  817. args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
  818. // The fifth argument is the 'hasStrong' flag.
  819. // FIXME: should this really always be false?
  820. args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
  821. llvm::Value *copyStructFn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
  822. CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
  823. args,
  824. FunctionType::ExtInfo(),
  825. RequiredArgs::All),
  826. copyStructFn, ReturnValueSlot(), args);
  827. }
  828. /// emitCPPObjectAtomicSetterCall - Call the runtime function to store
  829. /// the value from the first formal parameter into the given ivar, using
  830. /// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
  831. static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,
  832. ObjCMethodDecl *OMD,
  833. ObjCIvarDecl *ivar,
  834. llvm::Constant *AtomicHelperFn) {
  835. // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
  836. // AtomicHelperFn);
  837. CallArgList args;
  838. // The first argument is the address of the ivar.
  839. llvm::Value *ivarAddr =
  840. CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
  841. CGF.LoadObjCSelf(), ivar, 0).getAddress();
  842. ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
  843. args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
  844. // The second argument is the address of the parameter variable.
  845. ParmVarDecl *argVar = *OMD->param_begin();
  846. DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
  847. VK_LValue, SourceLocation());
  848. llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
  849. argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
  850. args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
  851. // Third argument is the helper function.
  852. args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
  853. llvm::Value *copyCppAtomicObjectFn =
  854. CGF.CGM.getObjCRuntime().GetCppAtomicObjectSetFunction();
  855. CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
  856. args,
  857. FunctionType::ExtInfo(),
  858. RequiredArgs::All),
  859. copyCppAtomicObjectFn, ReturnValueSlot(), args);
  860. }
  861. static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
  862. Expr *setter = PID->getSetterCXXAssignment();
  863. if (!setter) return true;
  864. // Sema only makes only of these when the ivar has a C++ class type,
  865. // so the form is pretty constrained.
  866. // An operator call is trivial if the function it calls is trivial.
  867. // This also implies that there's nothing non-trivial going on with
  868. // the arguments, because operator= can only be trivial if it's a
  869. // synthesized assignment operator and therefore both parameters are
  870. // references.
  871. if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
  872. if (const FunctionDecl *callee
  873. = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
  874. if (callee->isTrivial())
  875. return true;
  876. return false;
  877. }
  878. assert(isa<ExprWithCleanups>(setter));
  879. return false;
  880. }
  881. static bool UseOptimizedSetter(CodeGenModule &CGM) {
  882. if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
  883. return false;
  884. return CGM.getLangOpts().ObjCRuntime.hasOptimizedSetter();
  885. }
  886. void
  887. CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
  888. const ObjCPropertyImplDecl *propImpl,
  889. llvm::Constant *AtomicHelperFn) {
  890. const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
  891. ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
  892. ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl();
  893. // Just use the setter expression if Sema gave us one and it's
  894. // non-trivial.
  895. if (!hasTrivialSetExpr(propImpl)) {
  896. if (!AtomicHelperFn)
  897. // If non-atomic, assignment is called directly.
  898. EmitStmt(propImpl->getSetterCXXAssignment());
  899. else
  900. // If atomic, assignment is called via a locking api.
  901. emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
  902. AtomicHelperFn);
  903. return;
  904. }
  905. PropertyImplStrategy strategy(CGM, propImpl);
  906. switch (strategy.getKind()) {
  907. case PropertyImplStrategy::Native: {
  908. // We don't need to do anything for a zero-size struct.
  909. if (strategy.getIvarSize().isZero())
  910. return;
  911. llvm::Value *argAddr = LocalDeclMap[*setterMethod->param_begin()];
  912. LValue ivarLValue =
  913. EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
  914. llvm::Value *ivarAddr = ivarLValue.getAddress();
  915. // Currently, all atomic accesses have to be through integer
  916. // types, so there's no point in trying to pick a prettier type.
  917. llvm::Type *bitcastType =
  918. llvm::Type::getIntNTy(getLLVMContext(),
  919. getContext().toBits(strategy.getIvarSize()));
  920. bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
  921. // Cast both arguments to the chosen operation type.
  922. argAddr = Builder.CreateBitCast(argAddr, bitcastType);
  923. ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
  924. // This bitcast load is likely to cause some nasty IR.
  925. llvm::Value *load = Builder.CreateLoad(argAddr);
  926. // Perform an atomic store. There are no memory ordering requirements.
  927. llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
  928. store->setAlignment(strategy.getIvarAlignment().getQuantity());
  929. store->setAtomic(llvm::Unordered);
  930. return;
  931. }
  932. case PropertyImplStrategy::GetSetProperty:
  933. case PropertyImplStrategy::SetPropertyAndExpressionGet: {
  934. llvm::Value *setOptimizedPropertyFn = 0;
  935. llvm::Value *setPropertyFn = 0;
  936. if (UseOptimizedSetter(CGM)) {
  937. // 10.8 and iOS 6.0 code and GC is off
  938. setOptimizedPropertyFn =
  939. CGM.getObjCRuntime()
  940. .GetOptimizedPropertySetFunction(strategy.isAtomic(),
  941. strategy.isCopy());
  942. if (!setOptimizedPropertyFn) {
  943. CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI");
  944. return;
  945. }
  946. }
  947. else {
  948. setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction();
  949. if (!setPropertyFn) {
  950. CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
  951. return;
  952. }
  953. }
  954. // Emit objc_setProperty((id) self, _cmd, offset, arg,
  955. // <is-atomic>, <is-copy>).
  956. llvm::Value *cmd =
  957. Builder.CreateLoad(LocalDeclMap[setterMethod->getCmdDecl()]);
  958. llvm::Value *self =
  959. Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
  960. llvm::Value *ivarOffset =
  961. EmitIvarOffset(classImpl->getClassInterface(), ivar);
  962. llvm::Value *arg = LocalDeclMap[*setterMethod->param_begin()];
  963. arg = Builder.CreateBitCast(Builder.CreateLoad(arg, "arg"), VoidPtrTy);
  964. CallArgList args;
  965. args.add(RValue::get(self), getContext().getObjCIdType());
  966. args.add(RValue::get(cmd), getContext().getObjCSelType());
  967. if (setOptimizedPropertyFn) {
  968. args.add(RValue::get(arg), getContext().getObjCIdType());
  969. args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
  970. EmitCall(getTypes().arrangeFreeFunctionCall(getContext().VoidTy, args,
  971. FunctionType::ExtInfo(),
  972. RequiredArgs::All),
  973. setOptimizedPropertyFn, ReturnValueSlot(), args);
  974. } else {
  975. args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
  976. args.add(RValue::get(arg), getContext().getObjCIdType());
  977. args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
  978. getContext().BoolTy);
  979. args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
  980. getContext().BoolTy);
  981. // FIXME: We shouldn't need to get the function info here, the runtime
  982. // already should have computed it to build the function.
  983. EmitCall(getTypes().arrangeFreeFunctionCall(getContext().VoidTy, args,
  984. FunctionType::ExtInfo(),
  985. RequiredArgs::All),
  986. setPropertyFn, ReturnValueSlot(), args);
  987. }
  988. return;
  989. }
  990. case PropertyImplStrategy::CopyStruct:
  991. emitStructSetterCall(*this, setterMethod, ivar);
  992. return;
  993. case PropertyImplStrategy::Expression:
  994. break;
  995. }
  996. // Otherwise, fake up some ASTs and emit a normal assignment.
  997. ValueDecl *selfDecl = setterMethod->getSelfDecl();
  998. DeclRefExpr self(selfDecl, false, selfDecl->getType(),
  999. VK_LValue, SourceLocation());
  1000. ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
  1001. selfDecl->getType(), CK_LValueToRValue, &self,
  1002. VK_RValue);
  1003. ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
  1004. SourceLocation(), &selfLoad, true, true);
  1005. ParmVarDecl *argDecl = *setterMethod->param_begin();
  1006. QualType argType = argDecl->getType().getNonReferenceType();
  1007. DeclRefExpr arg(argDecl, false, argType, VK_LValue, SourceLocation());
  1008. ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
  1009. argType.getUnqualifiedType(), CK_LValueToRValue,
  1010. &arg, VK_RValue);
  1011. // The property type can differ from the ivar type in some situations with
  1012. // Objective-C pointer types, we can always bit cast the RHS in these cases.
  1013. // The following absurdity is just to ensure well-formed IR.
  1014. CastKind argCK = CK_NoOp;
  1015. if (ivarRef.getType()->isObjCObjectPointerType()) {
  1016. if (argLoad.getType()->isObjCObjectPointerType())
  1017. argCK = CK_BitCast;
  1018. else if (argLoad.getType()->isBlockPointerType())
  1019. argCK = CK_BlockPointerToObjCPointerCast;
  1020. else
  1021. argCK = CK_CPointerToObjCPointerCast;
  1022. } else if (ivarRef.getType()->isBlockPointerType()) {
  1023. if (argLoad.getType()->isBlockPointerType())
  1024. argCK = CK_BitCast;
  1025. else
  1026. argCK = CK_AnyPointerToBlockPointerCast;
  1027. } else if (ivarRef.getType()->isPointerType()) {
  1028. argCK = CK_BitCast;
  1029. }
  1030. ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
  1031. ivarRef.getType(), argCK, &argLoad,
  1032. VK_RValue);
  1033. Expr *finalArg = &argLoad;
  1034. if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
  1035. argLoad.getType()))
  1036. finalArg = &argCast;
  1037. BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
  1038. ivarRef.getType(), VK_RValue, OK_Ordinary,
  1039. SourceLocation(), false);
  1040. EmitStmt(&assign);
  1041. }
  1042. /// \brief Generate an Objective-C property setter function.
  1043. ///
  1044. /// The given Decl must be an ObjCImplementationDecl. \@synthesize
  1045. /// is illegal within a category.
  1046. void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
  1047. const ObjCPropertyImplDecl *PID) {
  1048. llvm::Constant *AtomicHelperFn =
  1049. GenerateObjCAtomicSetterCopyHelperFunction(PID);
  1050. const ObjCPropertyDecl *PD = PID->getPropertyDecl();
  1051. ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
  1052. assert(OMD && "Invalid call to generate setter (empty method)");
  1053. StartObjCMethod(OMD, IMP->getClassInterface(), OMD->getLocStart());
  1054. generateObjCSetterBody(IMP, PID, AtomicHelperFn);
  1055. FinishFunction();
  1056. }
  1057. namespace {
  1058. struct DestroyIvar : EHScopeStack::Cleanup {
  1059. private:
  1060. llvm::Value *addr;
  1061. const ObjCIvarDecl *ivar;
  1062. CodeGenFunction::Destroyer *destroyer;
  1063. bool useEHCleanupForArray;
  1064. public:
  1065. DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
  1066. CodeGenFunction::Destroyer *destroyer,
  1067. bool useEHCleanupForArray)
  1068. : addr(addr), ivar(ivar), destroyer(destroyer),
  1069. useEHCleanupForArray(useEHCleanupForArray) {}
  1070. void Emit(CodeGenFunction &CGF, Flags flags) {
  1071. LValue lvalue
  1072. = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
  1073. CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
  1074. flags.isForNormalCleanup() && useEHCleanupForArray);
  1075. }
  1076. };
  1077. }
  1078. /// Like CodeGenFunction::destroyARCStrong, but do it with a call.
  1079. static void destroyARCStrongWithStore(CodeGenFunction &CGF,
  1080. llvm::Value *addr,
  1081. QualType type) {
  1082. llvm::Value *null = getNullForVariable(addr);
  1083. CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
  1084. }
  1085. static void emitCXXDestructMethod(CodeGenFunction &CGF,
  1086. ObjCImplementationDecl *impl) {
  1087. CodeGenFunction::RunCleanupsScope scope(CGF);
  1088. llvm::Value *self = CGF.LoadObjCSelf();
  1089. const ObjCInterfaceDecl *iface = impl->getClassInterface();
  1090. for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
  1091. ivar; ivar = ivar->getNextIvar()) {
  1092. QualType type = ivar->getType();
  1093. // Check whether the ivar is a destructible type.
  1094. QualType::DestructionKind dtorKind = type.isDestructedType();
  1095. if (!dtorKind) continue;
  1096. CodeGenFunction::Destroyer *destroyer = 0;
  1097. // Use a call to objc_storeStrong to destroy strong ivars, for the
  1098. // general benefit of the tools.
  1099. if (dtorKind == QualType::DK_objc_strong_lifetime) {
  1100. destroyer = destroyARCStrongWithStore;
  1101. // Otherwise use the default for the destruction kind.
  1102. } else {
  1103. destroyer = CGF.getDestroyer(dtorKind);
  1104. }
  1105. CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
  1106. CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
  1107. cleanupKind & EHCleanup);
  1108. }
  1109. assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
  1110. }
  1111. void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
  1112. ObjCMethodDecl *MD,
  1113. bool ctor) {
  1114. MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
  1115. StartObjCMethod(MD, IMP->getClassInterface(), MD->getLocStart());
  1116. // Emit .cxx_construct.
  1117. if (ctor) {
  1118. // Suppress the final autorelease in ARC.
  1119. AutoreleaseResult = false;
  1120. SmallVector<CXXCtorInitializer *, 8> IvarInitializers;
  1121. for (ObjCImplementationDecl::init_const_iterator B = IMP->init_begin(),
  1122. E = IMP->init_end(); B != E; ++B) {
  1123. CXXCtorInitializer *IvarInit = (*B);
  1124. FieldDecl *Field = IvarInit->getAnyMember();
  1125. ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
  1126. LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
  1127. LoadObjCSelf(), Ivar, 0);
  1128. EmitAggExpr(IvarInit->getInit(),
  1129. AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed,
  1130. AggValueSlot::DoesNotNeedGCBarriers,
  1131. AggValueSlot::IsNotAliased));
  1132. }
  1133. // constructor returns 'self'.
  1134. CodeGenTypes &Types = CGM.getTypes();
  1135. QualType IdTy(CGM.getContext().getObjCIdType());
  1136. llvm::Value *SelfAsId =
  1137. Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
  1138. EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
  1139. // Emit .cxx_destruct.
  1140. } else {
  1141. emitCXXDestructMethod(*this, IMP);
  1142. }
  1143. FinishFunction();
  1144. }
  1145. bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) {
  1146. CGFunctionInfo::const_arg_iterator it = FI.arg_begin();
  1147. it++; it++;
  1148. const ABIArgInfo &AI = it->info;
  1149. // FIXME. Is this sufficient check?
  1150. return (AI.getKind() == ABIArgInfo::Indirect);
  1151. }
  1152. bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) {
  1153. if (CGM.getLangOpts().getGC() == LangOptions::NonGC)
  1154. return false;
  1155. if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>())
  1156. return FDTTy->getDecl()->hasObjectMember();
  1157. return false;
  1158. }
  1159. llvm::Value *CodeGenFunction::LoadObjCSelf() {
  1160. const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
  1161. return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self");
  1162. }
  1163. QualType CodeGenFunction::TypeOfSelfObject() {
  1164. const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
  1165. ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
  1166. const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
  1167. getContext().getCanonicalType(selfDecl->getType()));
  1168. return PTy->getPointeeType();
  1169. }
  1170. void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
  1171. llvm::Constant *EnumerationMutationFn =
  1172. CGM.getObjCRuntime().EnumerationMutationFunction();
  1173. if (!EnumerationMutationFn) {
  1174. CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
  1175. return;
  1176. }
  1177. CGDebugInfo *DI = getDebugInfo();
  1178. if (DI)
  1179. DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
  1180. // The local variable comes into scope immediately.
  1181. AutoVarEmission variable = AutoVarEmission::invalid();
  1182. if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
  1183. variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
  1184. JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
  1185. // Fast enumeration state.
  1186. QualType StateTy = CGM.getObjCFastEnumerationStateType();
  1187. llvm::Value *StatePtr = CreateMemTemp(StateTy, "state.ptr");
  1188. EmitNullInitialization(StatePtr, StateTy);
  1189. // Number of elements in the items array.
  1190. static const unsigned NumItems = 16;
  1191. // Fetch the countByEnumeratingWithState:objects:count: selector.
  1192. IdentifierInfo *II[] = {
  1193. &CGM.getContext().Idents.get("countByEnumeratingWithState"),
  1194. &CGM.getContext().Idents.get("objects"),
  1195. &CGM.getContext().Idents.get("count")
  1196. };
  1197. Selector FastEnumSel =
  1198. CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
  1199. QualType ItemsTy =
  1200. getContext().getConstantArrayType(getContext().getObjCIdType(),
  1201. llvm::APInt(32, NumItems),
  1202. ArrayType::Normal, 0);
  1203. llvm::Value *ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
  1204. // Emit the collection pointer. In ARC, we do a retain.
  1205. llvm::Value *Collection;
  1206. if (getLangOpts().ObjCAutoRefCount) {
  1207. Collection = EmitARCRetainScalarExpr(S.getCollection());
  1208. // Enter a cleanup to do the release.
  1209. EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
  1210. } else {
  1211. Collection = EmitScalarExpr(S.getCollection());
  1212. }
  1213. // The 'continue' label needs to appear within the cleanup for the
  1214. // collection object.
  1215. JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
  1216. // Send it our message:
  1217. CallArgList Args;
  1218. // The first argument is a temporary of the enumeration-state type.
  1219. Args.add(RValue::get(StatePtr), getContext().getPointerType(StateTy));
  1220. // The second argument is a temporary array with space for NumItems
  1221. // pointers. We'll actually be loading elements from the array
  1222. // pointer written into the control state; this buffer is so that
  1223. // collections that *aren't* backed by arrays can still queue up
  1224. // batches of elements.
  1225. Args.add(RValue::get(ItemsPtr), getContext().getPointerType(ItemsTy));
  1226. // The third argument is the capacity of that temporary array.
  1227. llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
  1228. llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
  1229. Args.add(RValue::get(Count), getContext().UnsignedLongTy);
  1230. // Start the enumeration.
  1231. RValue CountRV =
  1232. CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
  1233. getContext().UnsignedLongTy,
  1234. FastEnumSel,
  1235. Collection, Args);
  1236. // The initial number of objects that were returned in the buffer.
  1237. llvm::Value *initialBufferLimit = CountRV.getScalarVal();
  1238. llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
  1239. llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
  1240. llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy);
  1241. // If the limit pointer was zero to begin with, the collection is
  1242. // empty; skip all this.
  1243. Builder.CreateCondBr(Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"),
  1244. EmptyBB, LoopInitBB);
  1245. // Otherwise, initialize the loop.
  1246. EmitBlock(LoopInitBB);
  1247. // Save the initial mutations value. This is the value at an
  1248. // address that was written into the state object by
  1249. // countByEnumeratingWithState:objects:count:.
  1250. llvm::Value *StateMutationsPtrPtr =
  1251. Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
  1252. llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
  1253. "mutationsptr");
  1254. llvm::Value *initialMutations =
  1255. Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations");
  1256. // Start looping. This is the point we return to whenever we have a
  1257. // fresh, non-empty batch of objects.
  1258. llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
  1259. EmitBlock(LoopBodyBB);
  1260. // The current index into the buffer.
  1261. llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.index");
  1262. index->addIncoming(zero, LoopInitBB);
  1263. // The current buffer size.
  1264. llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.count");
  1265. count->addIncoming(initialBufferLimit, LoopInitBB);
  1266. // Check whether the mutations value has changed from where it was
  1267. // at start. StateMutationsPtr should actually be invariant between
  1268. // refreshes.
  1269. StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
  1270. llvm::Value *currentMutations
  1271. = Builder.CreateLoad(StateMutationsPtr, "statemutations");
  1272. llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
  1273. llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
  1274. Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
  1275. WasNotMutatedBB, WasMutatedBB);
  1276. // If so, call the enumeration-mutation function.
  1277. EmitBlock(WasMutatedBB);
  1278. llvm::Value *V =
  1279. Builder.CreateBitCast(Collection,
  1280. ConvertType(getContext().getObjCIdType()));
  1281. CallArgList Args2;
  1282. Args2.add(RValue::get(V), getContext().getObjCIdType());
  1283. // FIXME: We shouldn't need to get the function info here, the runtime already
  1284. // should have computed it to build the function.
  1285. EmitCall(CGM.getTypes().arrangeFreeFunctionCall(getContext().VoidTy, Args2,
  1286. FunctionType::ExtInfo(),
  1287. RequiredArgs::All),
  1288. EnumerationMutationFn, ReturnValueSlot(), Args2);
  1289. // Otherwise, or if the mutation function returns, just continue.
  1290. EmitBlock(WasNotMutatedBB);
  1291. // Initialize the element variable.
  1292. RunCleanupsScope elementVariableScope(*this);
  1293. bool elementIsVariable;
  1294. LValue elementLValue;
  1295. QualType elementType;
  1296. if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
  1297. // Initialize the variable, in case it's a __block variable or something.
  1298. EmitAutoVarInit(variable);
  1299. const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
  1300. DeclRefExpr tempDRE(const_cast<VarDecl*>(D), false, D->getType(),
  1301. VK_LValue, SourceLocation());
  1302. elementLValue = EmitLValue(&tempDRE);
  1303. elementType = D->getType();
  1304. elementIsVariable = true;
  1305. if (D->isARCPseudoStrong())
  1306. elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
  1307. } else {
  1308. elementLValue = LValue(); // suppress warning
  1309. elementType = cast<Expr>(S.getElement())->getType();
  1310. elementIsVariable = false;
  1311. }
  1312. llvm::Type *convertedElementType = ConvertType(elementType);
  1313. // Fetch the buffer out of the enumeration state.
  1314. // TODO: this pointer should actually be invariant between
  1315. // refreshes, which would help us do certain loop optimizations.
  1316. llvm::Value *StateItemsPtr =
  1317. Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
  1318. llvm::Value *EnumStateItems =
  1319. Builder.CreateLoad(StateItemsPtr, "stateitems");
  1320. // Fetch the value at the current index from the buffer.
  1321. llvm::Value *CurrentItemPtr =
  1322. Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
  1323. llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr);
  1324. // Cast that value to the right type.
  1325. CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
  1326. "currentitem");
  1327. // Make sure we have an l-value. Yes, this gets evaluated every
  1328. // time through the loop.
  1329. if (!elementIsVariable) {
  1330. elementLValue = EmitLValue(cast<Expr>(S.getElement()));
  1331. EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
  1332. } else {
  1333. EmitScalarInit(CurrentItem, elementLValue);
  1334. }
  1335. // If we do have an element variable, this assignment is the end of
  1336. // its initialization.
  1337. if (elementIsVariable)
  1338. EmitAutoVarCleanups(variable);
  1339. // Perform the loop body, setting up break and continue labels.
  1340. BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
  1341. {
  1342. RunCleanupsScope Scope(*this);
  1343. EmitStmt(S.getBody());
  1344. }
  1345. BreakContinueStack.pop_back();
  1346. // Destroy the element variable now.
  1347. elementVariableScope.ForceCleanup();
  1348. // Check whether there are more elements.
  1349. EmitBlock(AfterBody.getBlock());
  1350. llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
  1351. // First we check in the local buffer.
  1352. llvm::Value *indexPlusOne
  1353. = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1));
  1354. // If we haven't overrun the buffer yet, we can continue.
  1355. Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count),
  1356. LoopBodyBB, FetchMoreBB);
  1357. index->addIncoming(indexPlusOne, AfterBody.getBlock());
  1358. count->addIncoming(count, AfterBody.getBlock());
  1359. // Otherwise, we have to fetch more elements.
  1360. EmitBlock(FetchMoreBB);
  1361. CountRV =
  1362. CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
  1363. getContext().UnsignedLongTy,
  1364. FastEnumSel,
  1365. Collection, Args);
  1366. // If we got a zero count, we're done.
  1367. llvm::Value *refetchCount = CountRV.getScalarVal();
  1368. // (note that the message send might split FetchMoreBB)
  1369. index->addIncoming(zero, Builder.GetInsertBlock());
  1370. count->addIncoming(refetchCount, Builder.GetInsertBlock());
  1371. Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
  1372. EmptyBB, LoopBodyBB);
  1373. // No more elements.
  1374. EmitBlock(EmptyBB);
  1375. if (!elementIsVariable) {
  1376. // If the element was not a declaration, set it to be null.
  1377. llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
  1378. elementLValue = EmitLValue(cast<Expr>(S.getElement()));
  1379. EmitStoreThroughLValue(RValue::get(null), elementLValue);
  1380. }
  1381. if (DI)
  1382. DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
  1383. // Leave the cleanup we entered in ARC.
  1384. if (getLangOpts().ObjCAutoRefCount)
  1385. PopCleanupBlock();
  1386. EmitBlock(LoopEnd.getBlock());
  1387. }
  1388. void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
  1389. CGM.getObjCRuntime().EmitTryStmt(*this, S);
  1390. }
  1391. void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
  1392. CGM.getObjCRuntime().EmitThrowStmt(*this, S);
  1393. }
  1394. void CodeGenFunction::EmitObjCAtSynchronizedStmt(
  1395. const ObjCAtSynchronizedStmt &S) {
  1396. CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
  1397. }
  1398. /// Produce the code for a CK_ARCProduceObject. Just does a
  1399. /// primitive retain.
  1400. llvm::Value *CodeGenFunction::EmitObjCProduceObject(QualType type,
  1401. llvm::Value *value) {
  1402. return EmitARCRetain(type, value);
  1403. }
  1404. namespace {
  1405. struct CallObjCRelease : EHScopeStack::Cleanup {
  1406. CallObjCRelease(llvm::Value *object) : object(object) {}
  1407. llvm::Value *object;
  1408. void Emit(CodeGenFunction &CGF, Flags flags) {
  1409. CGF.EmitARCRelease(object, /*precise*/ true);
  1410. }
  1411. };
  1412. }
  1413. /// Produce the code for a CK_ARCConsumeObject. Does a primitive
  1414. /// release at the end of the full-expression.
  1415. llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
  1416. llvm::Value *object) {
  1417. // If we're in a conditional branch, we need to make the cleanup
  1418. // conditional.
  1419. pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
  1420. return object;
  1421. }
  1422. llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
  1423. llvm::Value *value) {
  1424. return EmitARCRetainAutorelease(type, value);
  1425. }
  1426. static llvm::Constant *createARCRuntimeFunction(CodeGenModule &CGM,
  1427. llvm::FunctionType *type,
  1428. StringRef fnName) {
  1429. llvm::Constant *fn = CGM.CreateRuntimeFunction(type, fnName);
  1430. // If the target runtime doesn't naturally support ARC, emit weak
  1431. // references to the runtime support library. We don't really
  1432. // permit this to fail, but we need a particular relocation style.
  1433. if (llvm::Function *f = dyn_cast<llvm::Function>(fn)) {
  1434. if (!CGM.getLangOpts().ObjCRuntime.hasNativeARC())
  1435. f->setLinkage(llvm::Function::ExternalWeakLinkage);
  1436. // set nonlazybind attribute for these APIs for performance.
  1437. if (fnName == "objc_retain" || fnName == "objc_release")
  1438. f->addFnAttr(llvm::Attribute::NonLazyBind);
  1439. }
  1440. return fn;
  1441. }
  1442. /// Perform an operation having the signature
  1443. /// i8* (i8*)
  1444. /// where a null input causes a no-op and returns null.
  1445. static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF,
  1446. llvm::Value *value,
  1447. llvm::Constant *&fn,
  1448. StringRef fnName,
  1449. bool isTailCall = false) {
  1450. if (isa<llvm::ConstantPointerNull>(value)) return value;
  1451. if (!fn) {
  1452. std::vector<llvm::Type*> args(1, CGF.Int8PtrTy);
  1453. llvm::FunctionType *fnType =
  1454. llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
  1455. fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
  1456. }
  1457. // Cast the argument to 'id'.
  1458. llvm::Type *origType = value->getType();
  1459. value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
  1460. // Call the function.
  1461. llvm::CallInst *call = CGF.Builder.CreateCall(fn, value);
  1462. call->setDoesNotThrow();
  1463. if (isTailCall)
  1464. call->setTailCall();
  1465. // Cast the result back to the original type.
  1466. return CGF.Builder.CreateBitCast(call, origType);
  1467. }
  1468. /// Perform an operation having the following signature:
  1469. /// i8* (i8**)
  1470. static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF,
  1471. llvm::Value *addr,
  1472. llvm::Constant *&fn,
  1473. StringRef fnName) {
  1474. if (!fn) {
  1475. std::vector<llvm::Type*> args(1, CGF.Int8PtrPtrTy);
  1476. llvm::FunctionType *fnType =
  1477. llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
  1478. fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
  1479. }
  1480. // Cast the argument to 'id*'.
  1481. llvm::Type *origType = addr->getType();
  1482. addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
  1483. // Call the function.
  1484. llvm::CallInst *call = CGF.Builder.CreateCall(fn, addr);
  1485. call->setDoesNotThrow();
  1486. // Cast the result back to a dereference of the original type.
  1487. llvm::Value *result = call;
  1488. if (origType != CGF.Int8PtrPtrTy)
  1489. result = CGF.Builder.CreateBitCast(result,
  1490. cast<llvm::PointerType>(origType)->getElementType());
  1491. return result;
  1492. }
  1493. /// Perform an operation having the following signature:
  1494. /// i8* (i8**, i8*)
  1495. static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF,
  1496. llvm::Value *addr,
  1497. llvm::Value *value,
  1498. llvm::Constant *&fn,
  1499. StringRef fnName,
  1500. bool ignored) {
  1501. assert(cast<llvm::PointerType>(addr->getType())->getElementType()
  1502. == value->getType());
  1503. if (!fn) {
  1504. llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrTy };
  1505. llvm::FunctionType *fnType
  1506. = llvm::FunctionType::get(CGF.Int8PtrTy, argTypes, false);
  1507. fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
  1508. }
  1509. llvm::Type *origType = value->getType();
  1510. addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
  1511. value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
  1512. llvm::CallInst *result = CGF.Builder.CreateCall2(fn, addr, value);
  1513. result->setDoesNotThrow();
  1514. if (ignored) return 0;
  1515. return CGF.Builder.CreateBitCast(result, origType);
  1516. }
  1517. /// Perform an operation having the following signature:
  1518. /// void (i8**, i8**)
  1519. static void emitARCCopyOperation(CodeGenFunction &CGF,
  1520. llvm::Value *dst,
  1521. llvm::Value *src,
  1522. llvm::Constant *&fn,
  1523. StringRef fnName) {
  1524. assert(dst->getType() == src->getType());
  1525. if (!fn) {
  1526. std::vector<llvm::Type*> argTypes(2, CGF.Int8PtrPtrTy);
  1527. llvm::FunctionType *fnType
  1528. = llvm::FunctionType::get(CGF.Builder.getVoidTy(), argTypes, false);
  1529. fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
  1530. }
  1531. dst = CGF.Builder.CreateBitCast(dst, CGF.Int8PtrPtrTy);
  1532. src = CGF.Builder.CreateBitCast(src, CGF.Int8PtrPtrTy);
  1533. llvm::CallInst *result = CGF.Builder.CreateCall2(fn, dst, src);
  1534. result->setDoesNotThrow();
  1535. }
  1536. /// Produce the code to do a retain. Based on the type, calls one of:
  1537. /// call i8* \@objc_retain(i8* %value)
  1538. /// call i8* \@objc_retainBlock(i8* %value)
  1539. llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
  1540. if (type->isBlockPointerType())
  1541. return EmitARCRetainBlock(value, /*mandatory*/ false);
  1542. else
  1543. return EmitARCRetainNonBlock(value);
  1544. }
  1545. /// Retain the given object, with normal retain semantics.
  1546. /// call i8* \@objc_retain(i8* %value)
  1547. llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
  1548. return emitARCValueOperation(*this, value,
  1549. CGM.getARCEntrypoints().objc_retain,
  1550. "objc_retain");
  1551. }
  1552. /// Retain the given block, with _Block_copy semantics.
  1553. /// call i8* \@objc_retainBlock(i8* %value)
  1554. ///
  1555. /// \param mandatory - If false, emit the call with metadata
  1556. /// indicating that it's okay for the optimizer to eliminate this call
  1557. /// if it can prove that the block never escapes except down the stack.
  1558. llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
  1559. bool mandatory) {
  1560. llvm::Value *result
  1561. = emitARCValueOperation(*this, value,
  1562. CGM.getARCEntrypoints().objc_retainBlock,
  1563. "objc_retainBlock");
  1564. // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
  1565. // tell the optimizer that it doesn't need to do this copy if the
  1566. // block doesn't escape, where being passed as an argument doesn't
  1567. // count as escaping.
  1568. if (!mandatory && isa<llvm::Instruction>(result)) {
  1569. llvm::CallInst *call
  1570. = cast<llvm::CallInst>(result->stripPointerCasts());
  1571. assert(call->getCalledValue() == CGM.getARCEntrypoints().objc_retainBlock);
  1572. SmallVector<llvm::Value*,1> args;
  1573. call->setMetadata("clang.arc.copy_on_escape",
  1574. llvm::MDNode::get(Builder.getContext(), args));
  1575. }
  1576. return result;
  1577. }
  1578. /// Retain the given object which is the result of a function call.
  1579. /// call i8* \@objc_retainAutoreleasedReturnValue(i8* %value)
  1580. ///
  1581. /// Yes, this function name is one character away from a different
  1582. /// call with completely different semantics.
  1583. llvm::Value *
  1584. CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
  1585. // Fetch the void(void) inline asm which marks that we're going to
  1586. // retain the autoreleased return value.
  1587. llvm::InlineAsm *&marker
  1588. = CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker;
  1589. if (!marker) {
  1590. StringRef assembly
  1591. = CGM.getTargetCodeGenInfo()
  1592. .getARCRetainAutoreleasedReturnValueMarker();
  1593. // If we have an empty assembly string, there's nothing to do.
  1594. if (assembly.empty()) {
  1595. // Otherwise, at -O0, build an inline asm that we're going to call
  1596. // in a moment.
  1597. } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
  1598. llvm::FunctionType *type =
  1599. llvm::FunctionType::get(VoidTy, /*variadic*/false);
  1600. marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
  1601. // If we're at -O1 and above, we don't want to litter the code
  1602. // with this marker yet, so leave a breadcrumb for the ARC
  1603. // optimizer to pick up.
  1604. } else {
  1605. llvm::NamedMDNode *metadata =
  1606. CGM.getModule().getOrInsertNamedMetadata(
  1607. "clang.arc.retainAutoreleasedReturnValueMarker");
  1608. assert(metadata->getNumOperands() <= 1);
  1609. if (metadata->getNumOperands() == 0) {
  1610. llvm::Value *string = llvm::MDString::get(getLLVMContext(), assembly);
  1611. metadata->addOperand(llvm::MDNode::get(getLLVMContext(), string));
  1612. }
  1613. }
  1614. }
  1615. // Call the marker asm if we made one, which we do only at -O0.
  1616. if (marker) Builder.CreateCall(marker);
  1617. return emitARCValueOperation(*this, value,
  1618. CGM.getARCEntrypoints().objc_retainAutoreleasedReturnValue,
  1619. "objc_retainAutoreleasedReturnValue");
  1620. }
  1621. /// Release the given object.
  1622. /// call void \@objc_release(i8* %value)
  1623. void CodeGenFunction::EmitARCRelease(llvm::Value *value, bool precise) {
  1624. if (isa<llvm::ConstantPointerNull>(value)) return;
  1625. llvm::Constant *&fn = CGM.getARCEntrypoints().objc_release;
  1626. if (!fn) {
  1627. std::vector<llvm::Type*> args(1, Int8PtrTy);
  1628. llvm::FunctionType *fnType =
  1629. llvm::FunctionType::get(Builder.getVoidTy(), args, false);
  1630. fn = createARCRuntimeFunction(CGM, fnType, "objc_release");
  1631. }
  1632. // Cast the argument to 'id'.
  1633. value = Builder.CreateBitCast(value, Int8PtrTy);
  1634. // Call objc_release.
  1635. llvm::CallInst *call = Builder.CreateCall(fn, value);
  1636. call->setDoesNotThrow();
  1637. if (!precise) {
  1638. SmallVector<llvm::Value*,1> args;
  1639. call->setMetadata("clang.imprecise_release",
  1640. llvm::MDNode::get(Builder.getContext(), args));
  1641. }
  1642. }
  1643. /// Destroy a __strong variable.
  1644. ///
  1645. /// At -O0, emit a call to store 'null' into the address;
  1646. /// instrumenting tools prefer this because the address is exposed,
  1647. /// but it's relatively cumbersome to optimize.
  1648. ///
  1649. /// At -O1 and above, just load and call objc_release.
  1650. ///
  1651. /// call void \@objc_storeStrong(i8** %addr, i8* null)
  1652. void CodeGenFunction::EmitARCDestroyStrong(llvm::Value *addr, bool precise) {
  1653. if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
  1654. llvm::PointerType *addrTy = cast<llvm::PointerType>(addr->getType());
  1655. llvm::Value *null = llvm::ConstantPointerNull::get(
  1656. cast<llvm::PointerType>(addrTy->getElementType()));
  1657. EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
  1658. return;
  1659. }
  1660. llvm::Value *value = Builder.CreateLoad(addr);
  1661. EmitARCRelease(value, precise);
  1662. }
  1663. /// Store into a strong object. Always calls this:
  1664. /// call void \@objc_storeStrong(i8** %addr, i8* %value)
  1665. llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(llvm::Value *addr,
  1666. llvm::Value *value,
  1667. bool ignored) {
  1668. assert(cast<llvm::PointerType>(addr->getType())->getElementType()
  1669. == value->getType());
  1670. llvm::Constant *&fn = CGM.getARCEntrypoints().objc_storeStrong;
  1671. if (!fn) {
  1672. llvm::Type *argTypes[] = { Int8PtrPtrTy, Int8PtrTy };
  1673. llvm::FunctionType *fnType
  1674. = llvm::FunctionType::get(Builder.getVoidTy(), argTypes, false);
  1675. fn = createARCRuntimeFunction(CGM, fnType, "objc_storeStrong");
  1676. }
  1677. addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
  1678. llvm::Value *castValue = Builder.CreateBitCast(value, Int8PtrTy);
  1679. Builder.CreateCall2(fn, addr, castValue)->setDoesNotThrow();
  1680. if (ignored) return 0;
  1681. return value;
  1682. }
  1683. /// Store into a strong object. Sometimes calls this:
  1684. /// call void \@objc_storeStrong(i8** %addr, i8* %value)
  1685. /// Other times, breaks it down into components.
  1686. llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
  1687. llvm::Value *newValue,
  1688. bool ignored) {
  1689. QualType type = dst.getType();
  1690. bool isBlock = type->isBlockPointerType();
  1691. // Use a store barrier at -O0 unless this is a block type or the
  1692. // lvalue is inadequately aligned.
  1693. if (shouldUseFusedARCCalls() &&
  1694. !isBlock &&
  1695. (dst.getAlignment().isZero() ||
  1696. dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) {
  1697. return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
  1698. }
  1699. // Otherwise, split it out.
  1700. // Retain the new value.
  1701. newValue = EmitARCRetain(type, newValue);
  1702. // Read the old value.
  1703. llvm::Value *oldValue = EmitLoadOfScalar(dst);
  1704. // Store. We do this before the release so that any deallocs won't
  1705. // see the old value.
  1706. EmitStoreOfScalar(newValue, dst);
  1707. // Finally, release the old value.
  1708. EmitARCRelease(oldValue, /*precise*/ false);
  1709. return newValue;
  1710. }
  1711. /// Autorelease the given object.
  1712. /// call i8* \@objc_autorelease(i8* %value)
  1713. llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
  1714. return emitARCValueOperation(*this, value,
  1715. CGM.getARCEntrypoints().objc_autorelease,
  1716. "objc_autorelease");
  1717. }
  1718. /// Autorelease the given object.
  1719. /// call i8* \@objc_autoreleaseReturnValue(i8* %value)
  1720. llvm::Value *
  1721. CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
  1722. return emitARCValueOperation(*this, value,
  1723. CGM.getARCEntrypoints().objc_autoreleaseReturnValue,
  1724. "objc_autoreleaseReturnValue",
  1725. /*isTailCall*/ true);
  1726. }
  1727. /// Do a fused retain/autorelease of the given object.
  1728. /// call i8* \@objc_retainAutoreleaseReturnValue(i8* %value)
  1729. llvm::Value *
  1730. CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
  1731. return emitARCValueOperation(*this, value,
  1732. CGM.getARCEntrypoints().objc_retainAutoreleaseReturnValue,
  1733. "objc_retainAutoreleaseReturnValue",
  1734. /*isTailCall*/ true);
  1735. }
  1736. /// Do a fused retain/autorelease of the given object.
  1737. /// call i8* \@objc_retainAutorelease(i8* %value)
  1738. /// or
  1739. /// %retain = call i8* \@objc_retainBlock(i8* %value)
  1740. /// call i8* \@objc_autorelease(i8* %retain)
  1741. llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
  1742. llvm::Value *value) {
  1743. if (!type->isBlockPointerType())
  1744. return EmitARCRetainAutoreleaseNonBlock(value);
  1745. if (isa<llvm::ConstantPointerNull>(value)) return value;
  1746. llvm::Type *origType = value->getType();
  1747. value = Builder.CreateBitCast(value, Int8PtrTy);
  1748. value = EmitARCRetainBlock(value, /*mandatory*/ true);
  1749. value = EmitARCAutorelease(value);
  1750. return Builder.CreateBitCast(value, origType);
  1751. }
  1752. /// Do a fused retain/autorelease of the given object.
  1753. /// call i8* \@objc_retainAutorelease(i8* %value)
  1754. llvm::Value *
  1755. CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
  1756. return emitARCValueOperation(*this, value,
  1757. CGM.getARCEntrypoints().objc_retainAutorelease,
  1758. "objc_retainAutorelease");
  1759. }
  1760. /// i8* \@objc_loadWeak(i8** %addr)
  1761. /// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
  1762. llvm::Value *CodeGenFunction::EmitARCLoadWeak(llvm::Value *addr) {
  1763. return emitARCLoadOperation(*this, addr,
  1764. CGM.getARCEntrypoints().objc_loadWeak,
  1765. "objc_loadWeak");
  1766. }
  1767. /// i8* \@objc_loadWeakRetained(i8** %addr)
  1768. llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(llvm::Value *addr) {
  1769. return emitARCLoadOperation(*this, addr,
  1770. CGM.getARCEntrypoints().objc_loadWeakRetained,
  1771. "objc_loadWeakRetained");
  1772. }
  1773. /// i8* \@objc_storeWeak(i8** %addr, i8* %value)
  1774. /// Returns %value.
  1775. llvm::Value *CodeGenFunction::EmitARCStoreWeak(llvm::Value *addr,
  1776. llvm::Value *value,
  1777. bool ignored) {
  1778. return emitARCStoreOperation(*this, addr, value,
  1779. CGM.getARCEntrypoints().objc_storeWeak,
  1780. "objc_storeWeak", ignored);
  1781. }
  1782. /// i8* \@objc_initWeak(i8** %addr, i8* %value)
  1783. /// Returns %value. %addr is known to not have a current weak entry.
  1784. /// Essentially equivalent to:
  1785. /// *addr = nil; objc_storeWeak(addr, value);
  1786. void CodeGenFunction::EmitARCInitWeak(llvm::Value *addr, llvm::Value *value) {
  1787. // If we're initializing to null, just write null to memory; no need
  1788. // to get the runtime involved. But don't do this if optimization
  1789. // is enabled, because accounting for this would make the optimizer
  1790. // much more complicated.
  1791. if (isa<llvm::ConstantPointerNull>(value) &&
  1792. CGM.getCodeGenOpts().OptimizationLevel == 0) {
  1793. Builder.CreateStore(value, addr);
  1794. return;
  1795. }
  1796. emitARCStoreOperation(*this, addr, value,
  1797. CGM.getARCEntrypoints().objc_initWeak,
  1798. "objc_initWeak", /*ignored*/ true);
  1799. }
  1800. /// void \@objc_destroyWeak(i8** %addr)
  1801. /// Essentially objc_storeWeak(addr, nil).
  1802. void CodeGenFunction::EmitARCDestroyWeak(llvm::Value *addr) {
  1803. llvm::Constant *&fn = CGM.getARCEntrypoints().objc_destroyWeak;
  1804. if (!fn) {
  1805. std::vector<llvm::Type*> args(1, Int8PtrPtrTy);
  1806. llvm::FunctionType *fnType =
  1807. llvm::FunctionType::get(Builder.getVoidTy(), args, false);
  1808. fn = createARCRuntimeFunction(CGM, fnType, "objc_destroyWeak");
  1809. }
  1810. // Cast the argument to 'id*'.
  1811. addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
  1812. llvm::CallInst *call = Builder.CreateCall(fn, addr);
  1813. call->setDoesNotThrow();
  1814. }
  1815. /// void \@objc_moveWeak(i8** %dest, i8** %src)
  1816. /// Disregards the current value in %dest. Leaves %src pointing to nothing.
  1817. /// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
  1818. void CodeGenFunction::EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src) {
  1819. emitARCCopyOperation(*this, dst, src,
  1820. CGM.getARCEntrypoints().objc_moveWeak,
  1821. "objc_moveWeak");
  1822. }
  1823. /// void \@objc_copyWeak(i8** %dest, i8** %src)
  1824. /// Disregards the current value in %dest. Essentially
  1825. /// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
  1826. void CodeGenFunction::EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src) {
  1827. emitARCCopyOperation(*this, dst, src,
  1828. CGM.getARCEntrypoints().objc_copyWeak,
  1829. "objc_copyWeak");
  1830. }
  1831. /// Produce the code to do a objc_autoreleasepool_push.
  1832. /// call i8* \@objc_autoreleasePoolPush(void)
  1833. llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
  1834. llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPush;
  1835. if (!fn) {
  1836. llvm::FunctionType *fnType =
  1837. llvm::FunctionType::get(Int8PtrTy, false);
  1838. fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPush");
  1839. }
  1840. llvm::CallInst *call = Builder.CreateCall(fn);
  1841. call->setDoesNotThrow();
  1842. return call;
  1843. }
  1844. /// Produce the code to do a primitive release.
  1845. /// call void \@objc_autoreleasePoolPop(i8* %ptr)
  1846. void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
  1847. assert(value->getType() == Int8PtrTy);
  1848. llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPop;
  1849. if (!fn) {
  1850. std::vector<llvm::Type*> args(1, Int8PtrTy);
  1851. llvm::FunctionType *fnType =
  1852. llvm::FunctionType::get(Builder.getVoidTy(), args, false);
  1853. // We don't want to use a weak import here; instead we should not
  1854. // fall into this path.
  1855. fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPop");
  1856. }
  1857. llvm::CallInst *call = Builder.CreateCall(fn, value);
  1858. call->setDoesNotThrow();
  1859. }
  1860. /// Produce the code to do an MRR version objc_autoreleasepool_push.
  1861. /// Which is: [[NSAutoreleasePool alloc] init];
  1862. /// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
  1863. /// init is declared as: - (id) init; in its NSObject super class.
  1864. ///
  1865. llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
  1866. CGObjCRuntime &Runtime = CGM.getObjCRuntime();
  1867. llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(Builder);
  1868. // [NSAutoreleasePool alloc]
  1869. IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
  1870. Selector AllocSel = getContext().Selectors.getSelector(0, &II);
  1871. CallArgList Args;
  1872. RValue AllocRV =
  1873. Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
  1874. getContext().getObjCIdType(),
  1875. AllocSel, Receiver, Args);
  1876. // [Receiver init]
  1877. Receiver = AllocRV.getScalarVal();
  1878. II = &CGM.getContext().Idents.get("init");
  1879. Selector InitSel = getContext().Selectors.getSelector(0, &II);
  1880. RValue InitRV =
  1881. Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
  1882. getContext().getObjCIdType(),
  1883. InitSel, Receiver, Args);
  1884. return InitRV.getScalarVal();
  1885. }
  1886. /// Produce the code to do a primitive release.
  1887. /// [tmp drain];
  1888. void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
  1889. IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
  1890. Selector DrainSel = getContext().Selectors.getSelector(0, &II);
  1891. CallArgList Args;
  1892. CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
  1893. getContext().VoidTy, DrainSel, Arg, Args);
  1894. }
  1895. void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
  1896. llvm::Value *addr,
  1897. QualType type) {
  1898. CGF.EmitARCDestroyStrong(addr, /*precise*/ true);
  1899. }
  1900. void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
  1901. llvm::Value *addr,
  1902. QualType type) {
  1903. CGF.EmitARCDestroyStrong(addr, /*precise*/ false);
  1904. }
  1905. void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
  1906. llvm::Value *addr,
  1907. QualType type) {
  1908. CGF.EmitARCDestroyWeak(addr);
  1909. }
  1910. namespace {
  1911. struct CallObjCAutoreleasePoolObject : EHScopeStack::Cleanup {
  1912. llvm::Value *Token;
  1913. CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
  1914. void Emit(CodeGenFunction &CGF, Flags flags) {
  1915. CGF.EmitObjCAutoreleasePoolPop(Token);
  1916. }
  1917. };
  1918. struct CallObjCMRRAutoreleasePoolObject : EHScopeStack::Cleanup {
  1919. llvm::Value *Token;
  1920. CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
  1921. void Emit(CodeGenFunction &CGF, Flags flags) {
  1922. CGF.EmitObjCMRRAutoreleasePoolPop(Token);
  1923. }
  1924. };
  1925. }
  1926. void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
  1927. if (CGM.getLangOpts().ObjCAutoRefCount)
  1928. EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
  1929. else
  1930. EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
  1931. }
  1932. static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
  1933. LValue lvalue,
  1934. QualType type) {
  1935. switch (type.getObjCLifetime()) {
  1936. case Qualifiers::OCL_None:
  1937. case Qualifiers::OCL_ExplicitNone:
  1938. case Qualifiers::OCL_Strong:
  1939. case Qualifiers::OCL_Autoreleasing:
  1940. return TryEmitResult(CGF.EmitLoadOfLValue(lvalue).getScalarVal(),
  1941. false);
  1942. case Qualifiers::OCL_Weak:
  1943. return TryEmitResult(CGF.EmitARCLoadWeakRetained(lvalue.getAddress()),
  1944. true);
  1945. }
  1946. llvm_unreachable("impossible lifetime!");
  1947. }
  1948. static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
  1949. const Expr *e) {
  1950. e = e->IgnoreParens();
  1951. QualType type = e->getType();
  1952. // If we're loading retained from a __strong xvalue, we can avoid
  1953. // an extra retain/release pair by zeroing out the source of this
  1954. // "move" operation.
  1955. if (e->isXValue() &&
  1956. !type.isConstQualified() &&
  1957. type.getObjCLifetime() == Qualifiers::OCL_Strong) {
  1958. // Emit the lvalue.
  1959. LValue lv = CGF.EmitLValue(e);
  1960. // Load the object pointer.
  1961. llvm::Value *result = CGF.EmitLoadOfLValue(lv).getScalarVal();
  1962. // Set the source pointer to NULL.
  1963. CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv);
  1964. return TryEmitResult(result, true);
  1965. }
  1966. // As a very special optimization, in ARC++, if the l-value is the
  1967. // result of a non-volatile assignment, do a simple retain of the
  1968. // result of the call to objc_storeWeak instead of reloading.
  1969. if (CGF.getLangOpts().CPlusPlus &&
  1970. !type.isVolatileQualified() &&
  1971. type.getObjCLifetime() == Qualifiers::OCL_Weak &&
  1972. isa<BinaryOperator>(e) &&
  1973. cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
  1974. return TryEmitResult(CGF.EmitScalarExpr(e), false);
  1975. return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
  1976. }
  1977. static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
  1978. llvm::Value *value);
  1979. /// Given that the given expression is some sort of call (which does
  1980. /// not return retained), emit a retain following it.
  1981. static llvm::Value *emitARCRetainCall(CodeGenFunction &CGF, const Expr *e) {
  1982. llvm::Value *value = CGF.EmitScalarExpr(e);
  1983. return emitARCRetainAfterCall(CGF, value);
  1984. }
  1985. static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
  1986. llvm::Value *value) {
  1987. if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
  1988. CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
  1989. // Place the retain immediately following the call.
  1990. CGF.Builder.SetInsertPoint(call->getParent(),
  1991. ++llvm::BasicBlock::iterator(call));
  1992. value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
  1993. CGF.Builder.restoreIP(ip);
  1994. return value;
  1995. } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
  1996. CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
  1997. // Place the retain at the beginning of the normal destination block.
  1998. llvm::BasicBlock *BB = invoke->getNormalDest();
  1999. CGF.Builder.SetInsertPoint(BB, BB->begin());
  2000. value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
  2001. CGF.Builder.restoreIP(ip);
  2002. return value;
  2003. // Bitcasts can arise because of related-result returns. Rewrite
  2004. // the operand.
  2005. } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
  2006. llvm::Value *operand = bitcast->getOperand(0);
  2007. operand = emitARCRetainAfterCall(CGF, operand);
  2008. bitcast->setOperand(0, operand);
  2009. return bitcast;
  2010. // Generic fall-back case.
  2011. } else {
  2012. // Retain using the non-block variant: we never need to do a copy
  2013. // of a block that's been returned to us.
  2014. return CGF.EmitARCRetainNonBlock(value);
  2015. }
  2016. }
  2017. /// Determine whether it might be important to emit a separate
  2018. /// objc_retain_block on the result of the given expression, or
  2019. /// whether it's okay to just emit it in a +1 context.
  2020. static bool shouldEmitSeparateBlockRetain(const Expr *e) {
  2021. assert(e->getType()->isBlockPointerType());
  2022. e = e->IgnoreParens();
  2023. // For future goodness, emit block expressions directly in +1
  2024. // contexts if we can.
  2025. if (isa<BlockExpr>(e))
  2026. return false;
  2027. if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
  2028. switch (cast->getCastKind()) {
  2029. // Emitting these operations in +1 contexts is goodness.
  2030. case CK_LValueToRValue:
  2031. case CK_ARCReclaimReturnedObject:
  2032. case CK_ARCConsumeObject:
  2033. case CK_ARCProduceObject:
  2034. return false;
  2035. // These operations preserve a block type.
  2036. case CK_NoOp:
  2037. case CK_BitCast:
  2038. return shouldEmitSeparateBlockRetain(cast->getSubExpr());
  2039. // These operations are known to be bad (or haven't been considered).
  2040. case CK_AnyPointerToBlockPointerCast:
  2041. default:
  2042. return true;
  2043. }
  2044. }
  2045. return true;
  2046. }
  2047. /// Try to emit a PseudoObjectExpr at +1.
  2048. ///
  2049. /// This massively duplicates emitPseudoObjectRValue.
  2050. static TryEmitResult tryEmitARCRetainPseudoObject(CodeGenFunction &CGF,
  2051. const PseudoObjectExpr *E) {
  2052. SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
  2053. // Find the result expression.
  2054. const Expr *resultExpr = E->getResultExpr();
  2055. assert(resultExpr);
  2056. TryEmitResult result;
  2057. for (PseudoObjectExpr::const_semantics_iterator
  2058. i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
  2059. const Expr *semantic = *i;
  2060. // If this semantic expression is an opaque value, bind it
  2061. // to the result of its source expression.
  2062. if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
  2063. typedef CodeGenFunction::OpaqueValueMappingData OVMA;
  2064. OVMA opaqueData;
  2065. // If this semantic is the result of the pseudo-object
  2066. // expression, try to evaluate the source as +1.
  2067. if (ov == resultExpr) {
  2068. assert(!OVMA::shouldBindAsLValue(ov));
  2069. result = tryEmitARCRetainScalarExpr(CGF, ov->getSourceExpr());
  2070. opaqueData = OVMA::bind(CGF, ov, RValue::get(result.getPointer()));
  2071. // Otherwise, just bind it.
  2072. } else {
  2073. opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
  2074. }
  2075. opaques.push_back(opaqueData);
  2076. // Otherwise, if the expression is the result, evaluate it
  2077. // and remember the result.
  2078. } else if (semantic == resultExpr) {
  2079. result = tryEmitARCRetainScalarExpr(CGF, semantic);
  2080. // Otherwise, evaluate the expression in an ignored context.
  2081. } else {
  2082. CGF.EmitIgnoredExpr(semantic);
  2083. }
  2084. }
  2085. // Unbind all the opaques now.
  2086. for (unsigned i = 0, e = opaques.size(); i != e; ++i)
  2087. opaques[i].unbind(CGF);
  2088. return result;
  2089. }
  2090. static TryEmitResult
  2091. tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
  2092. // Look through cleanups.
  2093. if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
  2094. CGF.enterFullExpression(cleanups);
  2095. CodeGenFunction::RunCleanupsScope scope(CGF);
  2096. return tryEmitARCRetainScalarExpr(CGF, cleanups->getSubExpr());
  2097. }
  2098. // The desired result type, if it differs from the type of the
  2099. // ultimate opaque expression.
  2100. llvm::Type *resultType = 0;
  2101. while (true) {
  2102. e = e->IgnoreParens();
  2103. // There's a break at the end of this if-chain; anything
  2104. // that wants to keep looping has to explicitly continue.
  2105. if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
  2106. switch (ce->getCastKind()) {
  2107. // No-op casts don't change the type, so we just ignore them.
  2108. case CK_NoOp:
  2109. e = ce->getSubExpr();
  2110. continue;
  2111. case CK_LValueToRValue: {
  2112. TryEmitResult loadResult
  2113. = tryEmitARCRetainLoadOfScalar(CGF, ce->getSubExpr());
  2114. if (resultType) {
  2115. llvm::Value *value = loadResult.getPointer();
  2116. value = CGF.Builder.CreateBitCast(value, resultType);
  2117. loadResult.setPointer(value);
  2118. }
  2119. return loadResult;
  2120. }
  2121. // These casts can change the type, so remember that and
  2122. // soldier on. We only need to remember the outermost such
  2123. // cast, though.
  2124. case CK_CPointerToObjCPointerCast:
  2125. case CK_BlockPointerToObjCPointerCast:
  2126. case CK_AnyPointerToBlockPointerCast:
  2127. case CK_BitCast:
  2128. if (!resultType)
  2129. resultType = CGF.ConvertType(ce->getType());
  2130. e = ce->getSubExpr();
  2131. assert(e->getType()->hasPointerRepresentation());
  2132. continue;
  2133. // For consumptions, just emit the subexpression and thus elide
  2134. // the retain/release pair.
  2135. case CK_ARCConsumeObject: {
  2136. llvm::Value *result = CGF.EmitScalarExpr(ce->getSubExpr());
  2137. if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
  2138. return TryEmitResult(result, true);
  2139. }
  2140. // Block extends are net +0. Naively, we could just recurse on
  2141. // the subexpression, but actually we need to ensure that the
  2142. // value is copied as a block, so there's a little filter here.
  2143. case CK_ARCExtendBlockObject: {
  2144. llvm::Value *result; // will be a +0 value
  2145. // If we can't safely assume the sub-expression will produce a
  2146. // block-copied value, emit the sub-expression at +0.
  2147. if (shouldEmitSeparateBlockRetain(ce->getSubExpr())) {
  2148. result = CGF.EmitScalarExpr(ce->getSubExpr());
  2149. // Otherwise, try to emit the sub-expression at +1 recursively.
  2150. } else {
  2151. TryEmitResult subresult
  2152. = tryEmitARCRetainScalarExpr(CGF, ce->getSubExpr());
  2153. result = subresult.getPointer();
  2154. // If that produced a retained value, just use that,
  2155. // possibly casting down.
  2156. if (subresult.getInt()) {
  2157. if (resultType)
  2158. result = CGF.Builder.CreateBitCast(result, resultType);
  2159. return TryEmitResult(result, true);
  2160. }
  2161. // Otherwise it's +0.
  2162. }
  2163. // Retain the object as a block, then cast down.
  2164. result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
  2165. if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
  2166. return TryEmitResult(result, true);
  2167. }
  2168. // For reclaims, emit the subexpression as a retained call and
  2169. // skip the consumption.
  2170. case CK_ARCReclaimReturnedObject: {
  2171. llvm::Value *result = emitARCRetainCall(CGF, ce->getSubExpr());
  2172. if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
  2173. return TryEmitResult(result, true);
  2174. }
  2175. default:
  2176. break;
  2177. }
  2178. // Skip __extension__.
  2179. } else if (const UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
  2180. if (op->getOpcode() == UO_Extension) {
  2181. e = op->getSubExpr();
  2182. continue;
  2183. }
  2184. // For calls and message sends, use the retained-call logic.
  2185. // Delegate inits are a special case in that they're the only
  2186. // returns-retained expression that *isn't* surrounded by
  2187. // a consume.
  2188. } else if (isa<CallExpr>(e) ||
  2189. (isa<ObjCMessageExpr>(e) &&
  2190. !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
  2191. llvm::Value *result = emitARCRetainCall(CGF, e);
  2192. if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
  2193. return TryEmitResult(result, true);
  2194. // Look through pseudo-object expressions.
  2195. } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
  2196. TryEmitResult result
  2197. = tryEmitARCRetainPseudoObject(CGF, pseudo);
  2198. if (resultType) {
  2199. llvm::Value *value = result.getPointer();
  2200. value = CGF.Builder.CreateBitCast(value, resultType);
  2201. result.setPointer(value);
  2202. }
  2203. return result;
  2204. }
  2205. // Conservatively halt the search at any other expression kind.
  2206. break;
  2207. }
  2208. // We didn't find an obvious production, so emit what we've got and
  2209. // tell the caller that we didn't manage to retain.
  2210. llvm::Value *result = CGF.EmitScalarExpr(e);
  2211. if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
  2212. return TryEmitResult(result, false);
  2213. }
  2214. static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
  2215. LValue lvalue,
  2216. QualType type) {
  2217. TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
  2218. llvm::Value *value = result.getPointer();
  2219. if (!result.getInt())
  2220. value = CGF.EmitARCRetain(type, value);
  2221. return value;
  2222. }
  2223. /// EmitARCRetainScalarExpr - Semantically equivalent to
  2224. /// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
  2225. /// best-effort attempt to peephole expressions that naturally produce
  2226. /// retained objects.
  2227. llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
  2228. TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
  2229. llvm::Value *value = result.getPointer();
  2230. if (!result.getInt())
  2231. value = EmitARCRetain(e->getType(), value);
  2232. return value;
  2233. }
  2234. llvm::Value *
  2235. CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
  2236. TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
  2237. llvm::Value *value = result.getPointer();
  2238. if (result.getInt())
  2239. value = EmitARCAutorelease(value);
  2240. else
  2241. value = EmitARCRetainAutorelease(e->getType(), value);
  2242. return value;
  2243. }
  2244. llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {
  2245. llvm::Value *result;
  2246. bool doRetain;
  2247. if (shouldEmitSeparateBlockRetain(e)) {
  2248. result = EmitScalarExpr(e);
  2249. doRetain = true;
  2250. } else {
  2251. TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
  2252. result = subresult.getPointer();
  2253. doRetain = !subresult.getInt();
  2254. }
  2255. if (doRetain)
  2256. result = EmitARCRetainBlock(result, /*mandatory*/ true);
  2257. return EmitObjCConsumeObject(e->getType(), result);
  2258. }
  2259. llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
  2260. // In ARC, retain and autorelease the expression.
  2261. if (getLangOpts().ObjCAutoRefCount) {
  2262. // Do so before running any cleanups for the full-expression.
  2263. // tryEmitARCRetainScalarExpr does make an effort to do things
  2264. // inside cleanups, but there are crazy cases like
  2265. // @throw A().foo;
  2266. // where a full retain+autorelease is required and would
  2267. // otherwise happen after the destructor for the temporary.
  2268. if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(expr)) {
  2269. enterFullExpression(ewc);
  2270. expr = ewc->getSubExpr();
  2271. }
  2272. CodeGenFunction::RunCleanupsScope cleanups(*this);
  2273. return EmitARCRetainAutoreleaseScalarExpr(expr);
  2274. }
  2275. // Otherwise, use the normal scalar-expression emission. The
  2276. // exception machinery doesn't do anything special with the
  2277. // exception like retaining it, so there's no safety associated with
  2278. // only running cleanups after the throw has started, and when it
  2279. // matters it tends to be substantially inferior code.
  2280. return EmitScalarExpr(expr);
  2281. }
  2282. std::pair<LValue,llvm::Value*>
  2283. CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
  2284. bool ignored) {
  2285. // Evaluate the RHS first.
  2286. TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
  2287. llvm::Value *value = result.getPointer();
  2288. bool hasImmediateRetain = result.getInt();
  2289. // If we didn't emit a retained object, and the l-value is of block
  2290. // type, then we need to emit the block-retain immediately in case
  2291. // it invalidates the l-value.
  2292. if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
  2293. value = EmitARCRetainBlock(value, /*mandatory*/ false);
  2294. hasImmediateRetain = true;
  2295. }
  2296. LValue lvalue = EmitLValue(e->getLHS());
  2297. // If the RHS was emitted retained, expand this.
  2298. if (hasImmediateRetain) {
  2299. llvm::Value *oldValue =
  2300. EmitLoadOfScalar(lvalue);
  2301. EmitStoreOfScalar(value, lvalue);
  2302. EmitARCRelease(oldValue, /*precise*/ false);
  2303. } else {
  2304. value = EmitARCStoreStrong(lvalue, value, ignored);
  2305. }
  2306. return std::pair<LValue,llvm::Value*>(lvalue, value);
  2307. }
  2308. std::pair<LValue,llvm::Value*>
  2309. CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
  2310. llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
  2311. LValue lvalue = EmitLValue(e->getLHS());
  2312. EmitStoreOfScalar(value, lvalue);
  2313. return std::pair<LValue,llvm::Value*>(lvalue, value);
  2314. }
  2315. void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
  2316. const ObjCAutoreleasePoolStmt &ARPS) {
  2317. const Stmt *subStmt = ARPS.getSubStmt();
  2318. const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
  2319. CGDebugInfo *DI = getDebugInfo();
  2320. if (DI)
  2321. DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
  2322. // Keep track of the current cleanup stack depth.
  2323. RunCleanupsScope Scope(*this);
  2324. if (CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
  2325. llvm::Value *token = EmitObjCAutoreleasePoolPush();
  2326. EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
  2327. } else {
  2328. llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
  2329. EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
  2330. }
  2331. for (CompoundStmt::const_body_iterator I = S.body_begin(),
  2332. E = S.body_end(); I != E; ++I)
  2333. EmitStmt(*I);
  2334. if (DI)
  2335. DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
  2336. }
  2337. /// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
  2338. /// make sure it survives garbage collection until this point.
  2339. void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
  2340. // We just use an inline assembly.
  2341. llvm::FunctionType *extenderType
  2342. = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All);
  2343. llvm::Value *extender
  2344. = llvm::InlineAsm::get(extenderType,
  2345. /* assembly */ "",
  2346. /* constraints */ "r",
  2347. /* side effects */ true);
  2348. object = Builder.CreateBitCast(object, VoidPtrTy);
  2349. Builder.CreateCall(extender, object)->setDoesNotThrow();
  2350. }
  2351. /// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with
  2352. /// non-trivial copy assignment function, produce following helper function.
  2353. /// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
  2354. ///
  2355. llvm::Constant *
  2356. CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction(
  2357. const ObjCPropertyImplDecl *PID) {
  2358. if (!getLangOpts().CPlusPlus ||
  2359. !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
  2360. return 0;
  2361. QualType Ty = PID->getPropertyIvarDecl()->getType();
  2362. if (!Ty->isRecordType())
  2363. return 0;
  2364. const ObjCPropertyDecl *PD = PID->getPropertyDecl();
  2365. if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
  2366. return 0;
  2367. llvm::Constant * HelperFn = 0;
  2368. if (hasTrivialSetExpr(PID))
  2369. return 0;
  2370. assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
  2371. if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))
  2372. return HelperFn;
  2373. ASTContext &C = getContext();
  2374. IdentifierInfo *II
  2375. = &CGM.getContext().Idents.get("__assign_helper_atomic_property_");
  2376. FunctionDecl *FD = FunctionDecl::Create(C,
  2377. C.getTranslationUnitDecl(),
  2378. SourceLocation(),
  2379. SourceLocation(), II, C.VoidTy, 0,
  2380. SC_Static,
  2381. SC_None,
  2382. false,
  2383. false);
  2384. QualType DestTy = C.getPointerType(Ty);
  2385. QualType SrcTy = Ty;
  2386. SrcTy.addConst();
  2387. SrcTy = C.getPointerType(SrcTy);
  2388. FunctionArgList args;
  2389. ImplicitParamDecl dstDecl(FD, SourceLocation(), 0, DestTy);
  2390. args.push_back(&dstDecl);
  2391. ImplicitParamDecl srcDecl(FD, SourceLocation(), 0, SrcTy);
  2392. args.push_back(&srcDecl);
  2393. const CGFunctionInfo &FI =
  2394. CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
  2395. FunctionType::ExtInfo(),
  2396. RequiredArgs::All);
  2397. llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
  2398. llvm::Function *Fn =
  2399. llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
  2400. "__assign_helper_atomic_property_",
  2401. &CGM.getModule());
  2402. // Initialize debug info if needed.
  2403. maybeInitializeDebugInfo();
  2404. StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
  2405. DeclRefExpr DstExpr(&dstDecl, false, DestTy,
  2406. VK_RValue, SourceLocation());
  2407. UnaryOperator DST(&DstExpr, UO_Deref, DestTy->getPointeeType(),
  2408. VK_LValue, OK_Ordinary, SourceLocation());
  2409. DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
  2410. VK_RValue, SourceLocation());
  2411. UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
  2412. VK_LValue, OK_Ordinary, SourceLocation());
  2413. Expr *Args[2] = { &DST, &SRC };
  2414. CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
  2415. CXXOperatorCallExpr TheCall(C, OO_Equal, CalleeExp->getCallee(),
  2416. Args, DestTy->getPointeeType(),
  2417. VK_LValue, SourceLocation(), false);
  2418. EmitStmt(&TheCall);
  2419. FinishFunction();
  2420. HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
  2421. CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
  2422. return HelperFn;
  2423. }
  2424. llvm::Constant *
  2425. CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(
  2426. const ObjCPropertyImplDecl *PID) {
  2427. if (!getLangOpts().CPlusPlus ||
  2428. !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
  2429. return 0;
  2430. const ObjCPropertyDecl *PD = PID->getPropertyDecl();
  2431. QualType Ty = PD->getType();
  2432. if (!Ty->isRecordType())
  2433. return 0;
  2434. if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
  2435. return 0;
  2436. llvm::Constant * HelperFn = 0;
  2437. if (hasTrivialGetExpr(PID))
  2438. return 0;
  2439. assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");
  2440. if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
  2441. return HelperFn;
  2442. ASTContext &C = getContext();
  2443. IdentifierInfo *II
  2444. = &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
  2445. FunctionDecl *FD = FunctionDecl::Create(C,
  2446. C.getTranslationUnitDecl(),
  2447. SourceLocation(),
  2448. SourceLocation(), II, C.VoidTy, 0,
  2449. SC_Static,
  2450. SC_None,
  2451. false,
  2452. false);
  2453. QualType DestTy = C.getPointerType(Ty);
  2454. QualType SrcTy = Ty;
  2455. SrcTy.addConst();
  2456. SrcTy = C.getPointerType(SrcTy);
  2457. FunctionArgList args;
  2458. ImplicitParamDecl dstDecl(FD, SourceLocation(), 0, DestTy);
  2459. args.push_back(&dstDecl);
  2460. ImplicitParamDecl srcDecl(FD, SourceLocation(), 0, SrcTy);
  2461. args.push_back(&srcDecl);
  2462. const CGFunctionInfo &FI =
  2463. CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
  2464. FunctionType::ExtInfo(),
  2465. RequiredArgs::All);
  2466. llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
  2467. llvm::Function *Fn =
  2468. llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
  2469. "__copy_helper_atomic_property_", &CGM.getModule());
  2470. // Initialize debug info if needed.
  2471. maybeInitializeDebugInfo();
  2472. StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
  2473. DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
  2474. VK_RValue, SourceLocation());
  2475. UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
  2476. VK_LValue, OK_Ordinary, SourceLocation());
  2477. CXXConstructExpr *CXXConstExpr =
  2478. cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
  2479. SmallVector<Expr*, 4> ConstructorArgs;
  2480. ConstructorArgs.push_back(&SRC);
  2481. CXXConstructExpr::arg_iterator A = CXXConstExpr->arg_begin();
  2482. ++A;
  2483. for (CXXConstructExpr::arg_iterator AEnd = CXXConstExpr->arg_end();
  2484. A != AEnd; ++A)
  2485. ConstructorArgs.push_back(*A);
  2486. CXXConstructExpr *TheCXXConstructExpr =
  2487. CXXConstructExpr::Create(C, Ty, SourceLocation(),
  2488. CXXConstExpr->getConstructor(),
  2489. CXXConstExpr->isElidable(),
  2490. ConstructorArgs,
  2491. CXXConstExpr->hadMultipleCandidates(),
  2492. CXXConstExpr->isListInitialization(),
  2493. CXXConstExpr->requiresZeroInitialization(),
  2494. CXXConstExpr->getConstructionKind(),
  2495. SourceRange());
  2496. DeclRefExpr DstExpr(&dstDecl, false, DestTy,
  2497. VK_RValue, SourceLocation());
  2498. RValue DV = EmitAnyExpr(&DstExpr);
  2499. CharUnits Alignment
  2500. = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());
  2501. EmitAggExpr(TheCXXConstructExpr,
  2502. AggValueSlot::forAddr(DV.getScalarVal(), Alignment, Qualifiers(),
  2503. AggValueSlot::IsDestructed,
  2504. AggValueSlot::DoesNotNeedGCBarriers,
  2505. AggValueSlot::IsNotAliased));
  2506. FinishFunction();
  2507. HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
  2508. CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);
  2509. return HelperFn;
  2510. }
  2511. llvm::Value *
  2512. CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty) {
  2513. // Get selectors for retain/autorelease.
  2514. IdentifierInfo *CopyID = &getContext().Idents.get("copy");
  2515. Selector CopySelector =
  2516. getContext().Selectors.getNullarySelector(CopyID);
  2517. IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease");
  2518. Selector AutoreleaseSelector =
  2519. getContext().Selectors.getNullarySelector(AutoreleaseID);
  2520. // Emit calls to retain/autorelease.
  2521. CGObjCRuntime &Runtime = CGM.getObjCRuntime();
  2522. llvm::Value *Val = Block;
  2523. RValue Result;
  2524. Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
  2525. Ty, CopySelector,
  2526. Val, CallArgList(), 0, 0);
  2527. Val = Result.getScalarVal();
  2528. Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
  2529. Ty, AutoreleaseSelector,
  2530. Val, CallArgList(), 0, 0);
  2531. Val = Result.getScalarVal();
  2532. return Val;
  2533. }
  2534. CGObjCRuntime::~CGObjCRuntime() {}