CGObjC.cpp 112 KB

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