CGObjC.cpp 141 KB

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