CGObjC.cpp 153 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030
  1. //===---- CGObjC.cpp - Emit LLVM Code for Objective-C ---------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This contains code to emit Objective-C code as LLVM code.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "CGDebugInfo.h"
  13. #include "CGObjCRuntime.h"
  14. #include "CodeGenFunction.h"
  15. #include "CodeGenModule.h"
  16. #include "ConstantEmitter.h"
  17. #include "TargetInfo.h"
  18. #include "clang/AST/ASTContext.h"
  19. #include "clang/AST/Attr.h"
  20. #include "clang/AST/DeclObjC.h"
  21. #include "clang/AST/StmtObjC.h"
  22. #include "clang/Basic/Diagnostic.h"
  23. #include "clang/CodeGen/CGFunctionInfo.h"
  24. #include "llvm/ADT/STLExtras.h"
  25. #include "llvm/Analysis/ObjCARCUtil.h"
  26. #include "llvm/BinaryFormat/MachO.h"
  27. #include "llvm/IR/DataLayout.h"
  28. #include "llvm/IR/InlineAsm.h"
  29. using namespace clang;
  30. using namespace CodeGen;
  31. typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult;
  32. static TryEmitResult
  33. tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e);
  34. static RValue AdjustObjCObjectType(CodeGenFunction &CGF,
  35. QualType ET,
  36. RValue Result);
  37. /// Given the address of a variable of pointer type, find the correct
  38. /// null to store into it.
  39. static llvm::Constant *getNullForVariable(Address addr) {
  40. llvm::Type *type = addr.getElementType();
  41. return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type));
  42. }
  43. /// Emits an instance of NSConstantString representing the object.
  44. llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
  45. {
  46. llvm::Constant *C =
  47. CGM.getObjCRuntime().GenerateConstantString(E->getString()).getPointer();
  48. // FIXME: This bitcast should just be made an invariant on the Runtime.
  49. return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
  50. }
  51. /// EmitObjCBoxedExpr - This routine generates code to call
  52. /// the appropriate expression boxing method. This will either be
  53. /// one of +[NSNumber numberWith<Type>:], or +[NSString stringWithUTF8String:],
  54. /// or [NSValue valueWithBytes:objCType:].
  55. ///
  56. llvm::Value *
  57. CodeGenFunction::EmitObjCBoxedExpr(const ObjCBoxedExpr *E) {
  58. // Generate the correct selector for this literal's concrete type.
  59. // Get the method.
  60. const ObjCMethodDecl *BoxingMethod = E->getBoxingMethod();
  61. const Expr *SubExpr = E->getSubExpr();
  62. if (E->isExpressibleAsConstantInitializer()) {
  63. ConstantEmitter ConstEmitter(CGM);
  64. return ConstEmitter.tryEmitAbstract(E, E->getType());
  65. }
  66. assert(BoxingMethod->isClassMethod() && "BoxingMethod must be a class method");
  67. Selector Sel = BoxingMethod->getSelector();
  68. // Generate a reference to the class pointer, which will be the receiver.
  69. // Assumes that the method was introduced in the class that should be
  70. // messaged (avoids pulling it out of the result type).
  71. CGObjCRuntime &Runtime = CGM.getObjCRuntime();
  72. const ObjCInterfaceDecl *ClassDecl = BoxingMethod->getClassInterface();
  73. llvm::Value *Receiver = Runtime.GetClass(*this, ClassDecl);
  74. CallArgList Args;
  75. const ParmVarDecl *ArgDecl = *BoxingMethod->param_begin();
  76. QualType ArgQT = ArgDecl->getType().getUnqualifiedType();
  77. // ObjCBoxedExpr supports boxing of structs and unions
  78. // via [NSValue valueWithBytes:objCType:]
  79. const QualType ValueType(SubExpr->getType().getCanonicalType());
  80. if (ValueType->isObjCBoxableRecordType()) {
  81. // Emit CodeGen for first parameter
  82. // and cast value to correct type
  83. Address Temporary = CreateMemTemp(SubExpr->getType());
  84. EmitAnyExprToMem(SubExpr, Temporary, Qualifiers(), /*isInit*/ true);
  85. Address BitCast = Builder.CreateBitCast(Temporary, ConvertType(ArgQT));
  86. Args.add(RValue::get(BitCast.getPointer()), ArgQT);
  87. // Create char array to store type encoding
  88. std::string Str;
  89. getContext().getObjCEncodingForType(ValueType, Str);
  90. llvm::Constant *GV = CGM.GetAddrOfConstantCString(Str).getPointer();
  91. // Cast type encoding to correct type
  92. const ParmVarDecl *EncodingDecl = BoxingMethod->parameters()[1];
  93. QualType EncodingQT = EncodingDecl->getType().getUnqualifiedType();
  94. llvm::Value *Cast = Builder.CreateBitCast(GV, ConvertType(EncodingQT));
  95. Args.add(RValue::get(Cast), EncodingQT);
  96. } else {
  97. Args.add(EmitAnyExpr(SubExpr), ArgQT);
  98. }
  99. RValue result = Runtime.GenerateMessageSend(
  100. *this, ReturnValueSlot(), BoxingMethod->getReturnType(), Sel, Receiver,
  101. Args, ClassDecl, BoxingMethod);
  102. return Builder.CreateBitCast(result.getScalarVal(),
  103. ConvertType(E->getType()));
  104. }
  105. llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E,
  106. const ObjCMethodDecl *MethodWithObjects) {
  107. ASTContext &Context = CGM.getContext();
  108. const ObjCDictionaryLiteral *DLE = nullptr;
  109. const ObjCArrayLiteral *ALE = dyn_cast<ObjCArrayLiteral>(E);
  110. if (!ALE)
  111. DLE = cast<ObjCDictionaryLiteral>(E);
  112. // Optimize empty collections by referencing constants, when available.
  113. uint64_t NumElements =
  114. ALE ? ALE->getNumElements() : DLE->getNumElements();
  115. if (NumElements == 0 && CGM.getLangOpts().ObjCRuntime.hasEmptyCollections()) {
  116. StringRef ConstantName = ALE ? "__NSArray0__" : "__NSDictionary0__";
  117. QualType IdTy(CGM.getContext().getObjCIdType());
  118. llvm::Constant *Constant =
  119. CGM.CreateRuntimeVariable(ConvertType(IdTy), ConstantName);
  120. LValue LV = MakeNaturalAlignAddrLValue(Constant, IdTy);
  121. llvm::Value *Ptr = EmitLoadOfScalar(LV, E->getBeginLoc());
  122. cast<llvm::LoadInst>(Ptr)->setMetadata(
  123. CGM.getModule().getMDKindID("invariant.load"),
  124. llvm::MDNode::get(getLLVMContext(), None));
  125. return Builder.CreateBitCast(Ptr, ConvertType(E->getType()));
  126. }
  127. // Compute the type of the array we're initializing.
  128. llvm::APInt APNumElements(Context.getTypeSize(Context.getSizeType()),
  129. NumElements);
  130. QualType ElementType = Context.getObjCIdType().withConst();
  131. QualType ElementArrayType
  132. = Context.getConstantArrayType(ElementType, APNumElements, nullptr,
  133. ArrayType::Normal, /*IndexTypeQuals=*/0);
  134. // Allocate the temporary array(s).
  135. Address Objects = CreateMemTemp(ElementArrayType, "objects");
  136. Address Keys = Address::invalid();
  137. if (DLE)
  138. Keys = CreateMemTemp(ElementArrayType, "keys");
  139. // In ARC, we may need to do extra work to keep all the keys and
  140. // values alive until after the call.
  141. SmallVector<llvm::Value *, 16> NeededObjects;
  142. bool TrackNeededObjects =
  143. (getLangOpts().ObjCAutoRefCount &&
  144. CGM.getCodeGenOpts().OptimizationLevel != 0);
  145. // Perform the actual initialialization of the array(s).
  146. for (uint64_t i = 0; i < NumElements; i++) {
  147. if (ALE) {
  148. // Emit the element and store it to the appropriate array slot.
  149. const Expr *Rhs = ALE->getElement(i);
  150. LValue LV = MakeAddrLValue(Builder.CreateConstArrayGEP(Objects, i),
  151. ElementType, AlignmentSource::Decl);
  152. llvm::Value *value = EmitScalarExpr(Rhs);
  153. EmitStoreThroughLValue(RValue::get(value), LV, true);
  154. if (TrackNeededObjects) {
  155. NeededObjects.push_back(value);
  156. }
  157. } else {
  158. // Emit the key and store it to the appropriate array slot.
  159. const Expr *Key = DLE->getKeyValueElement(i).Key;
  160. LValue KeyLV = MakeAddrLValue(Builder.CreateConstArrayGEP(Keys, i),
  161. ElementType, AlignmentSource::Decl);
  162. llvm::Value *keyValue = EmitScalarExpr(Key);
  163. EmitStoreThroughLValue(RValue::get(keyValue), KeyLV, /*isInit=*/true);
  164. // Emit the value and store it to the appropriate array slot.
  165. const Expr *Value = DLE->getKeyValueElement(i).Value;
  166. LValue ValueLV = MakeAddrLValue(Builder.CreateConstArrayGEP(Objects, i),
  167. ElementType, AlignmentSource::Decl);
  168. llvm::Value *valueValue = EmitScalarExpr(Value);
  169. EmitStoreThroughLValue(RValue::get(valueValue), ValueLV, /*isInit=*/true);
  170. if (TrackNeededObjects) {
  171. NeededObjects.push_back(keyValue);
  172. NeededObjects.push_back(valueValue);
  173. }
  174. }
  175. }
  176. // Generate the argument list.
  177. CallArgList Args;
  178. ObjCMethodDecl::param_const_iterator PI = MethodWithObjects->param_begin();
  179. const ParmVarDecl *argDecl = *PI++;
  180. QualType ArgQT = argDecl->getType().getUnqualifiedType();
  181. Args.add(RValue::get(Objects.getPointer()), ArgQT);
  182. if (DLE) {
  183. argDecl = *PI++;
  184. ArgQT = argDecl->getType().getUnqualifiedType();
  185. Args.add(RValue::get(Keys.getPointer()), ArgQT);
  186. }
  187. argDecl = *PI;
  188. ArgQT = argDecl->getType().getUnqualifiedType();
  189. llvm::Value *Count =
  190. llvm::ConstantInt::get(CGM.getTypes().ConvertType(ArgQT), NumElements);
  191. Args.add(RValue::get(Count), ArgQT);
  192. // Generate a reference to the class pointer, which will be the receiver.
  193. Selector Sel = MethodWithObjects->getSelector();
  194. QualType ResultType = E->getType();
  195. const ObjCObjectPointerType *InterfacePointerType
  196. = ResultType->getAsObjCInterfacePointerType();
  197. ObjCInterfaceDecl *Class
  198. = InterfacePointerType->getObjectType()->getInterface();
  199. CGObjCRuntime &Runtime = CGM.getObjCRuntime();
  200. llvm::Value *Receiver = Runtime.GetClass(*this, Class);
  201. // Generate the message send.
  202. RValue result = Runtime.GenerateMessageSend(
  203. *this, ReturnValueSlot(), MethodWithObjects->getReturnType(), Sel,
  204. Receiver, Args, Class, MethodWithObjects);
  205. // The above message send needs these objects, but in ARC they are
  206. // passed in a buffer that is essentially __unsafe_unretained.
  207. // Therefore we must prevent the optimizer from releasing them until
  208. // after the call.
  209. if (TrackNeededObjects) {
  210. EmitARCIntrinsicUse(NeededObjects);
  211. }
  212. return Builder.CreateBitCast(result.getScalarVal(),
  213. ConvertType(E->getType()));
  214. }
  215. llvm::Value *CodeGenFunction::EmitObjCArrayLiteral(const ObjCArrayLiteral *E) {
  216. return EmitObjCCollectionLiteral(E, E->getArrayWithObjectsMethod());
  217. }
  218. llvm::Value *CodeGenFunction::EmitObjCDictionaryLiteral(
  219. const ObjCDictionaryLiteral *E) {
  220. return EmitObjCCollectionLiteral(E, E->getDictWithObjectsMethod());
  221. }
  222. /// Emit a selector.
  223. llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
  224. // Untyped selector.
  225. // Note that this implementation allows for non-constant strings to be passed
  226. // as arguments to @selector(). Currently, the only thing preventing this
  227. // behaviour is the type checking in the front end.
  228. return CGM.getObjCRuntime().GetSelector(*this, E->getSelector());
  229. }
  230. llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
  231. // FIXME: This should pass the Decl not the name.
  232. return CGM.getObjCRuntime().GenerateProtocolRef(*this, E->getProtocol());
  233. }
  234. /// Adjust the type of an Objective-C object that doesn't match up due
  235. /// to type erasure at various points, e.g., related result types or the use
  236. /// of parameterized classes.
  237. static RValue AdjustObjCObjectType(CodeGenFunction &CGF, QualType ExpT,
  238. RValue Result) {
  239. if (!ExpT->isObjCRetainableType())
  240. return Result;
  241. // If the converted types are the same, we're done.
  242. llvm::Type *ExpLLVMTy = CGF.ConvertType(ExpT);
  243. if (ExpLLVMTy == Result.getScalarVal()->getType())
  244. return Result;
  245. // We have applied a substitution. Cast the rvalue appropriately.
  246. return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(),
  247. ExpLLVMTy));
  248. }
  249. /// Decide whether to extend the lifetime of the receiver of a
  250. /// returns-inner-pointer message.
  251. static bool
  252. shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr *message) {
  253. switch (message->getReceiverKind()) {
  254. // For a normal instance message, we should extend unless the
  255. // receiver is loaded from a variable with precise lifetime.
  256. case ObjCMessageExpr::Instance: {
  257. const Expr *receiver = message->getInstanceReceiver();
  258. // Look through OVEs.
  259. if (auto opaque = dyn_cast<OpaqueValueExpr>(receiver)) {
  260. if (opaque->getSourceExpr())
  261. receiver = opaque->getSourceExpr()->IgnoreParens();
  262. }
  263. const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(receiver);
  264. if (!ice || ice->getCastKind() != CK_LValueToRValue) return true;
  265. receiver = ice->getSubExpr()->IgnoreParens();
  266. // Look through OVEs.
  267. if (auto opaque = dyn_cast<OpaqueValueExpr>(receiver)) {
  268. if (opaque->getSourceExpr())
  269. receiver = opaque->getSourceExpr()->IgnoreParens();
  270. }
  271. // Only __strong variables.
  272. if (receiver->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  273. return true;
  274. // All ivars and fields have precise lifetime.
  275. if (isa<MemberExpr>(receiver) || isa<ObjCIvarRefExpr>(receiver))
  276. return false;
  277. // Otherwise, check for variables.
  278. const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(ice->getSubExpr());
  279. if (!declRef) return true;
  280. const VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl());
  281. if (!var) return true;
  282. // All variables have precise lifetime except local variables with
  283. // automatic storage duration that aren't specially marked.
  284. return (var->hasLocalStorage() &&
  285. !var->hasAttr<ObjCPreciseLifetimeAttr>());
  286. }
  287. case ObjCMessageExpr::Class:
  288. case ObjCMessageExpr::SuperClass:
  289. // It's never necessary for class objects.
  290. return false;
  291. case ObjCMessageExpr::SuperInstance:
  292. // We generally assume that 'self' lives throughout a method call.
  293. return false;
  294. }
  295. llvm_unreachable("invalid receiver kind");
  296. }
  297. /// Given an expression of ObjC pointer type, check whether it was
  298. /// immediately loaded from an ARC __weak l-value.
  299. static const Expr *findWeakLValue(const Expr *E) {
  300. assert(E->getType()->isObjCRetainableType());
  301. E = E->IgnoreParens();
  302. if (auto CE = dyn_cast<CastExpr>(E)) {
  303. if (CE->getCastKind() == CK_LValueToRValue) {
  304. if (CE->getSubExpr()->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
  305. return CE->getSubExpr();
  306. }
  307. }
  308. return nullptr;
  309. }
  310. /// The ObjC runtime may provide entrypoints that are likely to be faster
  311. /// than an ordinary message send of the appropriate selector.
  312. ///
  313. /// The entrypoints are guaranteed to be equivalent to just sending the
  314. /// corresponding message. If the entrypoint is implemented naively as just a
  315. /// message send, using it is a trade-off: it sacrifices a few cycles of
  316. /// overhead to save a small amount of code. However, it's possible for
  317. /// runtimes to detect and special-case classes that use "standard"
  318. /// behavior; if that's dynamically a large proportion of all objects, using
  319. /// the entrypoint will also be faster than using a message send.
  320. ///
  321. /// If the runtime does support a required entrypoint, then this method will
  322. /// generate a call and return the resulting value. Otherwise it will return
  323. /// None and the caller can generate a msgSend instead.
  324. static Optional<llvm::Value *>
  325. tryGenerateSpecializedMessageSend(CodeGenFunction &CGF, QualType ResultType,
  326. llvm::Value *Receiver,
  327. const CallArgList& Args, Selector Sel,
  328. const ObjCMethodDecl *method,
  329. bool isClassMessage) {
  330. auto &CGM = CGF.CGM;
  331. if (!CGM.getCodeGenOpts().ObjCConvertMessagesToRuntimeCalls)
  332. return None;
  333. auto &Runtime = CGM.getLangOpts().ObjCRuntime;
  334. switch (Sel.getMethodFamily()) {
  335. case OMF_alloc:
  336. if (isClassMessage &&
  337. Runtime.shouldUseRuntimeFunctionsForAlloc() &&
  338. ResultType->isObjCObjectPointerType()) {
  339. // [Foo alloc] -> objc_alloc(Foo) or
  340. // [self alloc] -> objc_alloc(self)
  341. if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "alloc")
  342. return CGF.EmitObjCAlloc(Receiver, CGF.ConvertType(ResultType));
  343. // [Foo allocWithZone:nil] -> objc_allocWithZone(Foo) or
  344. // [self allocWithZone:nil] -> objc_allocWithZone(self)
  345. if (Sel.isKeywordSelector() && Sel.getNumArgs() == 1 &&
  346. Args.size() == 1 && Args.front().getType()->isPointerType() &&
  347. Sel.getNameForSlot(0) == "allocWithZone") {
  348. const llvm::Value* arg = Args.front().getKnownRValue().getScalarVal();
  349. if (isa<llvm::ConstantPointerNull>(arg))
  350. return CGF.EmitObjCAllocWithZone(Receiver,
  351. CGF.ConvertType(ResultType));
  352. return None;
  353. }
  354. }
  355. break;
  356. case OMF_autorelease:
  357. if (ResultType->isObjCObjectPointerType() &&
  358. CGM.getLangOpts().getGC() == LangOptions::NonGC &&
  359. Runtime.shouldUseARCFunctionsForRetainRelease())
  360. return CGF.EmitObjCAutorelease(Receiver, CGF.ConvertType(ResultType));
  361. break;
  362. case OMF_retain:
  363. if (ResultType->isObjCObjectPointerType() &&
  364. CGM.getLangOpts().getGC() == LangOptions::NonGC &&
  365. Runtime.shouldUseARCFunctionsForRetainRelease())
  366. return CGF.EmitObjCRetainNonBlock(Receiver, CGF.ConvertType(ResultType));
  367. break;
  368. case OMF_release:
  369. if (ResultType->isVoidType() &&
  370. CGM.getLangOpts().getGC() == LangOptions::NonGC &&
  371. Runtime.shouldUseARCFunctionsForRetainRelease()) {
  372. CGF.EmitObjCRelease(Receiver, ARCPreciseLifetime);
  373. return nullptr;
  374. }
  375. break;
  376. default:
  377. break;
  378. }
  379. return None;
  380. }
  381. CodeGen::RValue CGObjCRuntime::GeneratePossiblySpecializedMessageSend(
  382. CodeGenFunction &CGF, ReturnValueSlot Return, QualType ResultType,
  383. Selector Sel, llvm::Value *Receiver, const CallArgList &Args,
  384. const ObjCInterfaceDecl *OID, const ObjCMethodDecl *Method,
  385. bool isClassMessage) {
  386. if (Optional<llvm::Value *> SpecializedResult =
  387. tryGenerateSpecializedMessageSend(CGF, ResultType, Receiver, Args,
  388. Sel, Method, isClassMessage)) {
  389. return RValue::get(SpecializedResult.getValue());
  390. }
  391. return GenerateMessageSend(CGF, Return, ResultType, Sel, Receiver, Args, OID,
  392. Method);
  393. }
  394. static void AppendFirstImpliedRuntimeProtocols(
  395. const ObjCProtocolDecl *PD,
  396. llvm::UniqueVector<const ObjCProtocolDecl *> &PDs) {
  397. if (!PD->isNonRuntimeProtocol()) {
  398. const auto *Can = PD->getCanonicalDecl();
  399. PDs.insert(Can);
  400. return;
  401. }
  402. for (const auto *ParentPD : PD->protocols())
  403. AppendFirstImpliedRuntimeProtocols(ParentPD, PDs);
  404. }
  405. std::vector<const ObjCProtocolDecl *>
  406. CGObjCRuntime::GetRuntimeProtocolList(ObjCProtocolDecl::protocol_iterator begin,
  407. ObjCProtocolDecl::protocol_iterator end) {
  408. std::vector<const ObjCProtocolDecl *> RuntimePds;
  409. llvm::DenseSet<const ObjCProtocolDecl *> NonRuntimePDs;
  410. for (; begin != end; ++begin) {
  411. const auto *It = *begin;
  412. const auto *Can = It->getCanonicalDecl();
  413. if (Can->isNonRuntimeProtocol())
  414. NonRuntimePDs.insert(Can);
  415. else
  416. RuntimePds.push_back(Can);
  417. }
  418. // If there are no non-runtime protocols then we can just stop now.
  419. if (NonRuntimePDs.empty())
  420. return RuntimePds;
  421. // Else we have to search through the non-runtime protocol's inheritancy
  422. // hierarchy DAG stopping whenever a branch either finds a runtime protocol or
  423. // a non-runtime protocol without any parents. These are the "first-implied"
  424. // protocols from a non-runtime protocol.
  425. llvm::UniqueVector<const ObjCProtocolDecl *> FirstImpliedProtos;
  426. for (const auto *PD : NonRuntimePDs)
  427. AppendFirstImpliedRuntimeProtocols(PD, FirstImpliedProtos);
  428. // Walk the Runtime list to get all protocols implied via the inclusion of
  429. // this protocol, e.g. all protocols it inherits from including itself.
  430. llvm::DenseSet<const ObjCProtocolDecl *> AllImpliedProtocols;
  431. for (const auto *PD : RuntimePds) {
  432. const auto *Can = PD->getCanonicalDecl();
  433. AllImpliedProtocols.insert(Can);
  434. Can->getImpliedProtocols(AllImpliedProtocols);
  435. }
  436. // Similar to above, walk the list of first-implied protocols to find the set
  437. // all the protocols implied excluding the listed protocols themselves since
  438. // they are not yet a part of the `RuntimePds` list.
  439. for (const auto *PD : FirstImpliedProtos) {
  440. PD->getImpliedProtocols(AllImpliedProtocols);
  441. }
  442. // From the first-implied list we have to finish building the final protocol
  443. // list. If a protocol in the first-implied list was already implied via some
  444. // inheritance path through some other protocols then it would be redundant to
  445. // add it here and so we skip over it.
  446. for (const auto *PD : FirstImpliedProtos) {
  447. if (!AllImpliedProtocols.contains(PD)) {
  448. RuntimePds.push_back(PD);
  449. }
  450. }
  451. return RuntimePds;
  452. }
  453. /// Instead of '[[MyClass alloc] init]', try to generate
  454. /// 'objc_alloc_init(MyClass)'. This provides a code size improvement on the
  455. /// caller side, as well as the optimized objc_alloc.
  456. static Optional<llvm::Value *>
  457. tryEmitSpecializedAllocInit(CodeGenFunction &CGF, const ObjCMessageExpr *OME) {
  458. auto &Runtime = CGF.getLangOpts().ObjCRuntime;
  459. if (!Runtime.shouldUseRuntimeFunctionForCombinedAllocInit())
  460. return None;
  461. // Match the exact pattern '[[MyClass alloc] init]'.
  462. Selector Sel = OME->getSelector();
  463. if (OME->getReceiverKind() != ObjCMessageExpr::Instance ||
  464. !OME->getType()->isObjCObjectPointerType() || !Sel.isUnarySelector() ||
  465. Sel.getNameForSlot(0) != "init")
  466. return None;
  467. // Okay, this is '[receiver init]', check if 'receiver' is '[cls alloc]'
  468. // with 'cls' a Class.
  469. auto *SubOME =
  470. dyn_cast<ObjCMessageExpr>(OME->getInstanceReceiver()->IgnoreParenCasts());
  471. if (!SubOME)
  472. return None;
  473. Selector SubSel = SubOME->getSelector();
  474. if (!SubOME->getType()->isObjCObjectPointerType() ||
  475. !SubSel.isUnarySelector() || SubSel.getNameForSlot(0) != "alloc")
  476. return None;
  477. llvm::Value *Receiver = nullptr;
  478. switch (SubOME->getReceiverKind()) {
  479. case ObjCMessageExpr::Instance:
  480. if (!SubOME->getInstanceReceiver()->getType()->isObjCClassType())
  481. return None;
  482. Receiver = CGF.EmitScalarExpr(SubOME->getInstanceReceiver());
  483. break;
  484. case ObjCMessageExpr::Class: {
  485. QualType ReceiverType = SubOME->getClassReceiver();
  486. const ObjCObjectType *ObjTy = ReceiverType->castAs<ObjCObjectType>();
  487. const ObjCInterfaceDecl *ID = ObjTy->getInterface();
  488. assert(ID && "null interface should be impossible here");
  489. Receiver = CGF.CGM.getObjCRuntime().GetClass(CGF, ID);
  490. break;
  491. }
  492. case ObjCMessageExpr::SuperInstance:
  493. case ObjCMessageExpr::SuperClass:
  494. return None;
  495. }
  496. return CGF.EmitObjCAllocInit(Receiver, CGF.ConvertType(OME->getType()));
  497. }
  498. RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
  499. ReturnValueSlot Return) {
  500. // Only the lookup mechanism and first two arguments of the method
  501. // implementation vary between runtimes. We can get the receiver and
  502. // arguments in generic code.
  503. bool isDelegateInit = E->isDelegateInitCall();
  504. const ObjCMethodDecl *method = E->getMethodDecl();
  505. // If the method is -retain, and the receiver's being loaded from
  506. // a __weak variable, peephole the entire operation to objc_loadWeakRetained.
  507. if (method && E->getReceiverKind() == ObjCMessageExpr::Instance &&
  508. method->getMethodFamily() == OMF_retain) {
  509. if (auto lvalueExpr = findWeakLValue(E->getInstanceReceiver())) {
  510. LValue lvalue = EmitLValue(lvalueExpr);
  511. llvm::Value *result = EmitARCLoadWeakRetained(lvalue.getAddress(*this));
  512. return AdjustObjCObjectType(*this, E->getType(), RValue::get(result));
  513. }
  514. }
  515. if (Optional<llvm::Value *> Val = tryEmitSpecializedAllocInit(*this, E))
  516. return AdjustObjCObjectType(*this, E->getType(), RValue::get(*Val));
  517. // We don't retain the receiver in delegate init calls, and this is
  518. // safe because the receiver value is always loaded from 'self',
  519. // which we zero out. We don't want to Block_copy block receivers,
  520. // though.
  521. bool retainSelf =
  522. (!isDelegateInit &&
  523. CGM.getLangOpts().ObjCAutoRefCount &&
  524. method &&
  525. method->hasAttr<NSConsumesSelfAttr>());
  526. CGObjCRuntime &Runtime = CGM.getObjCRuntime();
  527. bool isSuperMessage = false;
  528. bool isClassMessage = false;
  529. ObjCInterfaceDecl *OID = nullptr;
  530. // Find the receiver
  531. QualType ReceiverType;
  532. llvm::Value *Receiver = nullptr;
  533. switch (E->getReceiverKind()) {
  534. case ObjCMessageExpr::Instance:
  535. ReceiverType = E->getInstanceReceiver()->getType();
  536. isClassMessage = ReceiverType->isObjCClassType();
  537. if (retainSelf) {
  538. TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
  539. E->getInstanceReceiver());
  540. Receiver = ter.getPointer();
  541. if (ter.getInt()) retainSelf = false;
  542. } else
  543. Receiver = EmitScalarExpr(E->getInstanceReceiver());
  544. break;
  545. case ObjCMessageExpr::Class: {
  546. ReceiverType = E->getClassReceiver();
  547. OID = ReceiverType->castAs<ObjCObjectType>()->getInterface();
  548. assert(OID && "Invalid Objective-C class message send");
  549. Receiver = Runtime.GetClass(*this, OID);
  550. isClassMessage = true;
  551. break;
  552. }
  553. case ObjCMessageExpr::SuperInstance:
  554. ReceiverType = E->getSuperType();
  555. Receiver = LoadObjCSelf();
  556. isSuperMessage = true;
  557. break;
  558. case ObjCMessageExpr::SuperClass:
  559. ReceiverType = E->getSuperType();
  560. Receiver = LoadObjCSelf();
  561. isSuperMessage = true;
  562. isClassMessage = true;
  563. break;
  564. }
  565. if (retainSelf)
  566. Receiver = EmitARCRetainNonBlock(Receiver);
  567. // In ARC, we sometimes want to "extend the lifetime"
  568. // (i.e. retain+autorelease) of receivers of returns-inner-pointer
  569. // messages.
  570. if (getLangOpts().ObjCAutoRefCount && method &&
  571. method->hasAttr<ObjCReturnsInnerPointerAttr>() &&
  572. shouldExtendReceiverForInnerPointerMessage(E))
  573. Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver);
  574. QualType ResultType = method ? method->getReturnType() : E->getType();
  575. CallArgList Args;
  576. EmitCallArgs(Args, method, E->arguments(), /*AC*/AbstractCallee(method));
  577. // For delegate init calls in ARC, do an unsafe store of null into
  578. // self. This represents the call taking direct ownership of that
  579. // value. We have to do this after emitting the other call
  580. // arguments because they might also reference self, but we don't
  581. // have to worry about any of them modifying self because that would
  582. // be an undefined read and write of an object in unordered
  583. // expressions.
  584. if (isDelegateInit) {
  585. assert(getLangOpts().ObjCAutoRefCount &&
  586. "delegate init calls should only be marked in ARC");
  587. // Do an unsafe store of null into self.
  588. Address selfAddr =
  589. GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());
  590. Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
  591. }
  592. RValue result;
  593. if (isSuperMessage) {
  594. // super is only valid in an Objective-C method
  595. const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
  596. bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
  597. result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
  598. E->getSelector(),
  599. OMD->getClassInterface(),
  600. isCategoryImpl,
  601. Receiver,
  602. isClassMessage,
  603. Args,
  604. method);
  605. } else {
  606. // Call runtime methods directly if we can.
  607. result = Runtime.GeneratePossiblySpecializedMessageSend(
  608. *this, Return, ResultType, E->getSelector(), Receiver, Args, OID,
  609. method, isClassMessage);
  610. }
  611. // For delegate init calls in ARC, implicitly store the result of
  612. // the call back into self. This takes ownership of the value.
  613. if (isDelegateInit) {
  614. Address selfAddr =
  615. GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());
  616. llvm::Value *newSelf = result.getScalarVal();
  617. // The delegate return type isn't necessarily a matching type; in
  618. // fact, it's quite likely to be 'id'.
  619. llvm::Type *selfTy = selfAddr.getElementType();
  620. newSelf = Builder.CreateBitCast(newSelf, selfTy);
  621. Builder.CreateStore(newSelf, selfAddr);
  622. }
  623. return AdjustObjCObjectType(*this, E->getType(), result);
  624. }
  625. namespace {
  626. struct FinishARCDealloc final : EHScopeStack::Cleanup {
  627. void Emit(CodeGenFunction &CGF, Flags flags) override {
  628. const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
  629. const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
  630. const ObjCInterfaceDecl *iface = impl->getClassInterface();
  631. if (!iface->getSuperClass()) return;
  632. bool isCategory = isa<ObjCCategoryImplDecl>(impl);
  633. // Call [super dealloc] if we have a superclass.
  634. llvm::Value *self = CGF.LoadObjCSelf();
  635. CallArgList args;
  636. CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
  637. CGF.getContext().VoidTy,
  638. method->getSelector(),
  639. iface,
  640. isCategory,
  641. self,
  642. /*is class msg*/ false,
  643. args,
  644. method);
  645. }
  646. };
  647. }
  648. /// StartObjCMethod - Begin emission of an ObjCMethod. This generates
  649. /// the LLVM function and sets the other context used by
  650. /// CodeGenFunction.
  651. void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
  652. const ObjCContainerDecl *CD) {
  653. SourceLocation StartLoc = OMD->getBeginLoc();
  654. FunctionArgList args;
  655. // Check if we should generate debug info for this method.
  656. if (OMD->hasAttr<NoDebugAttr>())
  657. DebugInfo = nullptr; // disable debug info indefinitely for this function
  658. llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
  659. const CGFunctionInfo &FI = CGM.getTypes().arrangeObjCMethodDeclaration(OMD);
  660. if (OMD->isDirectMethod()) {
  661. Fn->setVisibility(llvm::Function::HiddenVisibility);
  662. CGM.SetLLVMFunctionAttributes(OMD, FI, Fn, /*IsThunk=*/false);
  663. CGM.SetLLVMFunctionAttributesForDefinition(OMD, Fn);
  664. } else {
  665. CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
  666. }
  667. args.push_back(OMD->getSelfDecl());
  668. args.push_back(OMD->getCmdDecl());
  669. args.append(OMD->param_begin(), OMD->param_end());
  670. CurGD = OMD;
  671. CurEHLocation = OMD->getEndLoc();
  672. StartFunction(OMD, OMD->getReturnType(), Fn, FI, args,
  673. OMD->getLocation(), StartLoc);
  674. if (OMD->isDirectMethod()) {
  675. // This function is a direct call, it has to implement a nil check
  676. // on entry.
  677. //
  678. // TODO: possibly have several entry points to elide the check
  679. CGM.getObjCRuntime().GenerateDirectMethodPrologue(*this, Fn, OMD, CD);
  680. }
  681. // In ARC, certain methods get an extra cleanup.
  682. if (CGM.getLangOpts().ObjCAutoRefCount &&
  683. OMD->isInstanceMethod() &&
  684. OMD->getSelector().isUnarySelector()) {
  685. const IdentifierInfo *ident =
  686. OMD->getSelector().getIdentifierInfoForSlot(0);
  687. if (ident->isStr("dealloc"))
  688. EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
  689. }
  690. }
  691. static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
  692. LValue lvalue, QualType type);
  693. /// Generate an Objective-C method. An Objective-C method is a C function with
  694. /// its pointer, name, and types registered in the class structure.
  695. void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
  696. StartObjCMethod(OMD, OMD->getClassInterface());
  697. PGO.assignRegionCounters(GlobalDecl(OMD), CurFn);
  698. assert(isa<CompoundStmt>(OMD->getBody()));
  699. incrementProfileCounter(OMD->getBody());
  700. EmitCompoundStmtWithoutScope(*cast<CompoundStmt>(OMD->getBody()));
  701. FinishFunction(OMD->getBodyRBrace());
  702. }
  703. /// emitStructGetterCall - Call the runtime function to load a property
  704. /// into the return value slot.
  705. static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
  706. bool isAtomic, bool hasStrong) {
  707. ASTContext &Context = CGF.getContext();
  708. Address src =
  709. CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
  710. .getAddress(CGF);
  711. // objc_copyStruct (ReturnValue, &structIvar,
  712. // sizeof (Type of Ivar), isAtomic, false);
  713. CallArgList args;
  714. Address dest = CGF.Builder.CreateBitCast(CGF.ReturnValue, CGF.VoidPtrTy);
  715. args.add(RValue::get(dest.getPointer()), Context.VoidPtrTy);
  716. src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy);
  717. args.add(RValue::get(src.getPointer()), Context.VoidPtrTy);
  718. CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType());
  719. args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType());
  720. args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy);
  721. args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);
  722. llvm::FunctionCallee fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();
  723. CGCallee callee = CGCallee::forDirect(fn);
  724. CGF.EmitCall(CGF.getTypes().arrangeBuiltinFunctionCall(Context.VoidTy, args),
  725. callee, ReturnValueSlot(), args);
  726. }
  727. /// Determine whether the given architecture supports unaligned atomic
  728. /// accesses. They don't have to be fast, just faster than a function
  729. /// call and a mutex.
  730. static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) {
  731. // FIXME: Allow unaligned atomic load/store on x86. (It is not
  732. // currently supported by the backend.)
  733. return false;
  734. }
  735. /// Return the maximum size that permits atomic accesses for the given
  736. /// architecture.
  737. static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM,
  738. llvm::Triple::ArchType arch) {
  739. // ARM has 8-byte atomic accesses, but it's not clear whether we
  740. // want to rely on them here.
  741. // In the default case, just assume that any size up to a pointer is
  742. // fine given adequate alignment.
  743. return CharUnits::fromQuantity(CGM.PointerSizeInBytes);
  744. }
  745. namespace {
  746. class PropertyImplStrategy {
  747. public:
  748. enum StrategyKind {
  749. /// The 'native' strategy is to use the architecture's provided
  750. /// reads and writes.
  751. Native,
  752. /// Use objc_setProperty and objc_getProperty.
  753. GetSetProperty,
  754. /// Use objc_setProperty for the setter, but use expression
  755. /// evaluation for the getter.
  756. SetPropertyAndExpressionGet,
  757. /// Use objc_copyStruct.
  758. CopyStruct,
  759. /// The 'expression' strategy is to emit normal assignment or
  760. /// lvalue-to-rvalue expressions.
  761. Expression
  762. };
  763. StrategyKind getKind() const { return StrategyKind(Kind); }
  764. bool hasStrongMember() const { return HasStrong; }
  765. bool isAtomic() const { return IsAtomic; }
  766. bool isCopy() const { return IsCopy; }
  767. CharUnits getIvarSize() const { return IvarSize; }
  768. CharUnits getIvarAlignment() const { return IvarAlignment; }
  769. PropertyImplStrategy(CodeGenModule &CGM,
  770. const ObjCPropertyImplDecl *propImpl);
  771. private:
  772. unsigned Kind : 8;
  773. unsigned IsAtomic : 1;
  774. unsigned IsCopy : 1;
  775. unsigned HasStrong : 1;
  776. CharUnits IvarSize;
  777. CharUnits IvarAlignment;
  778. };
  779. }
  780. /// Pick an implementation strategy for the given property synthesis.
  781. PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
  782. const ObjCPropertyImplDecl *propImpl) {
  783. const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
  784. ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
  785. IsCopy = (setterKind == ObjCPropertyDecl::Copy);
  786. IsAtomic = prop->isAtomic();
  787. HasStrong = false; // doesn't matter here.
  788. // Evaluate the ivar's size and alignment.
  789. ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
  790. QualType ivarType = ivar->getType();
  791. auto TInfo = CGM.getContext().getTypeInfoInChars(ivarType);
  792. IvarSize = TInfo.Width;
  793. IvarAlignment = TInfo.Align;
  794. // If we have a copy property, we always have to use setProperty.
  795. // If the property is atomic we need to use getProperty, but in
  796. // the nonatomic case we can just use expression.
  797. if (IsCopy) {
  798. Kind = IsAtomic ? GetSetProperty : SetPropertyAndExpressionGet;
  799. return;
  800. }
  801. // Handle retain.
  802. if (setterKind == ObjCPropertyDecl::Retain) {
  803. // In GC-only, there's nothing special that needs to be done.
  804. if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
  805. // fallthrough
  806. // In ARC, if the property is non-atomic, use expression emission,
  807. // which translates to objc_storeStrong. This isn't required, but
  808. // it's slightly nicer.
  809. } else if (CGM.getLangOpts().ObjCAutoRefCount && !IsAtomic) {
  810. // Using standard expression emission for the setter is only
  811. // acceptable if the ivar is __strong, which won't be true if
  812. // the property is annotated with __attribute__((NSObject)).
  813. // TODO: falling all the way back to objc_setProperty here is
  814. // just laziness, though; we could still use objc_storeStrong
  815. // if we hacked it right.
  816. if (ivarType.getObjCLifetime() == Qualifiers::OCL_Strong)
  817. Kind = Expression;
  818. else
  819. Kind = SetPropertyAndExpressionGet;
  820. return;
  821. // Otherwise, we need to at least use setProperty. However, if
  822. // the property isn't atomic, we can use normal expression
  823. // emission for the getter.
  824. } else if (!IsAtomic) {
  825. Kind = SetPropertyAndExpressionGet;
  826. return;
  827. // Otherwise, we have to use both setProperty and getProperty.
  828. } else {
  829. Kind = GetSetProperty;
  830. return;
  831. }
  832. }
  833. // If we're not atomic, just use expression accesses.
  834. if (!IsAtomic) {
  835. Kind = Expression;
  836. return;
  837. }
  838. // Properties on bitfield ivars need to be emitted using expression
  839. // accesses even if they're nominally atomic.
  840. if (ivar->isBitField()) {
  841. Kind = Expression;
  842. return;
  843. }
  844. // GC-qualified or ARC-qualified ivars need to be emitted as
  845. // expressions. This actually works out to being atomic anyway,
  846. // except for ARC __strong, but that should trigger the above code.
  847. if (ivarType.hasNonTrivialObjCLifetime() ||
  848. (CGM.getLangOpts().getGC() &&
  849. CGM.getContext().getObjCGCAttrKind(ivarType))) {
  850. Kind = Expression;
  851. return;
  852. }
  853. // Compute whether the ivar has strong members.
  854. if (CGM.getLangOpts().getGC())
  855. if (const RecordType *recordType = ivarType->getAs<RecordType>())
  856. HasStrong = recordType->getDecl()->hasObjectMember();
  857. // We can never access structs with object members with a native
  858. // access, because we need to use write barriers. This is what
  859. // objc_copyStruct is for.
  860. if (HasStrong) {
  861. Kind = CopyStruct;
  862. return;
  863. }
  864. // Otherwise, this is target-dependent and based on the size and
  865. // alignment of the ivar.
  866. // If the size of the ivar is not a power of two, give up. We don't
  867. // want to get into the business of doing compare-and-swaps.
  868. if (!IvarSize.isPowerOfTwo()) {
  869. Kind = CopyStruct;
  870. return;
  871. }
  872. llvm::Triple::ArchType arch =
  873. CGM.getTarget().getTriple().getArch();
  874. // Most architectures require memory to fit within a single cache
  875. // line, so the alignment has to be at least the size of the access.
  876. // Otherwise we have to grab a lock.
  877. if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
  878. Kind = CopyStruct;
  879. return;
  880. }
  881. // If the ivar's size exceeds the architecture's maximum atomic
  882. // access size, we have to use CopyStruct.
  883. if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
  884. Kind = CopyStruct;
  885. return;
  886. }
  887. // Otherwise, we can use native loads and stores.
  888. Kind = Native;
  889. }
  890. /// Generate an Objective-C property getter function.
  891. ///
  892. /// The given Decl must be an ObjCImplementationDecl. \@synthesize
  893. /// is illegal within a category.
  894. void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
  895. const ObjCPropertyImplDecl *PID) {
  896. llvm::Constant *AtomicHelperFn =
  897. CodeGenFunction(CGM).GenerateObjCAtomicGetterCopyHelperFunction(PID);
  898. ObjCMethodDecl *OMD = PID->getGetterMethodDecl();
  899. assert(OMD && "Invalid call to generate getter (empty method)");
  900. StartObjCMethod(OMD, IMP->getClassInterface());
  901. generateObjCGetterBody(IMP, PID, OMD, AtomicHelperFn);
  902. FinishFunction(OMD->getEndLoc());
  903. }
  904. static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
  905. const Expr *getter = propImpl->getGetterCXXConstructor();
  906. if (!getter) return true;
  907. // Sema only makes only of these when the ivar has a C++ class type,
  908. // so the form is pretty constrained.
  909. // If the property has a reference type, we might just be binding a
  910. // reference, in which case the result will be a gl-value. We should
  911. // treat this as a non-trivial operation.
  912. if (getter->isGLValue())
  913. return false;
  914. // If we selected a trivial copy-constructor, we're okay.
  915. if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
  916. return (construct->getConstructor()->isTrivial());
  917. // The constructor might require cleanups (in which case it's never
  918. // trivial).
  919. assert(isa<ExprWithCleanups>(getter));
  920. return false;
  921. }
  922. /// emitCPPObjectAtomicGetterCall - Call the runtime function to
  923. /// copy the ivar into the resturn slot.
  924. static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF,
  925. llvm::Value *returnAddr,
  926. ObjCIvarDecl *ivar,
  927. llvm::Constant *AtomicHelperFn) {
  928. // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,
  929. // AtomicHelperFn);
  930. CallArgList args;
  931. // The 1st argument is the return Slot.
  932. args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy);
  933. // The 2nd argument is the address of the ivar.
  934. llvm::Value *ivarAddr =
  935. CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
  936. .getPointer(CGF);
  937. ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
  938. args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
  939. // Third argument is the helper function.
  940. args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
  941. llvm::FunctionCallee copyCppAtomicObjectFn =
  942. CGF.CGM.getObjCRuntime().GetCppAtomicObjectGetFunction();
  943. CGCallee callee = CGCallee::forDirect(copyCppAtomicObjectFn);
  944. CGF.EmitCall(
  945. CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
  946. callee, ReturnValueSlot(), args);
  947. }
  948. void
  949. CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
  950. const ObjCPropertyImplDecl *propImpl,
  951. const ObjCMethodDecl *GetterMethodDecl,
  952. llvm::Constant *AtomicHelperFn) {
  953. // If there's a non-trivial 'get' expression, we just have to emit that.
  954. if (!hasTrivialGetExpr(propImpl)) {
  955. if (!AtomicHelperFn) {
  956. auto *ret = ReturnStmt::Create(getContext(), SourceLocation(),
  957. propImpl->getGetterCXXConstructor(),
  958. /* NRVOCandidate=*/nullptr);
  959. EmitReturnStmt(*ret);
  960. }
  961. else {
  962. ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
  963. emitCPPObjectAtomicGetterCall(*this, ReturnValue.getPointer(),
  964. ivar, AtomicHelperFn);
  965. }
  966. return;
  967. }
  968. const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
  969. QualType propType = prop->getType();
  970. ObjCMethodDecl *getterMethod = propImpl->getGetterMethodDecl();
  971. ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
  972. // Pick an implementation strategy.
  973. PropertyImplStrategy strategy(CGM, propImpl);
  974. switch (strategy.getKind()) {
  975. case PropertyImplStrategy::Native: {
  976. // We don't need to do anything for a zero-size struct.
  977. if (strategy.getIvarSize().isZero())
  978. return;
  979. LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
  980. // Currently, all atomic accesses have to be through integer
  981. // types, so there's no point in trying to pick a prettier type.
  982. uint64_t ivarSize = getContext().toBits(strategy.getIvarSize());
  983. llvm::Type *bitcastType = llvm::Type::getIntNTy(getLLVMContext(), ivarSize);
  984. bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
  985. // Perform an atomic load. This does not impose ordering constraints.
  986. Address ivarAddr = LV.getAddress(*this);
  987. ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
  988. llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
  989. load->setAtomic(llvm::AtomicOrdering::Unordered);
  990. // Store that value into the return address. Doing this with a
  991. // bitcast is likely to produce some pretty ugly IR, but it's not
  992. // the *most* terrible thing in the world.
  993. llvm::Type *retTy = ConvertType(getterMethod->getReturnType());
  994. uint64_t retTySize = CGM.getDataLayout().getTypeSizeInBits(retTy);
  995. llvm::Value *ivarVal = load;
  996. if (ivarSize > retTySize) {
  997. llvm::Type *newTy = llvm::Type::getIntNTy(getLLVMContext(), retTySize);
  998. ivarVal = Builder.CreateTrunc(load, newTy);
  999. bitcastType = newTy->getPointerTo();
  1000. }
  1001. Builder.CreateStore(ivarVal,
  1002. Builder.CreateBitCast(ReturnValue, bitcastType));
  1003. // Make sure we don't do an autorelease.
  1004. AutoreleaseResult = false;
  1005. return;
  1006. }
  1007. case PropertyImplStrategy::GetSetProperty: {
  1008. llvm::FunctionCallee getPropertyFn =
  1009. CGM.getObjCRuntime().GetPropertyGetFunction();
  1010. if (!getPropertyFn) {
  1011. CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
  1012. return;
  1013. }
  1014. CGCallee callee = CGCallee::forDirect(getPropertyFn);
  1015. // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
  1016. // FIXME: Can't this be simpler? This might even be worse than the
  1017. // corresponding gcc code.
  1018. llvm::Value *cmd =
  1019. Builder.CreateLoad(GetAddrOfLocalVar(getterMethod->getCmdDecl()), "cmd");
  1020. llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
  1021. llvm::Value *ivarOffset =
  1022. EmitIvarOffset(classImpl->getClassInterface(), ivar);
  1023. CallArgList args;
  1024. args.add(RValue::get(self), getContext().getObjCIdType());
  1025. args.add(RValue::get(cmd), getContext().getObjCSelType());
  1026. args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
  1027. args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
  1028. getContext().BoolTy);
  1029. // FIXME: We shouldn't need to get the function info here, the
  1030. // runtime already should have computed it to build the function.
  1031. llvm::CallBase *CallInstruction;
  1032. RValue RV = EmitCall(getTypes().arrangeBuiltinFunctionCall(
  1033. getContext().getObjCIdType(), args),
  1034. callee, ReturnValueSlot(), args, &CallInstruction);
  1035. if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(CallInstruction))
  1036. call->setTailCall();
  1037. // We need to fix the type here. Ivars with copy & retain are
  1038. // always objects so we don't need to worry about complex or
  1039. // aggregates.
  1040. RV = RValue::get(Builder.CreateBitCast(
  1041. RV.getScalarVal(),
  1042. getTypes().ConvertType(getterMethod->getReturnType())));
  1043. EmitReturnOfRValue(RV, propType);
  1044. // objc_getProperty does an autorelease, so we should suppress ours.
  1045. AutoreleaseResult = false;
  1046. return;
  1047. }
  1048. case PropertyImplStrategy::CopyStruct:
  1049. emitStructGetterCall(*this, ivar, strategy.isAtomic(),
  1050. strategy.hasStrongMember());
  1051. return;
  1052. case PropertyImplStrategy::Expression:
  1053. case PropertyImplStrategy::SetPropertyAndExpressionGet: {
  1054. LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
  1055. QualType ivarType = ivar->getType();
  1056. switch (getEvaluationKind(ivarType)) {
  1057. case TEK_Complex: {
  1058. ComplexPairTy pair = EmitLoadOfComplex(LV, SourceLocation());
  1059. EmitStoreOfComplex(pair, MakeAddrLValue(ReturnValue, ivarType),
  1060. /*init*/ true);
  1061. return;
  1062. }
  1063. case TEK_Aggregate: {
  1064. // The return value slot is guaranteed to not be aliased, but
  1065. // that's not necessarily the same as "on the stack", so
  1066. // we still potentially need objc_memmove_collectable.
  1067. EmitAggregateCopy(/* Dest= */ MakeAddrLValue(ReturnValue, ivarType),
  1068. /* Src= */ LV, ivarType, getOverlapForReturnValue());
  1069. return;
  1070. }
  1071. case TEK_Scalar: {
  1072. llvm::Value *value;
  1073. if (propType->isReferenceType()) {
  1074. value = LV.getAddress(*this).getPointer();
  1075. } else {
  1076. // We want to load and autoreleaseReturnValue ARC __weak ivars.
  1077. if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
  1078. if (getLangOpts().ObjCAutoRefCount) {
  1079. value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
  1080. } else {
  1081. value = EmitARCLoadWeak(LV.getAddress(*this));
  1082. }
  1083. // Otherwise we want to do a simple load, suppressing the
  1084. // final autorelease.
  1085. } else {
  1086. value = EmitLoadOfLValue(LV, SourceLocation()).getScalarVal();
  1087. AutoreleaseResult = false;
  1088. }
  1089. value = Builder.CreateBitCast(
  1090. value, ConvertType(GetterMethodDecl->getReturnType()));
  1091. }
  1092. EmitReturnOfRValue(RValue::get(value), propType);
  1093. return;
  1094. }
  1095. }
  1096. llvm_unreachable("bad evaluation kind");
  1097. }
  1098. }
  1099. llvm_unreachable("bad @property implementation strategy!");
  1100. }
  1101. /// emitStructSetterCall - Call the runtime function to store the value
  1102. /// from the first formal parameter into the given ivar.
  1103. static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
  1104. ObjCIvarDecl *ivar) {
  1105. // objc_copyStruct (&structIvar, &Arg,
  1106. // sizeof (struct something), true, false);
  1107. CallArgList args;
  1108. // The first argument is the address of the ivar.
  1109. llvm::Value *ivarAddr =
  1110. CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
  1111. .getPointer(CGF);
  1112. ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
  1113. args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
  1114. // The second argument is the address of the parameter variable.
  1115. ParmVarDecl *argVar = *OMD->param_begin();
  1116. DeclRefExpr argRef(CGF.getContext(), argVar, false,
  1117. argVar->getType().getNonReferenceType(), VK_LValue,
  1118. SourceLocation());
  1119. llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer(CGF);
  1120. argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
  1121. args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
  1122. // The third argument is the sizeof the type.
  1123. llvm::Value *size =
  1124. CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
  1125. args.add(RValue::get(size), CGF.getContext().getSizeType());
  1126. // The fourth argument is the 'isAtomic' flag.
  1127. args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
  1128. // The fifth argument is the 'hasStrong' flag.
  1129. // FIXME: should this really always be false?
  1130. args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
  1131. llvm::FunctionCallee fn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
  1132. CGCallee callee = CGCallee::forDirect(fn);
  1133. CGF.EmitCall(
  1134. CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
  1135. callee, ReturnValueSlot(), args);
  1136. }
  1137. /// emitCPPObjectAtomicSetterCall - Call the runtime function to store
  1138. /// the value from the first formal parameter into the given ivar, using
  1139. /// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
  1140. static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,
  1141. ObjCMethodDecl *OMD,
  1142. ObjCIvarDecl *ivar,
  1143. llvm::Constant *AtomicHelperFn) {
  1144. // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
  1145. // AtomicHelperFn);
  1146. CallArgList args;
  1147. // The first argument is the address of the ivar.
  1148. llvm::Value *ivarAddr =
  1149. CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
  1150. .getPointer(CGF);
  1151. ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
  1152. args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
  1153. // The second argument is the address of the parameter variable.
  1154. ParmVarDecl *argVar = *OMD->param_begin();
  1155. DeclRefExpr argRef(CGF.getContext(), argVar, false,
  1156. argVar->getType().getNonReferenceType(), VK_LValue,
  1157. SourceLocation());
  1158. llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer(CGF);
  1159. argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
  1160. args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
  1161. // Third argument is the helper function.
  1162. args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
  1163. llvm::FunctionCallee fn =
  1164. CGF.CGM.getObjCRuntime().GetCppAtomicObjectSetFunction();
  1165. CGCallee callee = CGCallee::forDirect(fn);
  1166. CGF.EmitCall(
  1167. CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
  1168. callee, ReturnValueSlot(), args);
  1169. }
  1170. static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
  1171. Expr *setter = PID->getSetterCXXAssignment();
  1172. if (!setter) return true;
  1173. // Sema only makes only of these when the ivar has a C++ class type,
  1174. // so the form is pretty constrained.
  1175. // An operator call is trivial if the function it calls is trivial.
  1176. // This also implies that there's nothing non-trivial going on with
  1177. // the arguments, because operator= can only be trivial if it's a
  1178. // synthesized assignment operator and therefore both parameters are
  1179. // references.
  1180. if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
  1181. if (const FunctionDecl *callee
  1182. = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
  1183. if (callee->isTrivial())
  1184. return true;
  1185. return false;
  1186. }
  1187. assert(isa<ExprWithCleanups>(setter));
  1188. return false;
  1189. }
  1190. static bool UseOptimizedSetter(CodeGenModule &CGM) {
  1191. if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
  1192. return false;
  1193. return CGM.getLangOpts().ObjCRuntime.hasOptimizedSetter();
  1194. }
  1195. void
  1196. CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
  1197. const ObjCPropertyImplDecl *propImpl,
  1198. llvm::Constant *AtomicHelperFn) {
  1199. ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
  1200. ObjCMethodDecl *setterMethod = propImpl->getSetterMethodDecl();
  1201. // Just use the setter expression if Sema gave us one and it's
  1202. // non-trivial.
  1203. if (!hasTrivialSetExpr(propImpl)) {
  1204. if (!AtomicHelperFn)
  1205. // If non-atomic, assignment is called directly.
  1206. EmitStmt(propImpl->getSetterCXXAssignment());
  1207. else
  1208. // If atomic, assignment is called via a locking api.
  1209. emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
  1210. AtomicHelperFn);
  1211. return;
  1212. }
  1213. PropertyImplStrategy strategy(CGM, propImpl);
  1214. switch (strategy.getKind()) {
  1215. case PropertyImplStrategy::Native: {
  1216. // We don't need to do anything for a zero-size struct.
  1217. if (strategy.getIvarSize().isZero())
  1218. return;
  1219. Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
  1220. LValue ivarLValue =
  1221. EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
  1222. Address ivarAddr = ivarLValue.getAddress(*this);
  1223. // Currently, all atomic accesses have to be through integer
  1224. // types, so there's no point in trying to pick a prettier type.
  1225. llvm::Type *bitcastType =
  1226. llvm::Type::getIntNTy(getLLVMContext(),
  1227. getContext().toBits(strategy.getIvarSize()));
  1228. // Cast both arguments to the chosen operation type.
  1229. argAddr = Builder.CreateElementBitCast(argAddr, bitcastType);
  1230. ivarAddr = Builder.CreateElementBitCast(ivarAddr, bitcastType);
  1231. // This bitcast load is likely to cause some nasty IR.
  1232. llvm::Value *load = Builder.CreateLoad(argAddr);
  1233. // Perform an atomic store. There are no memory ordering requirements.
  1234. llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
  1235. store->setAtomic(llvm::AtomicOrdering::Unordered);
  1236. return;
  1237. }
  1238. case PropertyImplStrategy::GetSetProperty:
  1239. case PropertyImplStrategy::SetPropertyAndExpressionGet: {
  1240. llvm::FunctionCallee setOptimizedPropertyFn = nullptr;
  1241. llvm::FunctionCallee setPropertyFn = nullptr;
  1242. if (UseOptimizedSetter(CGM)) {
  1243. // 10.8 and iOS 6.0 code and GC is off
  1244. setOptimizedPropertyFn =
  1245. CGM.getObjCRuntime().GetOptimizedPropertySetFunction(
  1246. strategy.isAtomic(), strategy.isCopy());
  1247. if (!setOptimizedPropertyFn) {
  1248. CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI");
  1249. return;
  1250. }
  1251. }
  1252. else {
  1253. setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction();
  1254. if (!setPropertyFn) {
  1255. CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
  1256. return;
  1257. }
  1258. }
  1259. // Emit objc_setProperty((id) self, _cmd, offset, arg,
  1260. // <is-atomic>, <is-copy>).
  1261. llvm::Value *cmd =
  1262. Builder.CreateLoad(GetAddrOfLocalVar(setterMethod->getCmdDecl()));
  1263. llvm::Value *self =
  1264. Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
  1265. llvm::Value *ivarOffset =
  1266. EmitIvarOffset(classImpl->getClassInterface(), ivar);
  1267. Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
  1268. llvm::Value *arg = Builder.CreateLoad(argAddr, "arg");
  1269. arg = Builder.CreateBitCast(arg, VoidPtrTy);
  1270. CallArgList args;
  1271. args.add(RValue::get(self), getContext().getObjCIdType());
  1272. args.add(RValue::get(cmd), getContext().getObjCSelType());
  1273. if (setOptimizedPropertyFn) {
  1274. args.add(RValue::get(arg), getContext().getObjCIdType());
  1275. args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
  1276. CGCallee callee = CGCallee::forDirect(setOptimizedPropertyFn);
  1277. EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args),
  1278. callee, ReturnValueSlot(), args);
  1279. } else {
  1280. args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
  1281. args.add(RValue::get(arg), getContext().getObjCIdType());
  1282. args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
  1283. getContext().BoolTy);
  1284. args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
  1285. getContext().BoolTy);
  1286. // FIXME: We shouldn't need to get the function info here, the runtime
  1287. // already should have computed it to build the function.
  1288. CGCallee callee = CGCallee::forDirect(setPropertyFn);
  1289. EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args),
  1290. callee, ReturnValueSlot(), args);
  1291. }
  1292. return;
  1293. }
  1294. case PropertyImplStrategy::CopyStruct:
  1295. emitStructSetterCall(*this, setterMethod, ivar);
  1296. return;
  1297. case PropertyImplStrategy::Expression:
  1298. break;
  1299. }
  1300. // Otherwise, fake up some ASTs and emit a normal assignment.
  1301. ValueDecl *selfDecl = setterMethod->getSelfDecl();
  1302. DeclRefExpr self(getContext(), selfDecl, false, selfDecl->getType(),
  1303. VK_LValue, SourceLocation());
  1304. ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack, selfDecl->getType(),
  1305. CK_LValueToRValue, &self, VK_PRValue,
  1306. FPOptionsOverride());
  1307. ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
  1308. SourceLocation(), SourceLocation(),
  1309. &selfLoad, true, true);
  1310. ParmVarDecl *argDecl = *setterMethod->param_begin();
  1311. QualType argType = argDecl->getType().getNonReferenceType();
  1312. DeclRefExpr arg(getContext(), argDecl, false, argType, VK_LValue,
  1313. SourceLocation());
  1314. ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
  1315. argType.getUnqualifiedType(), CK_LValueToRValue,
  1316. &arg, VK_PRValue, FPOptionsOverride());
  1317. // The property type can differ from the ivar type in some situations with
  1318. // Objective-C pointer types, we can always bit cast the RHS in these cases.
  1319. // The following absurdity is just to ensure well-formed IR.
  1320. CastKind argCK = CK_NoOp;
  1321. if (ivarRef.getType()->isObjCObjectPointerType()) {
  1322. if (argLoad.getType()->isObjCObjectPointerType())
  1323. argCK = CK_BitCast;
  1324. else if (argLoad.getType()->isBlockPointerType())
  1325. argCK = CK_BlockPointerToObjCPointerCast;
  1326. else
  1327. argCK = CK_CPointerToObjCPointerCast;
  1328. } else if (ivarRef.getType()->isBlockPointerType()) {
  1329. if (argLoad.getType()->isBlockPointerType())
  1330. argCK = CK_BitCast;
  1331. else
  1332. argCK = CK_AnyPointerToBlockPointerCast;
  1333. } else if (ivarRef.getType()->isPointerType()) {
  1334. argCK = CK_BitCast;
  1335. } else if (argLoad.getType()->isAtomicType() &&
  1336. !ivarRef.getType()->isAtomicType()) {
  1337. argCK = CK_AtomicToNonAtomic;
  1338. } else if (!argLoad.getType()->isAtomicType() &&
  1339. ivarRef.getType()->isAtomicType()) {
  1340. argCK = CK_NonAtomicToAtomic;
  1341. }
  1342. ImplicitCastExpr argCast(ImplicitCastExpr::OnStack, ivarRef.getType(), argCK,
  1343. &argLoad, VK_PRValue, FPOptionsOverride());
  1344. Expr *finalArg = &argLoad;
  1345. if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
  1346. argLoad.getType()))
  1347. finalArg = &argCast;
  1348. BinaryOperator *assign = BinaryOperator::Create(
  1349. getContext(), &ivarRef, finalArg, BO_Assign, ivarRef.getType(),
  1350. VK_PRValue, OK_Ordinary, SourceLocation(), FPOptionsOverride());
  1351. EmitStmt(assign);
  1352. }
  1353. /// Generate an Objective-C property setter function.
  1354. ///
  1355. /// The given Decl must be an ObjCImplementationDecl. \@synthesize
  1356. /// is illegal within a category.
  1357. void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
  1358. const ObjCPropertyImplDecl *PID) {
  1359. llvm::Constant *AtomicHelperFn =
  1360. CodeGenFunction(CGM).GenerateObjCAtomicSetterCopyHelperFunction(PID);
  1361. ObjCMethodDecl *OMD = PID->getSetterMethodDecl();
  1362. assert(OMD && "Invalid call to generate setter (empty method)");
  1363. StartObjCMethod(OMD, IMP->getClassInterface());
  1364. generateObjCSetterBody(IMP, PID, AtomicHelperFn);
  1365. FinishFunction(OMD->getEndLoc());
  1366. }
  1367. namespace {
  1368. struct DestroyIvar final : EHScopeStack::Cleanup {
  1369. private:
  1370. llvm::Value *addr;
  1371. const ObjCIvarDecl *ivar;
  1372. CodeGenFunction::Destroyer *destroyer;
  1373. bool useEHCleanupForArray;
  1374. public:
  1375. DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
  1376. CodeGenFunction::Destroyer *destroyer,
  1377. bool useEHCleanupForArray)
  1378. : addr(addr), ivar(ivar), destroyer(destroyer),
  1379. useEHCleanupForArray(useEHCleanupForArray) {}
  1380. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1381. LValue lvalue
  1382. = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
  1383. CGF.emitDestroy(lvalue.getAddress(CGF), ivar->getType(), destroyer,
  1384. flags.isForNormalCleanup() && useEHCleanupForArray);
  1385. }
  1386. };
  1387. }
  1388. /// Like CodeGenFunction::destroyARCStrong, but do it with a call.
  1389. static void destroyARCStrongWithStore(CodeGenFunction &CGF,
  1390. Address addr,
  1391. QualType type) {
  1392. llvm::Value *null = getNullForVariable(addr);
  1393. CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
  1394. }
  1395. static void emitCXXDestructMethod(CodeGenFunction &CGF,
  1396. ObjCImplementationDecl *impl) {
  1397. CodeGenFunction::RunCleanupsScope scope(CGF);
  1398. llvm::Value *self = CGF.LoadObjCSelf();
  1399. const ObjCInterfaceDecl *iface = impl->getClassInterface();
  1400. for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
  1401. ivar; ivar = ivar->getNextIvar()) {
  1402. QualType type = ivar->getType();
  1403. // Check whether the ivar is a destructible type.
  1404. QualType::DestructionKind dtorKind = type.isDestructedType();
  1405. if (!dtorKind) continue;
  1406. CodeGenFunction::Destroyer *destroyer = nullptr;
  1407. // Use a call to objc_storeStrong to destroy strong ivars, for the
  1408. // general benefit of the tools.
  1409. if (dtorKind == QualType::DK_objc_strong_lifetime) {
  1410. destroyer = destroyARCStrongWithStore;
  1411. // Otherwise use the default for the destruction kind.
  1412. } else {
  1413. destroyer = CGF.getDestroyer(dtorKind);
  1414. }
  1415. CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
  1416. CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
  1417. cleanupKind & EHCleanup);
  1418. }
  1419. assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
  1420. }
  1421. void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
  1422. ObjCMethodDecl *MD,
  1423. bool ctor) {
  1424. MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
  1425. StartObjCMethod(MD, IMP->getClassInterface());
  1426. // Emit .cxx_construct.
  1427. if (ctor) {
  1428. // Suppress the final autorelease in ARC.
  1429. AutoreleaseResult = false;
  1430. for (const auto *IvarInit : IMP->inits()) {
  1431. FieldDecl *Field = IvarInit->getAnyMember();
  1432. ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
  1433. LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
  1434. LoadObjCSelf(), Ivar, 0);
  1435. EmitAggExpr(IvarInit->getInit(),
  1436. AggValueSlot::forLValue(LV, *this, AggValueSlot::IsDestructed,
  1437. AggValueSlot::DoesNotNeedGCBarriers,
  1438. AggValueSlot::IsNotAliased,
  1439. AggValueSlot::DoesNotOverlap));
  1440. }
  1441. // constructor returns 'self'.
  1442. CodeGenTypes &Types = CGM.getTypes();
  1443. QualType IdTy(CGM.getContext().getObjCIdType());
  1444. llvm::Value *SelfAsId =
  1445. Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
  1446. EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
  1447. // Emit .cxx_destruct.
  1448. } else {
  1449. emitCXXDestructMethod(*this, IMP);
  1450. }
  1451. FinishFunction();
  1452. }
  1453. llvm::Value *CodeGenFunction::LoadObjCSelf() {
  1454. VarDecl *Self = cast<ObjCMethodDecl>(CurFuncDecl)->getSelfDecl();
  1455. DeclRefExpr DRE(getContext(), Self,
  1456. /*is enclosing local*/ (CurFuncDecl != CurCodeDecl),
  1457. Self->getType(), VK_LValue, SourceLocation());
  1458. return EmitLoadOfScalar(EmitDeclRefLValue(&DRE), SourceLocation());
  1459. }
  1460. QualType CodeGenFunction::TypeOfSelfObject() {
  1461. const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
  1462. ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
  1463. const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
  1464. getContext().getCanonicalType(selfDecl->getType()));
  1465. return PTy->getPointeeType();
  1466. }
  1467. void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
  1468. llvm::FunctionCallee EnumerationMutationFnPtr =
  1469. CGM.getObjCRuntime().EnumerationMutationFunction();
  1470. if (!EnumerationMutationFnPtr) {
  1471. CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
  1472. return;
  1473. }
  1474. CGCallee EnumerationMutationFn =
  1475. CGCallee::forDirect(EnumerationMutationFnPtr);
  1476. CGDebugInfo *DI = getDebugInfo();
  1477. if (DI)
  1478. DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
  1479. RunCleanupsScope ForScope(*this);
  1480. // The local variable comes into scope immediately.
  1481. AutoVarEmission variable = AutoVarEmission::invalid();
  1482. if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
  1483. variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
  1484. JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
  1485. // Fast enumeration state.
  1486. QualType StateTy = CGM.getObjCFastEnumerationStateType();
  1487. Address StatePtr = CreateMemTemp(StateTy, "state.ptr");
  1488. EmitNullInitialization(StatePtr, StateTy);
  1489. // Number of elements in the items array.
  1490. static const unsigned NumItems = 16;
  1491. // Fetch the countByEnumeratingWithState:objects:count: selector.
  1492. IdentifierInfo *II[] = {
  1493. &CGM.getContext().Idents.get("countByEnumeratingWithState"),
  1494. &CGM.getContext().Idents.get("objects"),
  1495. &CGM.getContext().Idents.get("count")
  1496. };
  1497. Selector FastEnumSel =
  1498. CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
  1499. QualType ItemsTy =
  1500. getContext().getConstantArrayType(getContext().getObjCIdType(),
  1501. llvm::APInt(32, NumItems), nullptr,
  1502. ArrayType::Normal, 0);
  1503. Address ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
  1504. // Emit the collection pointer. In ARC, we do a retain.
  1505. llvm::Value *Collection;
  1506. if (getLangOpts().ObjCAutoRefCount) {
  1507. Collection = EmitARCRetainScalarExpr(S.getCollection());
  1508. // Enter a cleanup to do the release.
  1509. EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
  1510. } else {
  1511. Collection = EmitScalarExpr(S.getCollection());
  1512. }
  1513. // The 'continue' label needs to appear within the cleanup for the
  1514. // collection object.
  1515. JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
  1516. // Send it our message:
  1517. CallArgList Args;
  1518. // The first argument is a temporary of the enumeration-state type.
  1519. Args.add(RValue::get(StatePtr.getPointer()),
  1520. getContext().getPointerType(StateTy));
  1521. // The second argument is a temporary array with space for NumItems
  1522. // pointers. We'll actually be loading elements from the array
  1523. // pointer written into the control state; this buffer is so that
  1524. // collections that *aren't* backed by arrays can still queue up
  1525. // batches of elements.
  1526. Args.add(RValue::get(ItemsPtr.getPointer()),
  1527. getContext().getPointerType(ItemsTy));
  1528. // The third argument is the capacity of that temporary array.
  1529. llvm::Type *NSUIntegerTy = ConvertType(getContext().getNSUIntegerType());
  1530. llvm::Constant *Count = llvm::ConstantInt::get(NSUIntegerTy, NumItems);
  1531. Args.add(RValue::get(Count), getContext().getNSUIntegerType());
  1532. // Start the enumeration.
  1533. RValue CountRV =
  1534. CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
  1535. getContext().getNSUIntegerType(),
  1536. FastEnumSel, Collection, Args);
  1537. // The initial number of objects that were returned in the buffer.
  1538. llvm::Value *initialBufferLimit = CountRV.getScalarVal();
  1539. llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
  1540. llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
  1541. llvm::Value *zero = llvm::Constant::getNullValue(NSUIntegerTy);
  1542. // If the limit pointer was zero to begin with, the collection is
  1543. // empty; skip all this. Set the branch weight assuming this has the same
  1544. // probability of exiting the loop as any other loop exit.
  1545. uint64_t EntryCount = getCurrentProfileCount();
  1546. Builder.CreateCondBr(
  1547. Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"), EmptyBB,
  1548. LoopInitBB,
  1549. createProfileWeights(EntryCount, getProfileCount(S.getBody())));
  1550. // Otherwise, initialize the loop.
  1551. EmitBlock(LoopInitBB);
  1552. // Save the initial mutations value. This is the value at an
  1553. // address that was written into the state object by
  1554. // countByEnumeratingWithState:objects:count:.
  1555. Address StateMutationsPtrPtr =
  1556. Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
  1557. llvm::Value *StateMutationsPtr
  1558. = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
  1559. llvm::Type *UnsignedLongTy = ConvertType(getContext().UnsignedLongTy);
  1560. llvm::Value *initialMutations =
  1561. Builder.CreateAlignedLoad(UnsignedLongTy, StateMutationsPtr,
  1562. getPointerAlign(), "forcoll.initial-mutations");
  1563. // Start looping. This is the point we return to whenever we have a
  1564. // fresh, non-empty batch of objects.
  1565. llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
  1566. EmitBlock(LoopBodyBB);
  1567. // The current index into the buffer.
  1568. llvm::PHINode *index = Builder.CreatePHI(NSUIntegerTy, 3, "forcoll.index");
  1569. index->addIncoming(zero, LoopInitBB);
  1570. // The current buffer size.
  1571. llvm::PHINode *count = Builder.CreatePHI(NSUIntegerTy, 3, "forcoll.count");
  1572. count->addIncoming(initialBufferLimit, LoopInitBB);
  1573. incrementProfileCounter(&S);
  1574. // Check whether the mutations value has changed from where it was
  1575. // at start. StateMutationsPtr should actually be invariant between
  1576. // refreshes.
  1577. StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
  1578. llvm::Value *currentMutations
  1579. = Builder.CreateAlignedLoad(UnsignedLongTy, StateMutationsPtr,
  1580. getPointerAlign(), "statemutations");
  1581. llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
  1582. llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
  1583. Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
  1584. WasNotMutatedBB, WasMutatedBB);
  1585. // If so, call the enumeration-mutation function.
  1586. EmitBlock(WasMutatedBB);
  1587. llvm::Type *ObjCIdType = ConvertType(getContext().getObjCIdType());
  1588. llvm::Value *V =
  1589. Builder.CreateBitCast(Collection, ObjCIdType);
  1590. CallArgList Args2;
  1591. Args2.add(RValue::get(V), getContext().getObjCIdType());
  1592. // FIXME: We shouldn't need to get the function info here, the runtime already
  1593. // should have computed it to build the function.
  1594. EmitCall(
  1595. CGM.getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, Args2),
  1596. EnumerationMutationFn, ReturnValueSlot(), Args2);
  1597. // Otherwise, or if the mutation function returns, just continue.
  1598. EmitBlock(WasNotMutatedBB);
  1599. // Initialize the element variable.
  1600. RunCleanupsScope elementVariableScope(*this);
  1601. bool elementIsVariable;
  1602. LValue elementLValue;
  1603. QualType elementType;
  1604. if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
  1605. // Initialize the variable, in case it's a __block variable or something.
  1606. EmitAutoVarInit(variable);
  1607. const VarDecl *D = cast<VarDecl>(SD->getSingleDecl());
  1608. DeclRefExpr tempDRE(getContext(), const_cast<VarDecl *>(D), false,
  1609. D->getType(), VK_LValue, SourceLocation());
  1610. elementLValue = EmitLValue(&tempDRE);
  1611. elementType = D->getType();
  1612. elementIsVariable = true;
  1613. if (D->isARCPseudoStrong())
  1614. elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
  1615. } else {
  1616. elementLValue = LValue(); // suppress warning
  1617. elementType = cast<Expr>(S.getElement())->getType();
  1618. elementIsVariable = false;
  1619. }
  1620. llvm::Type *convertedElementType = ConvertType(elementType);
  1621. // Fetch the buffer out of the enumeration state.
  1622. // TODO: this pointer should actually be invariant between
  1623. // refreshes, which would help us do certain loop optimizations.
  1624. Address StateItemsPtr =
  1625. Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
  1626. llvm::Value *EnumStateItems =
  1627. Builder.CreateLoad(StateItemsPtr, "stateitems");
  1628. // Fetch the value at the current index from the buffer.
  1629. llvm::Value *CurrentItemPtr = Builder.CreateGEP(
  1630. EnumStateItems->getType()->getPointerElementType(), EnumStateItems, index,
  1631. "currentitem.ptr");
  1632. llvm::Value *CurrentItem =
  1633. Builder.CreateAlignedLoad(ObjCIdType, CurrentItemPtr, getPointerAlign());
  1634. if (SanOpts.has(SanitizerKind::ObjCCast)) {
  1635. // Before using an item from the collection, check that the implicit cast
  1636. // from id to the element type is valid. This is done with instrumentation
  1637. // roughly corresponding to:
  1638. //
  1639. // if (![item isKindOfClass:expectedCls]) { /* emit diagnostic */ }
  1640. const ObjCObjectPointerType *ObjPtrTy =
  1641. elementType->getAsObjCInterfacePointerType();
  1642. const ObjCInterfaceType *InterfaceTy =
  1643. ObjPtrTy ? ObjPtrTy->getInterfaceType() : nullptr;
  1644. if (InterfaceTy) {
  1645. SanitizerScope SanScope(this);
  1646. auto &C = CGM.getContext();
  1647. assert(InterfaceTy->getDecl() && "No decl for ObjC interface type");
  1648. Selector IsKindOfClassSel = GetUnarySelector("isKindOfClass", C);
  1649. CallArgList IsKindOfClassArgs;
  1650. llvm::Value *Cls =
  1651. CGM.getObjCRuntime().GetClass(*this, InterfaceTy->getDecl());
  1652. IsKindOfClassArgs.add(RValue::get(Cls), C.getObjCClassType());
  1653. llvm::Value *IsClass =
  1654. CGM.getObjCRuntime()
  1655. .GenerateMessageSend(*this, ReturnValueSlot(), C.BoolTy,
  1656. IsKindOfClassSel, CurrentItem,
  1657. IsKindOfClassArgs)
  1658. .getScalarVal();
  1659. llvm::Constant *StaticData[] = {
  1660. EmitCheckSourceLocation(S.getBeginLoc()),
  1661. EmitCheckTypeDescriptor(QualType(InterfaceTy, 0))};
  1662. EmitCheck({{IsClass, SanitizerKind::ObjCCast}},
  1663. SanitizerHandler::InvalidObjCCast,
  1664. ArrayRef<llvm::Constant *>(StaticData), CurrentItem);
  1665. }
  1666. }
  1667. // Cast that value to the right type.
  1668. CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
  1669. "currentitem");
  1670. // Make sure we have an l-value. Yes, this gets evaluated every
  1671. // time through the loop.
  1672. if (!elementIsVariable) {
  1673. elementLValue = EmitLValue(cast<Expr>(S.getElement()));
  1674. EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
  1675. } else {
  1676. EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue,
  1677. /*isInit*/ true);
  1678. }
  1679. // If we do have an element variable, this assignment is the end of
  1680. // its initialization.
  1681. if (elementIsVariable)
  1682. EmitAutoVarCleanups(variable);
  1683. // Perform the loop body, setting up break and continue labels.
  1684. BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
  1685. {
  1686. RunCleanupsScope Scope(*this);
  1687. EmitStmt(S.getBody());
  1688. }
  1689. BreakContinueStack.pop_back();
  1690. // Destroy the element variable now.
  1691. elementVariableScope.ForceCleanup();
  1692. // Check whether there are more elements.
  1693. EmitBlock(AfterBody.getBlock());
  1694. llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
  1695. // First we check in the local buffer.
  1696. llvm::Value *indexPlusOne =
  1697. Builder.CreateAdd(index, llvm::ConstantInt::get(NSUIntegerTy, 1));
  1698. // If we haven't overrun the buffer yet, we can continue.
  1699. // Set the branch weights based on the simplifying assumption that this is
  1700. // like a while-loop, i.e., ignoring that the false branch fetches more
  1701. // elements and then returns to the loop.
  1702. Builder.CreateCondBr(
  1703. Builder.CreateICmpULT(indexPlusOne, count), LoopBodyBB, FetchMoreBB,
  1704. createProfileWeights(getProfileCount(S.getBody()), EntryCount));
  1705. index->addIncoming(indexPlusOne, AfterBody.getBlock());
  1706. count->addIncoming(count, AfterBody.getBlock());
  1707. // Otherwise, we have to fetch more elements.
  1708. EmitBlock(FetchMoreBB);
  1709. CountRV =
  1710. CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
  1711. getContext().getNSUIntegerType(),
  1712. FastEnumSel, Collection, Args);
  1713. // If we got a zero count, we're done.
  1714. llvm::Value *refetchCount = CountRV.getScalarVal();
  1715. // (note that the message send might split FetchMoreBB)
  1716. index->addIncoming(zero, Builder.GetInsertBlock());
  1717. count->addIncoming(refetchCount, Builder.GetInsertBlock());
  1718. Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
  1719. EmptyBB, LoopBodyBB);
  1720. // No more elements.
  1721. EmitBlock(EmptyBB);
  1722. if (!elementIsVariable) {
  1723. // If the element was not a declaration, set it to be null.
  1724. llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
  1725. elementLValue = EmitLValue(cast<Expr>(S.getElement()));
  1726. EmitStoreThroughLValue(RValue::get(null), elementLValue);
  1727. }
  1728. if (DI)
  1729. DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
  1730. ForScope.ForceCleanup();
  1731. EmitBlock(LoopEnd.getBlock());
  1732. }
  1733. void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
  1734. CGM.getObjCRuntime().EmitTryStmt(*this, S);
  1735. }
  1736. void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
  1737. CGM.getObjCRuntime().EmitThrowStmt(*this, S);
  1738. }
  1739. void CodeGenFunction::EmitObjCAtSynchronizedStmt(
  1740. const ObjCAtSynchronizedStmt &S) {
  1741. CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
  1742. }
  1743. namespace {
  1744. struct CallObjCRelease final : EHScopeStack::Cleanup {
  1745. CallObjCRelease(llvm::Value *object) : object(object) {}
  1746. llvm::Value *object;
  1747. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1748. // Releases at the end of the full-expression are imprecise.
  1749. CGF.EmitARCRelease(object, ARCImpreciseLifetime);
  1750. }
  1751. };
  1752. }
  1753. /// Produce the code for a CK_ARCConsumeObject. Does a primitive
  1754. /// release at the end of the full-expression.
  1755. llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
  1756. llvm::Value *object) {
  1757. // If we're in a conditional branch, we need to make the cleanup
  1758. // conditional.
  1759. pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
  1760. return object;
  1761. }
  1762. llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
  1763. llvm::Value *value) {
  1764. return EmitARCRetainAutorelease(type, value);
  1765. }
  1766. /// Given a number of pointers, inform the optimizer that they're
  1767. /// being intrinsically used up until this point in the program.
  1768. void CodeGenFunction::EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values) {
  1769. llvm::Function *&fn = CGM.getObjCEntrypoints().clang_arc_use;
  1770. if (!fn)
  1771. fn = CGM.getIntrinsic(llvm::Intrinsic::objc_clang_arc_use);
  1772. // This isn't really a "runtime" function, but as an intrinsic it
  1773. // doesn't really matter as long as we align things up.
  1774. EmitNounwindRuntimeCall(fn, values);
  1775. }
  1776. /// Emit a call to "clang.arc.noop.use", which consumes the result of a call
  1777. /// that has operand bundle "clang.arc.attachedcall".
  1778. void CodeGenFunction::EmitARCNoopIntrinsicUse(ArrayRef<llvm::Value *> values) {
  1779. llvm::Function *&fn = CGM.getObjCEntrypoints().clang_arc_noop_use;
  1780. if (!fn)
  1781. fn = CGM.getIntrinsic(llvm::Intrinsic::objc_clang_arc_noop_use);
  1782. EmitNounwindRuntimeCall(fn, values);
  1783. }
  1784. static void setARCRuntimeFunctionLinkage(CodeGenModule &CGM, llvm::Value *RTF) {
  1785. if (auto *F = dyn_cast<llvm::Function>(RTF)) {
  1786. // If the target runtime doesn't naturally support ARC, emit weak
  1787. // references to the runtime support library. We don't really
  1788. // permit this to fail, but we need a particular relocation style.
  1789. if (!CGM.getLangOpts().ObjCRuntime.hasNativeARC() &&
  1790. !CGM.getTriple().isOSBinFormatCOFF()) {
  1791. F->setLinkage(llvm::Function::ExternalWeakLinkage);
  1792. }
  1793. }
  1794. }
  1795. static void setARCRuntimeFunctionLinkage(CodeGenModule &CGM,
  1796. llvm::FunctionCallee RTF) {
  1797. setARCRuntimeFunctionLinkage(CGM, RTF.getCallee());
  1798. }
  1799. static llvm::Function *getARCIntrinsic(llvm::Intrinsic::ID IntID,
  1800. CodeGenModule &CGM) {
  1801. llvm::Function *fn = CGM.getIntrinsic(IntID);
  1802. setARCRuntimeFunctionLinkage(CGM, fn);
  1803. return fn;
  1804. }
  1805. /// Perform an operation having the signature
  1806. /// i8* (i8*)
  1807. /// where a null input causes a no-op and returns null.
  1808. static llvm::Value *emitARCValueOperation(
  1809. CodeGenFunction &CGF, llvm::Value *value, llvm::Type *returnType,
  1810. llvm::Function *&fn, llvm::Intrinsic::ID IntID,
  1811. llvm::CallInst::TailCallKind tailKind = llvm::CallInst::TCK_None) {
  1812. if (isa<llvm::ConstantPointerNull>(value))
  1813. return value;
  1814. if (!fn)
  1815. fn = getARCIntrinsic(IntID, CGF.CGM);
  1816. // Cast the argument to 'id'.
  1817. llvm::Type *origType = returnType ? returnType : value->getType();
  1818. value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
  1819. // Call the function.
  1820. llvm::CallInst *call = CGF.EmitNounwindRuntimeCall(fn, value);
  1821. call->setTailCallKind(tailKind);
  1822. // Cast the result back to the original type.
  1823. return CGF.Builder.CreateBitCast(call, origType);
  1824. }
  1825. /// Perform an operation having the following signature:
  1826. /// i8* (i8**)
  1827. static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF, Address addr,
  1828. llvm::Function *&fn,
  1829. llvm::Intrinsic::ID IntID) {
  1830. if (!fn)
  1831. fn = getARCIntrinsic(IntID, CGF.CGM);
  1832. // Cast the argument to 'id*'.
  1833. llvm::Type *origType = addr.getElementType();
  1834. addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
  1835. // Call the function.
  1836. llvm::Value *result = CGF.EmitNounwindRuntimeCall(fn, addr.getPointer());
  1837. // Cast the result back to a dereference of the original type.
  1838. if (origType != CGF.Int8PtrTy)
  1839. result = CGF.Builder.CreateBitCast(result, origType);
  1840. return result;
  1841. }
  1842. /// Perform an operation having the following signature:
  1843. /// i8* (i8**, i8*)
  1844. static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF, Address addr,
  1845. llvm::Value *value,
  1846. llvm::Function *&fn,
  1847. llvm::Intrinsic::ID IntID,
  1848. bool ignored) {
  1849. assert(addr.getElementType() == value->getType());
  1850. if (!fn)
  1851. fn = getARCIntrinsic(IntID, CGF.CGM);
  1852. llvm::Type *origType = value->getType();
  1853. llvm::Value *args[] = {
  1854. CGF.Builder.CreateBitCast(addr.getPointer(), CGF.Int8PtrPtrTy),
  1855. CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy)
  1856. };
  1857. llvm::CallInst *result = CGF.EmitNounwindRuntimeCall(fn, args);
  1858. if (ignored) return nullptr;
  1859. return CGF.Builder.CreateBitCast(result, origType);
  1860. }
  1861. /// Perform an operation having the following signature:
  1862. /// void (i8**, i8**)
  1863. static void emitARCCopyOperation(CodeGenFunction &CGF, Address dst, Address src,
  1864. llvm::Function *&fn,
  1865. llvm::Intrinsic::ID IntID) {
  1866. assert(dst.getType() == src.getType());
  1867. if (!fn)
  1868. fn = getARCIntrinsic(IntID, CGF.CGM);
  1869. llvm::Value *args[] = {
  1870. CGF.Builder.CreateBitCast(dst.getPointer(), CGF.Int8PtrPtrTy),
  1871. CGF.Builder.CreateBitCast(src.getPointer(), CGF.Int8PtrPtrTy)
  1872. };
  1873. CGF.EmitNounwindRuntimeCall(fn, args);
  1874. }
  1875. /// Perform an operation having the signature
  1876. /// i8* (i8*)
  1877. /// where a null input causes a no-op and returns null.
  1878. static llvm::Value *emitObjCValueOperation(CodeGenFunction &CGF,
  1879. llvm::Value *value,
  1880. llvm::Type *returnType,
  1881. llvm::FunctionCallee &fn,
  1882. StringRef fnName) {
  1883. if (isa<llvm::ConstantPointerNull>(value))
  1884. return value;
  1885. if (!fn) {
  1886. llvm::FunctionType *fnType =
  1887. llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, false);
  1888. fn = CGF.CGM.CreateRuntimeFunction(fnType, fnName);
  1889. // We have Native ARC, so set nonlazybind attribute for performance
  1890. if (llvm::Function *f = dyn_cast<llvm::Function>(fn.getCallee()))
  1891. if (fnName == "objc_retain")
  1892. f->addFnAttr(llvm::Attribute::NonLazyBind);
  1893. }
  1894. // Cast the argument to 'id'.
  1895. llvm::Type *origType = returnType ? returnType : value->getType();
  1896. value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
  1897. // Call the function.
  1898. llvm::CallBase *Inst = CGF.EmitCallOrInvoke(fn, value);
  1899. // Mark calls to objc_autorelease as tail on the assumption that methods
  1900. // overriding autorelease do not touch anything on the stack.
  1901. if (fnName == "objc_autorelease")
  1902. if (auto *Call = dyn_cast<llvm::CallInst>(Inst))
  1903. Call->setTailCall();
  1904. // Cast the result back to the original type.
  1905. return CGF.Builder.CreateBitCast(Inst, origType);
  1906. }
  1907. /// Produce the code to do a retain. Based on the type, calls one of:
  1908. /// call i8* \@objc_retain(i8* %value)
  1909. /// call i8* \@objc_retainBlock(i8* %value)
  1910. llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
  1911. if (type->isBlockPointerType())
  1912. return EmitARCRetainBlock(value, /*mandatory*/ false);
  1913. else
  1914. return EmitARCRetainNonBlock(value);
  1915. }
  1916. /// Retain the given object, with normal retain semantics.
  1917. /// call i8* \@objc_retain(i8* %value)
  1918. llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
  1919. return emitARCValueOperation(*this, value, nullptr,
  1920. CGM.getObjCEntrypoints().objc_retain,
  1921. llvm::Intrinsic::objc_retain);
  1922. }
  1923. /// Retain the given block, with _Block_copy semantics.
  1924. /// call i8* \@objc_retainBlock(i8* %value)
  1925. ///
  1926. /// \param mandatory - If false, emit the call with metadata
  1927. /// indicating that it's okay for the optimizer to eliminate this call
  1928. /// if it can prove that the block never escapes except down the stack.
  1929. llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
  1930. bool mandatory) {
  1931. llvm::Value *result
  1932. = emitARCValueOperation(*this, value, nullptr,
  1933. CGM.getObjCEntrypoints().objc_retainBlock,
  1934. llvm::Intrinsic::objc_retainBlock);
  1935. // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
  1936. // tell the optimizer that it doesn't need to do this copy if the
  1937. // block doesn't escape, where being passed as an argument doesn't
  1938. // count as escaping.
  1939. if (!mandatory && isa<llvm::Instruction>(result)) {
  1940. llvm::CallInst *call
  1941. = cast<llvm::CallInst>(result->stripPointerCasts());
  1942. assert(call->getCalledOperand() ==
  1943. CGM.getObjCEntrypoints().objc_retainBlock);
  1944. call->setMetadata("clang.arc.copy_on_escape",
  1945. llvm::MDNode::get(Builder.getContext(), None));
  1946. }
  1947. return result;
  1948. }
  1949. static void emitAutoreleasedReturnValueMarker(CodeGenFunction &CGF) {
  1950. // Fetch the void(void) inline asm which marks that we're going to
  1951. // do something with the autoreleased return value.
  1952. llvm::InlineAsm *&marker
  1953. = CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker;
  1954. if (!marker) {
  1955. StringRef assembly
  1956. = CGF.CGM.getTargetCodeGenInfo()
  1957. .getARCRetainAutoreleasedReturnValueMarker();
  1958. // If we have an empty assembly string, there's nothing to do.
  1959. if (assembly.empty()) {
  1960. // Otherwise, at -O0, build an inline asm that we're going to call
  1961. // in a moment.
  1962. } else if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
  1963. llvm::FunctionType *type =
  1964. llvm::FunctionType::get(CGF.VoidTy, /*variadic*/false);
  1965. marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
  1966. // If we're at -O1 and above, we don't want to litter the code
  1967. // with this marker yet, so leave a breadcrumb for the ARC
  1968. // optimizer to pick up.
  1969. } else {
  1970. const char *retainRVMarkerKey = llvm::objcarc::getRVMarkerModuleFlagStr();
  1971. if (!CGF.CGM.getModule().getModuleFlag(retainRVMarkerKey)) {
  1972. auto *str = llvm::MDString::get(CGF.getLLVMContext(), assembly);
  1973. CGF.CGM.getModule().addModuleFlag(llvm::Module::Error,
  1974. retainRVMarkerKey, str);
  1975. }
  1976. }
  1977. }
  1978. // Call the marker asm if we made one, which we do only at -O0.
  1979. if (marker)
  1980. CGF.Builder.CreateCall(marker, None, CGF.getBundlesForFunclet(marker));
  1981. }
  1982. static llvm::Value *emitOptimizedARCReturnCall(llvm::Value *value,
  1983. bool IsRetainRV,
  1984. CodeGenFunction &CGF) {
  1985. emitAutoreleasedReturnValueMarker(CGF);
  1986. // Add operand bundle "clang.arc.attachedcall" to the call instead of emitting
  1987. // retainRV or claimRV calls in the IR. We currently do this only when the
  1988. // optimization level isn't -O0 since global-isel, which is currently run at
  1989. // -O0, doesn't know about the operand bundle.
  1990. ObjCEntrypoints &EPs = CGF.CGM.getObjCEntrypoints();
  1991. llvm::Function *&EP = IsRetainRV
  1992. ? EPs.objc_retainAutoreleasedReturnValue
  1993. : EPs.objc_unsafeClaimAutoreleasedReturnValue;
  1994. llvm::Intrinsic::ID IID =
  1995. IsRetainRV ? llvm::Intrinsic::objc_retainAutoreleasedReturnValue
  1996. : llvm::Intrinsic::objc_unsafeClaimAutoreleasedReturnValue;
  1997. EP = getARCIntrinsic(IID, CGF.CGM);
  1998. llvm::Triple::ArchType Arch = CGF.CGM.getTriple().getArch();
  1999. // FIXME: Do this on all targets and at -O0 too. This can be enabled only if
  2000. // the target backend knows how to handle the operand bundle.
  2001. if (CGF.CGM.getCodeGenOpts().OptimizationLevel > 0 &&
  2002. (Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::x86_64)) {
  2003. llvm::Value *bundleArgs[] = {EP};
  2004. llvm::OperandBundleDef OB("clang.arc.attachedcall", bundleArgs);
  2005. auto *oldCall = cast<llvm::CallBase>(value);
  2006. llvm::CallBase *newCall = llvm::CallBase::addOperandBundle(
  2007. oldCall, llvm::LLVMContext::OB_clang_arc_attachedcall, OB, oldCall);
  2008. newCall->copyMetadata(*oldCall);
  2009. oldCall->replaceAllUsesWith(newCall);
  2010. oldCall->eraseFromParent();
  2011. CGF.EmitARCNoopIntrinsicUse(newCall);
  2012. return newCall;
  2013. }
  2014. bool isNoTail =
  2015. CGF.CGM.getTargetCodeGenInfo().markARCOptimizedReturnCallsAsNoTail();
  2016. llvm::CallInst::TailCallKind tailKind =
  2017. isNoTail ? llvm::CallInst::TCK_NoTail : llvm::CallInst::TCK_None;
  2018. return emitARCValueOperation(CGF, value, nullptr, EP, IID, tailKind);
  2019. }
  2020. /// Retain the given object which is the result of a function call.
  2021. /// call i8* \@objc_retainAutoreleasedReturnValue(i8* %value)
  2022. ///
  2023. /// Yes, this function name is one character away from a different
  2024. /// call with completely different semantics.
  2025. llvm::Value *
  2026. CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
  2027. return emitOptimizedARCReturnCall(value, true, *this);
  2028. }
  2029. /// Claim a possibly-autoreleased return value at +0. This is only
  2030. /// valid to do in contexts which do not rely on the retain to keep
  2031. /// the object valid for all of its uses; for example, when
  2032. /// the value is ignored, or when it is being assigned to an
  2033. /// __unsafe_unretained variable.
  2034. ///
  2035. /// call i8* \@objc_unsafeClaimAutoreleasedReturnValue(i8* %value)
  2036. llvm::Value *
  2037. CodeGenFunction::EmitARCUnsafeClaimAutoreleasedReturnValue(llvm::Value *value) {
  2038. return emitOptimizedARCReturnCall(value, false, *this);
  2039. }
  2040. /// Release the given object.
  2041. /// call void \@objc_release(i8* %value)
  2042. void CodeGenFunction::EmitARCRelease(llvm::Value *value,
  2043. ARCPreciseLifetime_t precise) {
  2044. if (isa<llvm::ConstantPointerNull>(value)) return;
  2045. llvm::Function *&fn = CGM.getObjCEntrypoints().objc_release;
  2046. if (!fn)
  2047. fn = getARCIntrinsic(llvm::Intrinsic::objc_release, CGM);
  2048. // Cast the argument to 'id'.
  2049. value = Builder.CreateBitCast(value, Int8PtrTy);
  2050. // Call objc_release.
  2051. llvm::CallInst *call = EmitNounwindRuntimeCall(fn, value);
  2052. if (precise == ARCImpreciseLifetime) {
  2053. call->setMetadata("clang.imprecise_release",
  2054. llvm::MDNode::get(Builder.getContext(), None));
  2055. }
  2056. }
  2057. /// Destroy a __strong variable.
  2058. ///
  2059. /// At -O0, emit a call to store 'null' into the address;
  2060. /// instrumenting tools prefer this because the address is exposed,
  2061. /// but it's relatively cumbersome to optimize.
  2062. ///
  2063. /// At -O1 and above, just load and call objc_release.
  2064. ///
  2065. /// call void \@objc_storeStrong(i8** %addr, i8* null)
  2066. void CodeGenFunction::EmitARCDestroyStrong(Address addr,
  2067. ARCPreciseLifetime_t precise) {
  2068. if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
  2069. llvm::Value *null = getNullForVariable(addr);
  2070. EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
  2071. return;
  2072. }
  2073. llvm::Value *value = Builder.CreateLoad(addr);
  2074. EmitARCRelease(value, precise);
  2075. }
  2076. /// Store into a strong object. Always calls this:
  2077. /// call void \@objc_storeStrong(i8** %addr, i8* %value)
  2078. llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(Address addr,
  2079. llvm::Value *value,
  2080. bool ignored) {
  2081. assert(addr.getElementType() == value->getType());
  2082. llvm::Function *&fn = CGM.getObjCEntrypoints().objc_storeStrong;
  2083. if (!fn)
  2084. fn = getARCIntrinsic(llvm::Intrinsic::objc_storeStrong, CGM);
  2085. llvm::Value *args[] = {
  2086. Builder.CreateBitCast(addr.getPointer(), Int8PtrPtrTy),
  2087. Builder.CreateBitCast(value, Int8PtrTy)
  2088. };
  2089. EmitNounwindRuntimeCall(fn, args);
  2090. if (ignored) return nullptr;
  2091. return value;
  2092. }
  2093. /// Store into a strong object. Sometimes calls this:
  2094. /// call void \@objc_storeStrong(i8** %addr, i8* %value)
  2095. /// Other times, breaks it down into components.
  2096. llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
  2097. llvm::Value *newValue,
  2098. bool ignored) {
  2099. QualType type = dst.getType();
  2100. bool isBlock = type->isBlockPointerType();
  2101. // Use a store barrier at -O0 unless this is a block type or the
  2102. // lvalue is inadequately aligned.
  2103. if (shouldUseFusedARCCalls() &&
  2104. !isBlock &&
  2105. (dst.getAlignment().isZero() ||
  2106. dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) {
  2107. return EmitARCStoreStrongCall(dst.getAddress(*this), newValue, ignored);
  2108. }
  2109. // Otherwise, split it out.
  2110. // Retain the new value.
  2111. newValue = EmitARCRetain(type, newValue);
  2112. // Read the old value.
  2113. llvm::Value *oldValue = EmitLoadOfScalar(dst, SourceLocation());
  2114. // Store. We do this before the release so that any deallocs won't
  2115. // see the old value.
  2116. EmitStoreOfScalar(newValue, dst);
  2117. // Finally, release the old value.
  2118. EmitARCRelease(oldValue, dst.isARCPreciseLifetime());
  2119. return newValue;
  2120. }
  2121. /// Autorelease the given object.
  2122. /// call i8* \@objc_autorelease(i8* %value)
  2123. llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
  2124. return emitARCValueOperation(*this, value, nullptr,
  2125. CGM.getObjCEntrypoints().objc_autorelease,
  2126. llvm::Intrinsic::objc_autorelease);
  2127. }
  2128. /// Autorelease the given object.
  2129. /// call i8* \@objc_autoreleaseReturnValue(i8* %value)
  2130. llvm::Value *
  2131. CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
  2132. return emitARCValueOperation(*this, value, nullptr,
  2133. CGM.getObjCEntrypoints().objc_autoreleaseReturnValue,
  2134. llvm::Intrinsic::objc_autoreleaseReturnValue,
  2135. llvm::CallInst::TCK_Tail);
  2136. }
  2137. /// Do a fused retain/autorelease of the given object.
  2138. /// call i8* \@objc_retainAutoreleaseReturnValue(i8* %value)
  2139. llvm::Value *
  2140. CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
  2141. return emitARCValueOperation(*this, value, nullptr,
  2142. CGM.getObjCEntrypoints().objc_retainAutoreleaseReturnValue,
  2143. llvm::Intrinsic::objc_retainAutoreleaseReturnValue,
  2144. llvm::CallInst::TCK_Tail);
  2145. }
  2146. /// Do a fused retain/autorelease of the given object.
  2147. /// call i8* \@objc_retainAutorelease(i8* %value)
  2148. /// or
  2149. /// %retain = call i8* \@objc_retainBlock(i8* %value)
  2150. /// call i8* \@objc_autorelease(i8* %retain)
  2151. llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
  2152. llvm::Value *value) {
  2153. if (!type->isBlockPointerType())
  2154. return EmitARCRetainAutoreleaseNonBlock(value);
  2155. if (isa<llvm::ConstantPointerNull>(value)) return value;
  2156. llvm::Type *origType = value->getType();
  2157. value = Builder.CreateBitCast(value, Int8PtrTy);
  2158. value = EmitARCRetainBlock(value, /*mandatory*/ true);
  2159. value = EmitARCAutorelease(value);
  2160. return Builder.CreateBitCast(value, origType);
  2161. }
  2162. /// Do a fused retain/autorelease of the given object.
  2163. /// call i8* \@objc_retainAutorelease(i8* %value)
  2164. llvm::Value *
  2165. CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
  2166. return emitARCValueOperation(*this, value, nullptr,
  2167. CGM.getObjCEntrypoints().objc_retainAutorelease,
  2168. llvm::Intrinsic::objc_retainAutorelease);
  2169. }
  2170. /// i8* \@objc_loadWeak(i8** %addr)
  2171. /// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
  2172. llvm::Value *CodeGenFunction::EmitARCLoadWeak(Address addr) {
  2173. return emitARCLoadOperation(*this, addr,
  2174. CGM.getObjCEntrypoints().objc_loadWeak,
  2175. llvm::Intrinsic::objc_loadWeak);
  2176. }
  2177. /// i8* \@objc_loadWeakRetained(i8** %addr)
  2178. llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(Address addr) {
  2179. return emitARCLoadOperation(*this, addr,
  2180. CGM.getObjCEntrypoints().objc_loadWeakRetained,
  2181. llvm::Intrinsic::objc_loadWeakRetained);
  2182. }
  2183. /// i8* \@objc_storeWeak(i8** %addr, i8* %value)
  2184. /// Returns %value.
  2185. llvm::Value *CodeGenFunction::EmitARCStoreWeak(Address addr,
  2186. llvm::Value *value,
  2187. bool ignored) {
  2188. return emitARCStoreOperation(*this, addr, value,
  2189. CGM.getObjCEntrypoints().objc_storeWeak,
  2190. llvm::Intrinsic::objc_storeWeak, ignored);
  2191. }
  2192. /// i8* \@objc_initWeak(i8** %addr, i8* %value)
  2193. /// Returns %value. %addr is known to not have a current weak entry.
  2194. /// Essentially equivalent to:
  2195. /// *addr = nil; objc_storeWeak(addr, value);
  2196. void CodeGenFunction::EmitARCInitWeak(Address addr, llvm::Value *value) {
  2197. // If we're initializing to null, just write null to memory; no need
  2198. // to get the runtime involved. But don't do this if optimization
  2199. // is enabled, because accounting for this would make the optimizer
  2200. // much more complicated.
  2201. if (isa<llvm::ConstantPointerNull>(value) &&
  2202. CGM.getCodeGenOpts().OptimizationLevel == 0) {
  2203. Builder.CreateStore(value, addr);
  2204. return;
  2205. }
  2206. emitARCStoreOperation(*this, addr, value,
  2207. CGM.getObjCEntrypoints().objc_initWeak,
  2208. llvm::Intrinsic::objc_initWeak, /*ignored*/ true);
  2209. }
  2210. /// void \@objc_destroyWeak(i8** %addr)
  2211. /// Essentially objc_storeWeak(addr, nil).
  2212. void CodeGenFunction::EmitARCDestroyWeak(Address addr) {
  2213. llvm::Function *&fn = CGM.getObjCEntrypoints().objc_destroyWeak;
  2214. if (!fn)
  2215. fn = getARCIntrinsic(llvm::Intrinsic::objc_destroyWeak, CGM);
  2216. // Cast the argument to 'id*'.
  2217. addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
  2218. EmitNounwindRuntimeCall(fn, addr.getPointer());
  2219. }
  2220. /// void \@objc_moveWeak(i8** %dest, i8** %src)
  2221. /// Disregards the current value in %dest. Leaves %src pointing to nothing.
  2222. /// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
  2223. void CodeGenFunction::EmitARCMoveWeak(Address dst, Address src) {
  2224. emitARCCopyOperation(*this, dst, src,
  2225. CGM.getObjCEntrypoints().objc_moveWeak,
  2226. llvm::Intrinsic::objc_moveWeak);
  2227. }
  2228. /// void \@objc_copyWeak(i8** %dest, i8** %src)
  2229. /// Disregards the current value in %dest. Essentially
  2230. /// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
  2231. void CodeGenFunction::EmitARCCopyWeak(Address dst, Address src) {
  2232. emitARCCopyOperation(*this, dst, src,
  2233. CGM.getObjCEntrypoints().objc_copyWeak,
  2234. llvm::Intrinsic::objc_copyWeak);
  2235. }
  2236. void CodeGenFunction::emitARCCopyAssignWeak(QualType Ty, Address DstAddr,
  2237. Address SrcAddr) {
  2238. llvm::Value *Object = EmitARCLoadWeakRetained(SrcAddr);
  2239. Object = EmitObjCConsumeObject(Ty, Object);
  2240. EmitARCStoreWeak(DstAddr, Object, false);
  2241. }
  2242. void CodeGenFunction::emitARCMoveAssignWeak(QualType Ty, Address DstAddr,
  2243. Address SrcAddr) {
  2244. llvm::Value *Object = EmitARCLoadWeakRetained(SrcAddr);
  2245. Object = EmitObjCConsumeObject(Ty, Object);
  2246. EmitARCStoreWeak(DstAddr, Object, false);
  2247. EmitARCDestroyWeak(SrcAddr);
  2248. }
  2249. /// Produce the code to do a objc_autoreleasepool_push.
  2250. /// call i8* \@objc_autoreleasePoolPush(void)
  2251. llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
  2252. llvm::Function *&fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPush;
  2253. if (!fn)
  2254. fn = getARCIntrinsic(llvm::Intrinsic::objc_autoreleasePoolPush, CGM);
  2255. return EmitNounwindRuntimeCall(fn);
  2256. }
  2257. /// Produce the code to do a primitive release.
  2258. /// call void \@objc_autoreleasePoolPop(i8* %ptr)
  2259. void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
  2260. assert(value->getType() == Int8PtrTy);
  2261. if (getInvokeDest()) {
  2262. // Call the runtime method not the intrinsic if we are handling exceptions
  2263. llvm::FunctionCallee &fn =
  2264. CGM.getObjCEntrypoints().objc_autoreleasePoolPopInvoke;
  2265. if (!fn) {
  2266. llvm::FunctionType *fnType =
  2267. llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
  2268. fn = CGM.CreateRuntimeFunction(fnType, "objc_autoreleasePoolPop");
  2269. setARCRuntimeFunctionLinkage(CGM, fn);
  2270. }
  2271. // objc_autoreleasePoolPop can throw.
  2272. EmitRuntimeCallOrInvoke(fn, value);
  2273. } else {
  2274. llvm::FunctionCallee &fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPop;
  2275. if (!fn)
  2276. fn = getARCIntrinsic(llvm::Intrinsic::objc_autoreleasePoolPop, CGM);
  2277. EmitRuntimeCall(fn, value);
  2278. }
  2279. }
  2280. /// Produce the code to do an MRR version objc_autoreleasepool_push.
  2281. /// Which is: [[NSAutoreleasePool alloc] init];
  2282. /// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
  2283. /// init is declared as: - (id) init; in its NSObject super class.
  2284. ///
  2285. llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
  2286. CGObjCRuntime &Runtime = CGM.getObjCRuntime();
  2287. llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(*this);
  2288. // [NSAutoreleasePool alloc]
  2289. IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
  2290. Selector AllocSel = getContext().Selectors.getSelector(0, &II);
  2291. CallArgList Args;
  2292. RValue AllocRV =
  2293. Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
  2294. getContext().getObjCIdType(),
  2295. AllocSel, Receiver, Args);
  2296. // [Receiver init]
  2297. Receiver = AllocRV.getScalarVal();
  2298. II = &CGM.getContext().Idents.get("init");
  2299. Selector InitSel = getContext().Selectors.getSelector(0, &II);
  2300. RValue InitRV =
  2301. Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
  2302. getContext().getObjCIdType(),
  2303. InitSel, Receiver, Args);
  2304. return InitRV.getScalarVal();
  2305. }
  2306. /// Allocate the given objc object.
  2307. /// call i8* \@objc_alloc(i8* %value)
  2308. llvm::Value *CodeGenFunction::EmitObjCAlloc(llvm::Value *value,
  2309. llvm::Type *resultType) {
  2310. return emitObjCValueOperation(*this, value, resultType,
  2311. CGM.getObjCEntrypoints().objc_alloc,
  2312. "objc_alloc");
  2313. }
  2314. /// Allocate the given objc object.
  2315. /// call i8* \@objc_allocWithZone(i8* %value)
  2316. llvm::Value *CodeGenFunction::EmitObjCAllocWithZone(llvm::Value *value,
  2317. llvm::Type *resultType) {
  2318. return emitObjCValueOperation(*this, value, resultType,
  2319. CGM.getObjCEntrypoints().objc_allocWithZone,
  2320. "objc_allocWithZone");
  2321. }
  2322. llvm::Value *CodeGenFunction::EmitObjCAllocInit(llvm::Value *value,
  2323. llvm::Type *resultType) {
  2324. return emitObjCValueOperation(*this, value, resultType,
  2325. CGM.getObjCEntrypoints().objc_alloc_init,
  2326. "objc_alloc_init");
  2327. }
  2328. /// Produce the code to do a primitive release.
  2329. /// [tmp drain];
  2330. void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
  2331. IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
  2332. Selector DrainSel = getContext().Selectors.getSelector(0, &II);
  2333. CallArgList Args;
  2334. CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
  2335. getContext().VoidTy, DrainSel, Arg, Args);
  2336. }
  2337. void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
  2338. Address addr,
  2339. QualType type) {
  2340. CGF.EmitARCDestroyStrong(addr, ARCPreciseLifetime);
  2341. }
  2342. void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
  2343. Address addr,
  2344. QualType type) {
  2345. CGF.EmitARCDestroyStrong(addr, ARCImpreciseLifetime);
  2346. }
  2347. void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
  2348. Address addr,
  2349. QualType type) {
  2350. CGF.EmitARCDestroyWeak(addr);
  2351. }
  2352. void CodeGenFunction::emitARCIntrinsicUse(CodeGenFunction &CGF, Address addr,
  2353. QualType type) {
  2354. llvm::Value *value = CGF.Builder.CreateLoad(addr);
  2355. CGF.EmitARCIntrinsicUse(value);
  2356. }
  2357. /// Autorelease the given object.
  2358. /// call i8* \@objc_autorelease(i8* %value)
  2359. llvm::Value *CodeGenFunction::EmitObjCAutorelease(llvm::Value *value,
  2360. llvm::Type *returnType) {
  2361. return emitObjCValueOperation(
  2362. *this, value, returnType,
  2363. CGM.getObjCEntrypoints().objc_autoreleaseRuntimeFunction,
  2364. "objc_autorelease");
  2365. }
  2366. /// Retain the given object, with normal retain semantics.
  2367. /// call i8* \@objc_retain(i8* %value)
  2368. llvm::Value *CodeGenFunction::EmitObjCRetainNonBlock(llvm::Value *value,
  2369. llvm::Type *returnType) {
  2370. return emitObjCValueOperation(
  2371. *this, value, returnType,
  2372. CGM.getObjCEntrypoints().objc_retainRuntimeFunction, "objc_retain");
  2373. }
  2374. /// Release the given object.
  2375. /// call void \@objc_release(i8* %value)
  2376. void CodeGenFunction::EmitObjCRelease(llvm::Value *value,
  2377. ARCPreciseLifetime_t precise) {
  2378. if (isa<llvm::ConstantPointerNull>(value)) return;
  2379. llvm::FunctionCallee &fn =
  2380. CGM.getObjCEntrypoints().objc_releaseRuntimeFunction;
  2381. if (!fn) {
  2382. llvm::FunctionType *fnType =
  2383. llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
  2384. fn = CGM.CreateRuntimeFunction(fnType, "objc_release");
  2385. setARCRuntimeFunctionLinkage(CGM, fn);
  2386. // We have Native ARC, so set nonlazybind attribute for performance
  2387. if (llvm::Function *f = dyn_cast<llvm::Function>(fn.getCallee()))
  2388. f->addFnAttr(llvm::Attribute::NonLazyBind);
  2389. }
  2390. // Cast the argument to 'id'.
  2391. value = Builder.CreateBitCast(value, Int8PtrTy);
  2392. // Call objc_release.
  2393. llvm::CallBase *call = EmitCallOrInvoke(fn, value);
  2394. if (precise == ARCImpreciseLifetime) {
  2395. call->setMetadata("clang.imprecise_release",
  2396. llvm::MDNode::get(Builder.getContext(), None));
  2397. }
  2398. }
  2399. namespace {
  2400. struct CallObjCAutoreleasePoolObject final : EHScopeStack::Cleanup {
  2401. llvm::Value *Token;
  2402. CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
  2403. void Emit(CodeGenFunction &CGF, Flags flags) override {
  2404. CGF.EmitObjCAutoreleasePoolPop(Token);
  2405. }
  2406. };
  2407. struct CallObjCMRRAutoreleasePoolObject final : EHScopeStack::Cleanup {
  2408. llvm::Value *Token;
  2409. CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
  2410. void Emit(CodeGenFunction &CGF, Flags flags) override {
  2411. CGF.EmitObjCMRRAutoreleasePoolPop(Token);
  2412. }
  2413. };
  2414. }
  2415. void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
  2416. if (CGM.getLangOpts().ObjCAutoRefCount)
  2417. EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
  2418. else
  2419. EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
  2420. }
  2421. static bool shouldRetainObjCLifetime(Qualifiers::ObjCLifetime lifetime) {
  2422. switch (lifetime) {
  2423. case Qualifiers::OCL_None:
  2424. case Qualifiers::OCL_ExplicitNone:
  2425. case Qualifiers::OCL_Strong:
  2426. case Qualifiers::OCL_Autoreleasing:
  2427. return true;
  2428. case Qualifiers::OCL_Weak:
  2429. return false;
  2430. }
  2431. llvm_unreachable("impossible lifetime!");
  2432. }
  2433. static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
  2434. LValue lvalue,
  2435. QualType type) {
  2436. llvm::Value *result;
  2437. bool shouldRetain = shouldRetainObjCLifetime(type.getObjCLifetime());
  2438. if (shouldRetain) {
  2439. result = CGF.EmitLoadOfLValue(lvalue, SourceLocation()).getScalarVal();
  2440. } else {
  2441. assert(type.getObjCLifetime() == Qualifiers::OCL_Weak);
  2442. result = CGF.EmitARCLoadWeakRetained(lvalue.getAddress(CGF));
  2443. }
  2444. return TryEmitResult(result, !shouldRetain);
  2445. }
  2446. static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
  2447. const Expr *e) {
  2448. e = e->IgnoreParens();
  2449. QualType type = e->getType();
  2450. // If we're loading retained from a __strong xvalue, we can avoid
  2451. // an extra retain/release pair by zeroing out the source of this
  2452. // "move" operation.
  2453. if (e->isXValue() &&
  2454. !type.isConstQualified() &&
  2455. type.getObjCLifetime() == Qualifiers::OCL_Strong) {
  2456. // Emit the lvalue.
  2457. LValue lv = CGF.EmitLValue(e);
  2458. // Load the object pointer.
  2459. llvm::Value *result = CGF.EmitLoadOfLValue(lv,
  2460. SourceLocation()).getScalarVal();
  2461. // Set the source pointer to NULL.
  2462. CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress(CGF)), lv);
  2463. return TryEmitResult(result, true);
  2464. }
  2465. // As a very special optimization, in ARC++, if the l-value is the
  2466. // result of a non-volatile assignment, do a simple retain of the
  2467. // result of the call to objc_storeWeak instead of reloading.
  2468. if (CGF.getLangOpts().CPlusPlus &&
  2469. !type.isVolatileQualified() &&
  2470. type.getObjCLifetime() == Qualifiers::OCL_Weak &&
  2471. isa<BinaryOperator>(e) &&
  2472. cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
  2473. return TryEmitResult(CGF.EmitScalarExpr(e), false);
  2474. // Try to emit code for scalar constant instead of emitting LValue and
  2475. // loading it because we are not guaranteed to have an l-value. One of such
  2476. // cases is DeclRefExpr referencing non-odr-used constant-evaluated variable.
  2477. if (const auto *decl_expr = dyn_cast<DeclRefExpr>(e)) {
  2478. auto *DRE = const_cast<DeclRefExpr *>(decl_expr);
  2479. if (CodeGenFunction::ConstantEmission constant = CGF.tryEmitAsConstant(DRE))
  2480. return TryEmitResult(CGF.emitScalarConstant(constant, DRE),
  2481. !shouldRetainObjCLifetime(type.getObjCLifetime()));
  2482. }
  2483. return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
  2484. }
  2485. typedef llvm::function_ref<llvm::Value *(CodeGenFunction &CGF,
  2486. llvm::Value *value)>
  2487. ValueTransform;
  2488. /// Insert code immediately after a call.
  2489. // FIXME: We should find a way to emit the runtime call immediately
  2490. // after the call is emitted to eliminate the need for this function.
  2491. static llvm::Value *emitARCOperationAfterCall(CodeGenFunction &CGF,
  2492. llvm::Value *value,
  2493. ValueTransform doAfterCall,
  2494. ValueTransform doFallback) {
  2495. CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
  2496. auto *callBase = dyn_cast<llvm::CallBase>(value);
  2497. if (callBase && llvm::objcarc::hasAttachedCallOpBundle(callBase)) {
  2498. // Fall back if the call base has operand bundle "clang.arc.attachedcall".
  2499. value = doFallback(CGF, value);
  2500. } else if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
  2501. // Place the retain immediately following the call.
  2502. CGF.Builder.SetInsertPoint(call->getParent(),
  2503. ++llvm::BasicBlock::iterator(call));
  2504. value = doAfterCall(CGF, value);
  2505. } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
  2506. // Place the retain at the beginning of the normal destination block.
  2507. llvm::BasicBlock *BB = invoke->getNormalDest();
  2508. CGF.Builder.SetInsertPoint(BB, BB->begin());
  2509. value = doAfterCall(CGF, value);
  2510. // Bitcasts can arise because of related-result returns. Rewrite
  2511. // the operand.
  2512. } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
  2513. // Change the insert point to avoid emitting the fall-back call after the
  2514. // bitcast.
  2515. CGF.Builder.SetInsertPoint(bitcast->getParent(), bitcast->getIterator());
  2516. llvm::Value *operand = bitcast->getOperand(0);
  2517. operand = emitARCOperationAfterCall(CGF, operand, doAfterCall, doFallback);
  2518. bitcast->setOperand(0, operand);
  2519. value = bitcast;
  2520. } else {
  2521. auto *phi = dyn_cast<llvm::PHINode>(value);
  2522. if (phi && phi->getNumIncomingValues() == 2 &&
  2523. isa<llvm::ConstantPointerNull>(phi->getIncomingValue(1)) &&
  2524. isa<llvm::CallBase>(phi->getIncomingValue(0))) {
  2525. // Handle phi instructions that are generated when it's necessary to check
  2526. // whether the receiver of a message is null.
  2527. llvm::Value *inVal = phi->getIncomingValue(0);
  2528. inVal = emitARCOperationAfterCall(CGF, inVal, doAfterCall, doFallback);
  2529. phi->setIncomingValue(0, inVal);
  2530. value = phi;
  2531. } else {
  2532. // Generic fall-back case.
  2533. // Retain using the non-block variant: we never need to do a copy
  2534. // of a block that's been returned to us.
  2535. value = doFallback(CGF, value);
  2536. }
  2537. }
  2538. CGF.Builder.restoreIP(ip);
  2539. return value;
  2540. }
  2541. /// Given that the given expression is some sort of call (which does
  2542. /// not return retained), emit a retain following it.
  2543. static llvm::Value *emitARCRetainCallResult(CodeGenFunction &CGF,
  2544. const Expr *e) {
  2545. llvm::Value *value = CGF.EmitScalarExpr(e);
  2546. return emitARCOperationAfterCall(CGF, value,
  2547. [](CodeGenFunction &CGF, llvm::Value *value) {
  2548. return CGF.EmitARCRetainAutoreleasedReturnValue(value);
  2549. },
  2550. [](CodeGenFunction &CGF, llvm::Value *value) {
  2551. return CGF.EmitARCRetainNonBlock(value);
  2552. });
  2553. }
  2554. /// Given that the given expression is some sort of call (which does
  2555. /// not return retained), perform an unsafeClaim following it.
  2556. static llvm::Value *emitARCUnsafeClaimCallResult(CodeGenFunction &CGF,
  2557. const Expr *e) {
  2558. llvm::Value *value = CGF.EmitScalarExpr(e);
  2559. return emitARCOperationAfterCall(CGF, value,
  2560. [](CodeGenFunction &CGF, llvm::Value *value) {
  2561. return CGF.EmitARCUnsafeClaimAutoreleasedReturnValue(value);
  2562. },
  2563. [](CodeGenFunction &CGF, llvm::Value *value) {
  2564. return value;
  2565. });
  2566. }
  2567. llvm::Value *CodeGenFunction::EmitARCReclaimReturnedObject(const Expr *E,
  2568. bool allowUnsafeClaim) {
  2569. if (allowUnsafeClaim &&
  2570. CGM.getLangOpts().ObjCRuntime.hasARCUnsafeClaimAutoreleasedReturnValue()) {
  2571. return emitARCUnsafeClaimCallResult(*this, E);
  2572. } else {
  2573. llvm::Value *value = emitARCRetainCallResult(*this, E);
  2574. return EmitObjCConsumeObject(E->getType(), value);
  2575. }
  2576. }
  2577. /// Determine whether it might be important to emit a separate
  2578. /// objc_retain_block on the result of the given expression, or
  2579. /// whether it's okay to just emit it in a +1 context.
  2580. static bool shouldEmitSeparateBlockRetain(const Expr *e) {
  2581. assert(e->getType()->isBlockPointerType());
  2582. e = e->IgnoreParens();
  2583. // For future goodness, emit block expressions directly in +1
  2584. // contexts if we can.
  2585. if (isa<BlockExpr>(e))
  2586. return false;
  2587. if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
  2588. switch (cast->getCastKind()) {
  2589. // Emitting these operations in +1 contexts is goodness.
  2590. case CK_LValueToRValue:
  2591. case CK_ARCReclaimReturnedObject:
  2592. case CK_ARCConsumeObject:
  2593. case CK_ARCProduceObject:
  2594. return false;
  2595. // These operations preserve a block type.
  2596. case CK_NoOp:
  2597. case CK_BitCast:
  2598. return shouldEmitSeparateBlockRetain(cast->getSubExpr());
  2599. // These operations are known to be bad (or haven't been considered).
  2600. case CK_AnyPointerToBlockPointerCast:
  2601. default:
  2602. return true;
  2603. }
  2604. }
  2605. return true;
  2606. }
  2607. namespace {
  2608. /// A CRTP base class for emitting expressions of retainable object
  2609. /// pointer type in ARC.
  2610. template <typename Impl, typename Result> class ARCExprEmitter {
  2611. protected:
  2612. CodeGenFunction &CGF;
  2613. Impl &asImpl() { return *static_cast<Impl*>(this); }
  2614. ARCExprEmitter(CodeGenFunction &CGF) : CGF(CGF) {}
  2615. public:
  2616. Result visit(const Expr *e);
  2617. Result visitCastExpr(const CastExpr *e);
  2618. Result visitPseudoObjectExpr(const PseudoObjectExpr *e);
  2619. Result visitBlockExpr(const BlockExpr *e);
  2620. Result visitBinaryOperator(const BinaryOperator *e);
  2621. Result visitBinAssign(const BinaryOperator *e);
  2622. Result visitBinAssignUnsafeUnretained(const BinaryOperator *e);
  2623. Result visitBinAssignAutoreleasing(const BinaryOperator *e);
  2624. Result visitBinAssignWeak(const BinaryOperator *e);
  2625. Result visitBinAssignStrong(const BinaryOperator *e);
  2626. // Minimal implementation:
  2627. // Result visitLValueToRValue(const Expr *e)
  2628. // Result visitConsumeObject(const Expr *e)
  2629. // Result visitExtendBlockObject(const Expr *e)
  2630. // Result visitReclaimReturnedObject(const Expr *e)
  2631. // Result visitCall(const Expr *e)
  2632. // Result visitExpr(const Expr *e)
  2633. //
  2634. // Result emitBitCast(Result result, llvm::Type *resultType)
  2635. // llvm::Value *getValueOfResult(Result result)
  2636. };
  2637. }
  2638. /// Try to emit a PseudoObjectExpr under special ARC rules.
  2639. ///
  2640. /// This massively duplicates emitPseudoObjectRValue.
  2641. template <typename Impl, typename Result>
  2642. Result
  2643. ARCExprEmitter<Impl,Result>::visitPseudoObjectExpr(const PseudoObjectExpr *E) {
  2644. SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
  2645. // Find the result expression.
  2646. const Expr *resultExpr = E->getResultExpr();
  2647. assert(resultExpr);
  2648. Result result;
  2649. for (PseudoObjectExpr::const_semantics_iterator
  2650. i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
  2651. const Expr *semantic = *i;
  2652. // If this semantic expression is an opaque value, bind it
  2653. // to the result of its source expression.
  2654. if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
  2655. typedef CodeGenFunction::OpaqueValueMappingData OVMA;
  2656. OVMA opaqueData;
  2657. // If this semantic is the result of the pseudo-object
  2658. // expression, try to evaluate the source as +1.
  2659. if (ov == resultExpr) {
  2660. assert(!OVMA::shouldBindAsLValue(ov));
  2661. result = asImpl().visit(ov->getSourceExpr());
  2662. opaqueData = OVMA::bind(CGF, ov,
  2663. RValue::get(asImpl().getValueOfResult(result)));
  2664. // Otherwise, just bind it.
  2665. } else {
  2666. opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
  2667. }
  2668. opaques.push_back(opaqueData);
  2669. // Otherwise, if the expression is the result, evaluate it
  2670. // and remember the result.
  2671. } else if (semantic == resultExpr) {
  2672. result = asImpl().visit(semantic);
  2673. // Otherwise, evaluate the expression in an ignored context.
  2674. } else {
  2675. CGF.EmitIgnoredExpr(semantic);
  2676. }
  2677. }
  2678. // Unbind all the opaques now.
  2679. for (unsigned i = 0, e = opaques.size(); i != e; ++i)
  2680. opaques[i].unbind(CGF);
  2681. return result;
  2682. }
  2683. template <typename Impl, typename Result>
  2684. Result ARCExprEmitter<Impl, Result>::visitBlockExpr(const BlockExpr *e) {
  2685. // The default implementation just forwards the expression to visitExpr.
  2686. return asImpl().visitExpr(e);
  2687. }
  2688. template <typename Impl, typename Result>
  2689. Result ARCExprEmitter<Impl,Result>::visitCastExpr(const CastExpr *e) {
  2690. switch (e->getCastKind()) {
  2691. // No-op casts don't change the type, so we just ignore them.
  2692. case CK_NoOp:
  2693. return asImpl().visit(e->getSubExpr());
  2694. // These casts can change the type.
  2695. case CK_CPointerToObjCPointerCast:
  2696. case CK_BlockPointerToObjCPointerCast:
  2697. case CK_AnyPointerToBlockPointerCast:
  2698. case CK_BitCast: {
  2699. llvm::Type *resultType = CGF.ConvertType(e->getType());
  2700. assert(e->getSubExpr()->getType()->hasPointerRepresentation());
  2701. Result result = asImpl().visit(e->getSubExpr());
  2702. return asImpl().emitBitCast(result, resultType);
  2703. }
  2704. // Handle some casts specially.
  2705. case CK_LValueToRValue:
  2706. return asImpl().visitLValueToRValue(e->getSubExpr());
  2707. case CK_ARCConsumeObject:
  2708. return asImpl().visitConsumeObject(e->getSubExpr());
  2709. case CK_ARCExtendBlockObject:
  2710. return asImpl().visitExtendBlockObject(e->getSubExpr());
  2711. case CK_ARCReclaimReturnedObject:
  2712. return asImpl().visitReclaimReturnedObject(e->getSubExpr());
  2713. // Otherwise, use the default logic.
  2714. default:
  2715. return asImpl().visitExpr(e);
  2716. }
  2717. }
  2718. template <typename Impl, typename Result>
  2719. Result
  2720. ARCExprEmitter<Impl,Result>::visitBinaryOperator(const BinaryOperator *e) {
  2721. switch (e->getOpcode()) {
  2722. case BO_Comma:
  2723. CGF.EmitIgnoredExpr(e->getLHS());
  2724. CGF.EnsureInsertPoint();
  2725. return asImpl().visit(e->getRHS());
  2726. case BO_Assign:
  2727. return asImpl().visitBinAssign(e);
  2728. default:
  2729. return asImpl().visitExpr(e);
  2730. }
  2731. }
  2732. template <typename Impl, typename Result>
  2733. Result ARCExprEmitter<Impl,Result>::visitBinAssign(const BinaryOperator *e) {
  2734. switch (e->getLHS()->getType().getObjCLifetime()) {
  2735. case Qualifiers::OCL_ExplicitNone:
  2736. return asImpl().visitBinAssignUnsafeUnretained(e);
  2737. case Qualifiers::OCL_Weak:
  2738. return asImpl().visitBinAssignWeak(e);
  2739. case Qualifiers::OCL_Autoreleasing:
  2740. return asImpl().visitBinAssignAutoreleasing(e);
  2741. case Qualifiers::OCL_Strong:
  2742. return asImpl().visitBinAssignStrong(e);
  2743. case Qualifiers::OCL_None:
  2744. return asImpl().visitExpr(e);
  2745. }
  2746. llvm_unreachable("bad ObjC ownership qualifier");
  2747. }
  2748. /// The default rule for __unsafe_unretained emits the RHS recursively,
  2749. /// stores into the unsafe variable, and propagates the result outward.
  2750. template <typename Impl, typename Result>
  2751. Result ARCExprEmitter<Impl,Result>::
  2752. visitBinAssignUnsafeUnretained(const BinaryOperator *e) {
  2753. // Recursively emit the RHS.
  2754. // For __block safety, do this before emitting the LHS.
  2755. Result result = asImpl().visit(e->getRHS());
  2756. // Perform the store.
  2757. LValue lvalue =
  2758. CGF.EmitCheckedLValue(e->getLHS(), CodeGenFunction::TCK_Store);
  2759. CGF.EmitStoreThroughLValue(RValue::get(asImpl().getValueOfResult(result)),
  2760. lvalue);
  2761. return result;
  2762. }
  2763. template <typename Impl, typename Result>
  2764. Result
  2765. ARCExprEmitter<Impl,Result>::visitBinAssignAutoreleasing(const BinaryOperator *e) {
  2766. return asImpl().visitExpr(e);
  2767. }
  2768. template <typename Impl, typename Result>
  2769. Result
  2770. ARCExprEmitter<Impl,Result>::visitBinAssignWeak(const BinaryOperator *e) {
  2771. return asImpl().visitExpr(e);
  2772. }
  2773. template <typename Impl, typename Result>
  2774. Result
  2775. ARCExprEmitter<Impl,Result>::visitBinAssignStrong(const BinaryOperator *e) {
  2776. return asImpl().visitExpr(e);
  2777. }
  2778. /// The general expression-emission logic.
  2779. template <typename Impl, typename Result>
  2780. Result ARCExprEmitter<Impl,Result>::visit(const Expr *e) {
  2781. // We should *never* see a nested full-expression here, because if
  2782. // we fail to emit at +1, our caller must not retain after we close
  2783. // out the full-expression. This isn't as important in the unsafe
  2784. // emitter.
  2785. assert(!isa<ExprWithCleanups>(e));
  2786. // Look through parens, __extension__, generic selection, etc.
  2787. e = e->IgnoreParens();
  2788. // Handle certain kinds of casts.
  2789. if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
  2790. return asImpl().visitCastExpr(ce);
  2791. // Handle the comma operator.
  2792. } else if (auto op = dyn_cast<BinaryOperator>(e)) {
  2793. return asImpl().visitBinaryOperator(op);
  2794. // TODO: handle conditional operators here
  2795. // For calls and message sends, use the retained-call logic.
  2796. // Delegate inits are a special case in that they're the only
  2797. // returns-retained expression that *isn't* surrounded by
  2798. // a consume.
  2799. } else if (isa<CallExpr>(e) ||
  2800. (isa<ObjCMessageExpr>(e) &&
  2801. !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
  2802. return asImpl().visitCall(e);
  2803. // Look through pseudo-object expressions.
  2804. } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
  2805. return asImpl().visitPseudoObjectExpr(pseudo);
  2806. } else if (auto *be = dyn_cast<BlockExpr>(e))
  2807. return asImpl().visitBlockExpr(be);
  2808. return asImpl().visitExpr(e);
  2809. }
  2810. namespace {
  2811. /// An emitter for +1 results.
  2812. struct ARCRetainExprEmitter :
  2813. public ARCExprEmitter<ARCRetainExprEmitter, TryEmitResult> {
  2814. ARCRetainExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}
  2815. llvm::Value *getValueOfResult(TryEmitResult result) {
  2816. return result.getPointer();
  2817. }
  2818. TryEmitResult emitBitCast(TryEmitResult result, llvm::Type *resultType) {
  2819. llvm::Value *value = result.getPointer();
  2820. value = CGF.Builder.CreateBitCast(value, resultType);
  2821. result.setPointer(value);
  2822. return result;
  2823. }
  2824. TryEmitResult visitLValueToRValue(const Expr *e) {
  2825. return tryEmitARCRetainLoadOfScalar(CGF, e);
  2826. }
  2827. /// For consumptions, just emit the subexpression and thus elide
  2828. /// the retain/release pair.
  2829. TryEmitResult visitConsumeObject(const Expr *e) {
  2830. llvm::Value *result = CGF.EmitScalarExpr(e);
  2831. return TryEmitResult(result, true);
  2832. }
  2833. TryEmitResult visitBlockExpr(const BlockExpr *e) {
  2834. TryEmitResult result = visitExpr(e);
  2835. // Avoid the block-retain if this is a block literal that doesn't need to be
  2836. // copied to the heap.
  2837. if (CGF.CGM.getCodeGenOpts().ObjCAvoidHeapifyLocalBlocks &&
  2838. e->getBlockDecl()->canAvoidCopyToHeap())
  2839. result.setInt(true);
  2840. return result;
  2841. }
  2842. /// Block extends are net +0. Naively, we could just recurse on
  2843. /// the subexpression, but actually we need to ensure that the
  2844. /// value is copied as a block, so there's a little filter here.
  2845. TryEmitResult visitExtendBlockObject(const Expr *e) {
  2846. llvm::Value *result; // will be a +0 value
  2847. // If we can't safely assume the sub-expression will produce a
  2848. // block-copied value, emit the sub-expression at +0.
  2849. if (shouldEmitSeparateBlockRetain(e)) {
  2850. result = CGF.EmitScalarExpr(e);
  2851. // Otherwise, try to emit the sub-expression at +1 recursively.
  2852. } else {
  2853. TryEmitResult subresult = asImpl().visit(e);
  2854. // If that produced a retained value, just use that.
  2855. if (subresult.getInt()) {
  2856. return subresult;
  2857. }
  2858. // Otherwise it's +0.
  2859. result = subresult.getPointer();
  2860. }
  2861. // Retain the object as a block.
  2862. result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
  2863. return TryEmitResult(result, true);
  2864. }
  2865. /// For reclaims, emit the subexpression as a retained call and
  2866. /// skip the consumption.
  2867. TryEmitResult visitReclaimReturnedObject(const Expr *e) {
  2868. llvm::Value *result = emitARCRetainCallResult(CGF, e);
  2869. return TryEmitResult(result, true);
  2870. }
  2871. /// When we have an undecorated call, retroactively do a claim.
  2872. TryEmitResult visitCall(const Expr *e) {
  2873. llvm::Value *result = emitARCRetainCallResult(CGF, e);
  2874. return TryEmitResult(result, true);
  2875. }
  2876. // TODO: maybe special-case visitBinAssignWeak?
  2877. TryEmitResult visitExpr(const Expr *e) {
  2878. // We didn't find an obvious production, so emit what we've got and
  2879. // tell the caller that we didn't manage to retain.
  2880. llvm::Value *result = CGF.EmitScalarExpr(e);
  2881. return TryEmitResult(result, false);
  2882. }
  2883. };
  2884. }
  2885. static TryEmitResult
  2886. tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
  2887. return ARCRetainExprEmitter(CGF).visit(e);
  2888. }
  2889. static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
  2890. LValue lvalue,
  2891. QualType type) {
  2892. TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
  2893. llvm::Value *value = result.getPointer();
  2894. if (!result.getInt())
  2895. value = CGF.EmitARCRetain(type, value);
  2896. return value;
  2897. }
  2898. /// EmitARCRetainScalarExpr - Semantically equivalent to
  2899. /// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
  2900. /// best-effort attempt to peephole expressions that naturally produce
  2901. /// retained objects.
  2902. llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
  2903. // The retain needs to happen within the full-expression.
  2904. if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
  2905. RunCleanupsScope scope(*this);
  2906. return EmitARCRetainScalarExpr(cleanups->getSubExpr());
  2907. }
  2908. TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
  2909. llvm::Value *value = result.getPointer();
  2910. if (!result.getInt())
  2911. value = EmitARCRetain(e->getType(), value);
  2912. return value;
  2913. }
  2914. llvm::Value *
  2915. CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
  2916. // The retain needs to happen within the full-expression.
  2917. if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
  2918. RunCleanupsScope scope(*this);
  2919. return EmitARCRetainAutoreleaseScalarExpr(cleanups->getSubExpr());
  2920. }
  2921. TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
  2922. llvm::Value *value = result.getPointer();
  2923. if (result.getInt())
  2924. value = EmitARCAutorelease(value);
  2925. else
  2926. value = EmitARCRetainAutorelease(e->getType(), value);
  2927. return value;
  2928. }
  2929. llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {
  2930. llvm::Value *result;
  2931. bool doRetain;
  2932. if (shouldEmitSeparateBlockRetain(e)) {
  2933. result = EmitScalarExpr(e);
  2934. doRetain = true;
  2935. } else {
  2936. TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
  2937. result = subresult.getPointer();
  2938. doRetain = !subresult.getInt();
  2939. }
  2940. if (doRetain)
  2941. result = EmitARCRetainBlock(result, /*mandatory*/ true);
  2942. return EmitObjCConsumeObject(e->getType(), result);
  2943. }
  2944. llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
  2945. // In ARC, retain and autorelease the expression.
  2946. if (getLangOpts().ObjCAutoRefCount) {
  2947. // Do so before running any cleanups for the full-expression.
  2948. // EmitARCRetainAutoreleaseScalarExpr does this for us.
  2949. return EmitARCRetainAutoreleaseScalarExpr(expr);
  2950. }
  2951. // Otherwise, use the normal scalar-expression emission. The
  2952. // exception machinery doesn't do anything special with the
  2953. // exception like retaining it, so there's no safety associated with
  2954. // only running cleanups after the throw has started, and when it
  2955. // matters it tends to be substantially inferior code.
  2956. return EmitScalarExpr(expr);
  2957. }
  2958. namespace {
  2959. /// An emitter for assigning into an __unsafe_unretained context.
  2960. struct ARCUnsafeUnretainedExprEmitter :
  2961. public ARCExprEmitter<ARCUnsafeUnretainedExprEmitter, llvm::Value*> {
  2962. ARCUnsafeUnretainedExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}
  2963. llvm::Value *getValueOfResult(llvm::Value *value) {
  2964. return value;
  2965. }
  2966. llvm::Value *emitBitCast(llvm::Value *value, llvm::Type *resultType) {
  2967. return CGF.Builder.CreateBitCast(value, resultType);
  2968. }
  2969. llvm::Value *visitLValueToRValue(const Expr *e) {
  2970. return CGF.EmitScalarExpr(e);
  2971. }
  2972. /// For consumptions, just emit the subexpression and perform the
  2973. /// consumption like normal.
  2974. llvm::Value *visitConsumeObject(const Expr *e) {
  2975. llvm::Value *value = CGF.EmitScalarExpr(e);
  2976. return CGF.EmitObjCConsumeObject(e->getType(), value);
  2977. }
  2978. /// No special logic for block extensions. (This probably can't
  2979. /// actually happen in this emitter, though.)
  2980. llvm::Value *visitExtendBlockObject(const Expr *e) {
  2981. return CGF.EmitARCExtendBlockObject(e);
  2982. }
  2983. /// For reclaims, perform an unsafeClaim if that's enabled.
  2984. llvm::Value *visitReclaimReturnedObject(const Expr *e) {
  2985. return CGF.EmitARCReclaimReturnedObject(e, /*unsafe*/ true);
  2986. }
  2987. /// When we have an undecorated call, just emit it without adding
  2988. /// the unsafeClaim.
  2989. llvm::Value *visitCall(const Expr *e) {
  2990. return CGF.EmitScalarExpr(e);
  2991. }
  2992. /// Just do normal scalar emission in the default case.
  2993. llvm::Value *visitExpr(const Expr *e) {
  2994. return CGF.EmitScalarExpr(e);
  2995. }
  2996. };
  2997. }
  2998. static llvm::Value *emitARCUnsafeUnretainedScalarExpr(CodeGenFunction &CGF,
  2999. const Expr *e) {
  3000. return ARCUnsafeUnretainedExprEmitter(CGF).visit(e);
  3001. }
  3002. /// EmitARCUnsafeUnretainedScalarExpr - Semantically equivalent to
  3003. /// immediately releasing the resut of EmitARCRetainScalarExpr, but
  3004. /// avoiding any spurious retains, including by performing reclaims
  3005. /// with objc_unsafeClaimAutoreleasedReturnValue.
  3006. llvm::Value *CodeGenFunction::EmitARCUnsafeUnretainedScalarExpr(const Expr *e) {
  3007. // Look through full-expressions.
  3008. if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
  3009. RunCleanupsScope scope(*this);
  3010. return emitARCUnsafeUnretainedScalarExpr(*this, cleanups->getSubExpr());
  3011. }
  3012. return emitARCUnsafeUnretainedScalarExpr(*this, e);
  3013. }
  3014. std::pair<LValue,llvm::Value*>
  3015. CodeGenFunction::EmitARCStoreUnsafeUnretained(const BinaryOperator *e,
  3016. bool ignored) {
  3017. // Evaluate the RHS first. If we're ignoring the result, assume
  3018. // that we can emit at an unsafe +0.
  3019. llvm::Value *value;
  3020. if (ignored) {
  3021. value = EmitARCUnsafeUnretainedScalarExpr(e->getRHS());
  3022. } else {
  3023. value = EmitScalarExpr(e->getRHS());
  3024. }
  3025. // Emit the LHS and perform the store.
  3026. LValue lvalue = EmitLValue(e->getLHS());
  3027. EmitStoreOfScalar(value, lvalue);
  3028. return std::pair<LValue,llvm::Value*>(std::move(lvalue), value);
  3029. }
  3030. std::pair<LValue,llvm::Value*>
  3031. CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
  3032. bool ignored) {
  3033. // Evaluate the RHS first.
  3034. TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
  3035. llvm::Value *value = result.getPointer();
  3036. bool hasImmediateRetain = result.getInt();
  3037. // If we didn't emit a retained object, and the l-value is of block
  3038. // type, then we need to emit the block-retain immediately in case
  3039. // it invalidates the l-value.
  3040. if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
  3041. value = EmitARCRetainBlock(value, /*mandatory*/ false);
  3042. hasImmediateRetain = true;
  3043. }
  3044. LValue lvalue = EmitLValue(e->getLHS());
  3045. // If the RHS was emitted retained, expand this.
  3046. if (hasImmediateRetain) {
  3047. llvm::Value *oldValue = EmitLoadOfScalar(lvalue, SourceLocation());
  3048. EmitStoreOfScalar(value, lvalue);
  3049. EmitARCRelease(oldValue, lvalue.isARCPreciseLifetime());
  3050. } else {
  3051. value = EmitARCStoreStrong(lvalue, value, ignored);
  3052. }
  3053. return std::pair<LValue,llvm::Value*>(lvalue, value);
  3054. }
  3055. std::pair<LValue,llvm::Value*>
  3056. CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
  3057. llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
  3058. LValue lvalue = EmitLValue(e->getLHS());
  3059. EmitStoreOfScalar(value, lvalue);
  3060. return std::pair<LValue,llvm::Value*>(lvalue, value);
  3061. }
  3062. void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
  3063. const ObjCAutoreleasePoolStmt &ARPS) {
  3064. const Stmt *subStmt = ARPS.getSubStmt();
  3065. const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
  3066. CGDebugInfo *DI = getDebugInfo();
  3067. if (DI)
  3068. DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
  3069. // Keep track of the current cleanup stack depth.
  3070. RunCleanupsScope Scope(*this);
  3071. if (CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
  3072. llvm::Value *token = EmitObjCAutoreleasePoolPush();
  3073. EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
  3074. } else {
  3075. llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
  3076. EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
  3077. }
  3078. for (const auto *I : S.body())
  3079. EmitStmt(I);
  3080. if (DI)
  3081. DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
  3082. }
  3083. /// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
  3084. /// make sure it survives garbage collection until this point.
  3085. void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
  3086. // We just use an inline assembly.
  3087. llvm::FunctionType *extenderType
  3088. = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All);
  3089. llvm::InlineAsm *extender = llvm::InlineAsm::get(extenderType,
  3090. /* assembly */ "",
  3091. /* constraints */ "r",
  3092. /* side effects */ true);
  3093. object = Builder.CreateBitCast(object, VoidPtrTy);
  3094. EmitNounwindRuntimeCall(extender, object);
  3095. }
  3096. /// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with
  3097. /// non-trivial copy assignment function, produce following helper function.
  3098. /// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
  3099. ///
  3100. llvm::Constant *
  3101. CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction(
  3102. const ObjCPropertyImplDecl *PID) {
  3103. if (!getLangOpts().CPlusPlus ||
  3104. !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
  3105. return nullptr;
  3106. QualType Ty = PID->getPropertyIvarDecl()->getType();
  3107. if (!Ty->isRecordType())
  3108. return nullptr;
  3109. const ObjCPropertyDecl *PD = PID->getPropertyDecl();
  3110. if ((!(PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_atomic)))
  3111. return nullptr;
  3112. llvm::Constant *HelperFn = nullptr;
  3113. if (hasTrivialSetExpr(PID))
  3114. return nullptr;
  3115. assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
  3116. if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))
  3117. return HelperFn;
  3118. ASTContext &C = getContext();
  3119. IdentifierInfo *II
  3120. = &CGM.getContext().Idents.get("__assign_helper_atomic_property_");
  3121. QualType ReturnTy = C.VoidTy;
  3122. QualType DestTy = C.getPointerType(Ty);
  3123. QualType SrcTy = Ty;
  3124. SrcTy.addConst();
  3125. SrcTy = C.getPointerType(SrcTy);
  3126. SmallVector<QualType, 2> ArgTys;
  3127. ArgTys.push_back(DestTy);
  3128. ArgTys.push_back(SrcTy);
  3129. QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
  3130. FunctionDecl *FD = FunctionDecl::Create(
  3131. C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
  3132. FunctionTy, nullptr, SC_Static, false, false, false);
  3133. FunctionArgList args;
  3134. ParmVarDecl *Params[2];
  3135. ParmVarDecl *DstDecl = ParmVarDecl::Create(
  3136. C, FD, SourceLocation(), SourceLocation(), nullptr, DestTy,
  3137. C.getTrivialTypeSourceInfo(DestTy, SourceLocation()), SC_None,
  3138. /*DefArg=*/nullptr);
  3139. args.push_back(Params[0] = DstDecl);
  3140. ParmVarDecl *SrcDecl = ParmVarDecl::Create(
  3141. C, FD, SourceLocation(), SourceLocation(), nullptr, SrcTy,
  3142. C.getTrivialTypeSourceInfo(SrcTy, SourceLocation()), SC_None,
  3143. /*DefArg=*/nullptr);
  3144. args.push_back(Params[1] = SrcDecl);
  3145. FD->setParams(Params);
  3146. const CGFunctionInfo &FI =
  3147. CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
  3148. llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
  3149. llvm::Function *Fn =
  3150. llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
  3151. "__assign_helper_atomic_property_",
  3152. &CGM.getModule());
  3153. CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
  3154. StartFunction(FD, ReturnTy, Fn, FI, args);
  3155. DeclRefExpr DstExpr(C, DstDecl, false, DestTy, VK_PRValue, SourceLocation());
  3156. UnaryOperator *DST = UnaryOperator::Create(
  3157. C, &DstExpr, UO_Deref, DestTy->getPointeeType(), VK_LValue, OK_Ordinary,
  3158. SourceLocation(), false, FPOptionsOverride());
  3159. DeclRefExpr SrcExpr(C, SrcDecl, false, SrcTy, VK_PRValue, SourceLocation());
  3160. UnaryOperator *SRC = UnaryOperator::Create(
  3161. C, &SrcExpr, UO_Deref, SrcTy->getPointeeType(), VK_LValue, OK_Ordinary,
  3162. SourceLocation(), false, FPOptionsOverride());
  3163. Expr *Args[2] = {DST, SRC};
  3164. CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
  3165. CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
  3166. C, OO_Equal, CalleeExp->getCallee(), Args, DestTy->getPointeeType(),
  3167. VK_LValue, SourceLocation(), FPOptionsOverride());
  3168. EmitStmt(TheCall);
  3169. FinishFunction();
  3170. HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
  3171. CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
  3172. return HelperFn;
  3173. }
  3174. llvm::Constant *
  3175. CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(
  3176. const ObjCPropertyImplDecl *PID) {
  3177. if (!getLangOpts().CPlusPlus ||
  3178. !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
  3179. return nullptr;
  3180. const ObjCPropertyDecl *PD = PID->getPropertyDecl();
  3181. QualType Ty = PD->getType();
  3182. if (!Ty->isRecordType())
  3183. return nullptr;
  3184. if ((!(PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_atomic)))
  3185. return nullptr;
  3186. llvm::Constant *HelperFn = nullptr;
  3187. if (hasTrivialGetExpr(PID))
  3188. return nullptr;
  3189. assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");
  3190. if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
  3191. return HelperFn;
  3192. ASTContext &C = getContext();
  3193. IdentifierInfo *II =
  3194. &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
  3195. QualType ReturnTy = C.VoidTy;
  3196. QualType DestTy = C.getPointerType(Ty);
  3197. QualType SrcTy = Ty;
  3198. SrcTy.addConst();
  3199. SrcTy = C.getPointerType(SrcTy);
  3200. SmallVector<QualType, 2> ArgTys;
  3201. ArgTys.push_back(DestTy);
  3202. ArgTys.push_back(SrcTy);
  3203. QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
  3204. FunctionDecl *FD = FunctionDecl::Create(
  3205. C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
  3206. FunctionTy, nullptr, SC_Static, false, false, false);
  3207. FunctionArgList args;
  3208. ParmVarDecl *Params[2];
  3209. ParmVarDecl *DstDecl = ParmVarDecl::Create(
  3210. C, FD, SourceLocation(), SourceLocation(), nullptr, DestTy,
  3211. C.getTrivialTypeSourceInfo(DestTy, SourceLocation()), SC_None,
  3212. /*DefArg=*/nullptr);
  3213. args.push_back(Params[0] = DstDecl);
  3214. ParmVarDecl *SrcDecl = ParmVarDecl::Create(
  3215. C, FD, SourceLocation(), SourceLocation(), nullptr, SrcTy,
  3216. C.getTrivialTypeSourceInfo(SrcTy, SourceLocation()), SC_None,
  3217. /*DefArg=*/nullptr);
  3218. args.push_back(Params[1] = SrcDecl);
  3219. FD->setParams(Params);
  3220. const CGFunctionInfo &FI =
  3221. CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
  3222. llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
  3223. llvm::Function *Fn = llvm::Function::Create(
  3224. LTy, llvm::GlobalValue::InternalLinkage, "__copy_helper_atomic_property_",
  3225. &CGM.getModule());
  3226. CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
  3227. StartFunction(FD, ReturnTy, Fn, FI, args);
  3228. DeclRefExpr SrcExpr(getContext(), SrcDecl, false, SrcTy, VK_PRValue,
  3229. SourceLocation());
  3230. UnaryOperator *SRC = UnaryOperator::Create(
  3231. C, &SrcExpr, UO_Deref, SrcTy->getPointeeType(), VK_LValue, OK_Ordinary,
  3232. SourceLocation(), false, FPOptionsOverride());
  3233. CXXConstructExpr *CXXConstExpr =
  3234. cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
  3235. SmallVector<Expr*, 4> ConstructorArgs;
  3236. ConstructorArgs.push_back(SRC);
  3237. ConstructorArgs.append(std::next(CXXConstExpr->arg_begin()),
  3238. CXXConstExpr->arg_end());
  3239. CXXConstructExpr *TheCXXConstructExpr =
  3240. CXXConstructExpr::Create(C, Ty, SourceLocation(),
  3241. CXXConstExpr->getConstructor(),
  3242. CXXConstExpr->isElidable(),
  3243. ConstructorArgs,
  3244. CXXConstExpr->hadMultipleCandidates(),
  3245. CXXConstExpr->isListInitialization(),
  3246. CXXConstExpr->isStdInitListInitialization(),
  3247. CXXConstExpr->requiresZeroInitialization(),
  3248. CXXConstExpr->getConstructionKind(),
  3249. SourceRange());
  3250. DeclRefExpr DstExpr(getContext(), DstDecl, false, DestTy, VK_PRValue,
  3251. SourceLocation());
  3252. RValue DV = EmitAnyExpr(&DstExpr);
  3253. CharUnits Alignment
  3254. = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());
  3255. EmitAggExpr(TheCXXConstructExpr,
  3256. AggValueSlot::forAddr(Address(DV.getScalarVal(), Alignment),
  3257. Qualifiers(),
  3258. AggValueSlot::IsDestructed,
  3259. AggValueSlot::DoesNotNeedGCBarriers,
  3260. AggValueSlot::IsNotAliased,
  3261. AggValueSlot::DoesNotOverlap));
  3262. FinishFunction();
  3263. HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
  3264. CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);
  3265. return HelperFn;
  3266. }
  3267. llvm::Value *
  3268. CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty) {
  3269. // Get selectors for retain/autorelease.
  3270. IdentifierInfo *CopyID = &getContext().Idents.get("copy");
  3271. Selector CopySelector =
  3272. getContext().Selectors.getNullarySelector(CopyID);
  3273. IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease");
  3274. Selector AutoreleaseSelector =
  3275. getContext().Selectors.getNullarySelector(AutoreleaseID);
  3276. // Emit calls to retain/autorelease.
  3277. CGObjCRuntime &Runtime = CGM.getObjCRuntime();
  3278. llvm::Value *Val = Block;
  3279. RValue Result;
  3280. Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
  3281. Ty, CopySelector,
  3282. Val, CallArgList(), nullptr, nullptr);
  3283. Val = Result.getScalarVal();
  3284. Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
  3285. Ty, AutoreleaseSelector,
  3286. Val, CallArgList(), nullptr, nullptr);
  3287. Val = Result.getScalarVal();
  3288. return Val;
  3289. }
  3290. static unsigned getBaseMachOPlatformID(const llvm::Triple &TT) {
  3291. switch (TT.getOS()) {
  3292. case llvm::Triple::Darwin:
  3293. case llvm::Triple::MacOSX:
  3294. return llvm::MachO::PLATFORM_MACOS;
  3295. case llvm::Triple::IOS:
  3296. return llvm::MachO::PLATFORM_IOS;
  3297. case llvm::Triple::TvOS:
  3298. return llvm::MachO::PLATFORM_TVOS;
  3299. case llvm::Triple::WatchOS:
  3300. return llvm::MachO::PLATFORM_WATCHOS;
  3301. default:
  3302. return /*Unknown platform*/ 0;
  3303. }
  3304. }
  3305. static llvm::Value *emitIsPlatformVersionAtLeast(CodeGenFunction &CGF,
  3306. const VersionTuple &Version) {
  3307. CodeGenModule &CGM = CGF.CGM;
  3308. // Note: we intend to support multi-platform version checks, so reserve
  3309. // the room for a dual platform checking invocation that will be
  3310. // implemented in the future.
  3311. llvm::SmallVector<llvm::Value *, 8> Args;
  3312. auto EmitArgs = [&](const VersionTuple &Version, const llvm::Triple &TT) {
  3313. Optional<unsigned> Min = Version.getMinor(), SMin = Version.getSubminor();
  3314. Args.push_back(
  3315. llvm::ConstantInt::get(CGM.Int32Ty, getBaseMachOPlatformID(TT)));
  3316. Args.push_back(llvm::ConstantInt::get(CGM.Int32Ty, Version.getMajor()));
  3317. Args.push_back(llvm::ConstantInt::get(CGM.Int32Ty, Min.getValueOr(0)));
  3318. Args.push_back(llvm::ConstantInt::get(CGM.Int32Ty, SMin.getValueOr(0)));
  3319. };
  3320. assert(!Version.empty() && "unexpected empty version");
  3321. EmitArgs(Version, CGM.getTarget().getTriple());
  3322. if (!CGM.IsPlatformVersionAtLeastFn) {
  3323. llvm::FunctionType *FTy = llvm::FunctionType::get(
  3324. CGM.Int32Ty, {CGM.Int32Ty, CGM.Int32Ty, CGM.Int32Ty, CGM.Int32Ty},
  3325. false);
  3326. CGM.IsPlatformVersionAtLeastFn =
  3327. CGM.CreateRuntimeFunction(FTy, "__isPlatformVersionAtLeast");
  3328. }
  3329. llvm::Value *Check =
  3330. CGF.EmitNounwindRuntimeCall(CGM.IsPlatformVersionAtLeastFn, Args);
  3331. return CGF.Builder.CreateICmpNE(Check,
  3332. llvm::Constant::getNullValue(CGM.Int32Ty));
  3333. }
  3334. llvm::Value *
  3335. CodeGenFunction::EmitBuiltinAvailable(const VersionTuple &Version) {
  3336. // Darwin uses the new __isPlatformVersionAtLeast family of routines.
  3337. if (CGM.getTarget().getTriple().isOSDarwin())
  3338. return emitIsPlatformVersionAtLeast(*this, Version);
  3339. if (!CGM.IsOSVersionAtLeastFn) {
  3340. llvm::FunctionType *FTy =
  3341. llvm::FunctionType::get(Int32Ty, {Int32Ty, Int32Ty, Int32Ty}, false);
  3342. CGM.IsOSVersionAtLeastFn =
  3343. CGM.CreateRuntimeFunction(FTy, "__isOSVersionAtLeast");
  3344. }
  3345. Optional<unsigned> Min = Version.getMinor(), SMin = Version.getSubminor();
  3346. llvm::Value *Args[] = {
  3347. llvm::ConstantInt::get(CGM.Int32Ty, Version.getMajor()),
  3348. llvm::ConstantInt::get(CGM.Int32Ty, Min.getValueOr(0)),
  3349. llvm::ConstantInt::get(CGM.Int32Ty, SMin.getValueOr(0))
  3350. };
  3351. llvm::Value *CallRes =
  3352. EmitNounwindRuntimeCall(CGM.IsOSVersionAtLeastFn, Args);
  3353. return Builder.CreateICmpNE(CallRes, llvm::Constant::getNullValue(Int32Ty));
  3354. }
  3355. static bool isFoundationNeededForDarwinAvailabilityCheck(
  3356. const llvm::Triple &TT, const VersionTuple &TargetVersion) {
  3357. VersionTuple FoundationDroppedInVersion;
  3358. switch (TT.getOS()) {
  3359. case llvm::Triple::IOS:
  3360. case llvm::Triple::TvOS:
  3361. FoundationDroppedInVersion = VersionTuple(/*Major=*/13);
  3362. break;
  3363. case llvm::Triple::WatchOS:
  3364. FoundationDroppedInVersion = VersionTuple(/*Major=*/6);
  3365. break;
  3366. case llvm::Triple::Darwin:
  3367. case llvm::Triple::MacOSX:
  3368. FoundationDroppedInVersion = VersionTuple(/*Major=*/10, /*Minor=*/15);
  3369. break;
  3370. default:
  3371. llvm_unreachable("Unexpected OS");
  3372. }
  3373. return TargetVersion < FoundationDroppedInVersion;
  3374. }
  3375. void CodeGenModule::emitAtAvailableLinkGuard() {
  3376. if (!IsPlatformVersionAtLeastFn)
  3377. return;
  3378. // @available requires CoreFoundation only on Darwin.
  3379. if (!Target.getTriple().isOSDarwin())
  3380. return;
  3381. // @available doesn't need Foundation on macOS 10.15+, iOS/tvOS 13+, or
  3382. // watchOS 6+.
  3383. if (!isFoundationNeededForDarwinAvailabilityCheck(
  3384. Target.getTriple(), Target.getPlatformMinVersion()))
  3385. return;
  3386. // Add -framework CoreFoundation to the linker commands. We still want to
  3387. // emit the core foundation reference down below because otherwise if
  3388. // CoreFoundation is not used in the code, the linker won't link the
  3389. // framework.
  3390. auto &Context = getLLVMContext();
  3391. llvm::Metadata *Args[2] = {llvm::MDString::get(Context, "-framework"),
  3392. llvm::MDString::get(Context, "CoreFoundation")};
  3393. LinkerOptionsMetadata.push_back(llvm::MDNode::get(Context, Args));
  3394. // Emit a reference to a symbol from CoreFoundation to ensure that
  3395. // CoreFoundation is linked into the final binary.
  3396. llvm::FunctionType *FTy =
  3397. llvm::FunctionType::get(Int32Ty, {VoidPtrTy}, false);
  3398. llvm::FunctionCallee CFFunc =
  3399. CreateRuntimeFunction(FTy, "CFBundleGetVersionNumber");
  3400. llvm::FunctionType *CheckFTy = llvm::FunctionType::get(VoidTy, {}, false);
  3401. llvm::FunctionCallee CFLinkCheckFuncRef = CreateRuntimeFunction(
  3402. CheckFTy, "__clang_at_available_requires_core_foundation_framework",
  3403. llvm::AttributeList(), /*Local=*/true);
  3404. llvm::Function *CFLinkCheckFunc =
  3405. cast<llvm::Function>(CFLinkCheckFuncRef.getCallee()->stripPointerCasts());
  3406. if (CFLinkCheckFunc->empty()) {
  3407. CFLinkCheckFunc->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
  3408. CFLinkCheckFunc->setVisibility(llvm::GlobalValue::HiddenVisibility);
  3409. CodeGenFunction CGF(*this);
  3410. CGF.Builder.SetInsertPoint(CGF.createBasicBlock("", CFLinkCheckFunc));
  3411. CGF.EmitNounwindRuntimeCall(CFFunc,
  3412. llvm::Constant::getNullValue(VoidPtrTy));
  3413. CGF.Builder.CreateUnreachable();
  3414. addCompilerUsedGlobal(CFLinkCheckFunc);
  3415. }
  3416. }
  3417. CGObjCRuntime::~CGObjCRuntime() {}