CGBlocks.cpp 86 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378
  1. //===--- CGBlocks.cpp - Emit LLVM Code for declarations ---------*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This contains code to emit blocks.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CGBlocks.h"
  14. #include "CGDebugInfo.h"
  15. #include "CGObjCRuntime.h"
  16. #include "CodeGenFunction.h"
  17. #include "CodeGenModule.h"
  18. #include "ConstantBuilder.h"
  19. #include "clang/AST/DeclObjC.h"
  20. #include "llvm/ADT/SmallSet.h"
  21. #include "llvm/IR/CallSite.h"
  22. #include "llvm/IR/DataLayout.h"
  23. #include "llvm/IR/Module.h"
  24. #include <algorithm>
  25. #include <cstdio>
  26. using namespace clang;
  27. using namespace CodeGen;
  28. CGBlockInfo::CGBlockInfo(const BlockDecl *block, StringRef name)
  29. : Name(name), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
  30. HasCXXObject(false), UsesStret(false), HasCapturedVariableLayout(false),
  31. LocalAddress(Address::invalid()), StructureType(nullptr), Block(block),
  32. DominatingIP(nullptr) {
  33. // Skip asm prefix, if any. 'name' is usually taken directly from
  34. // the mangled name of the enclosing function.
  35. if (!name.empty() && name[0] == '\01')
  36. name = name.substr(1);
  37. }
  38. // Anchor the vtable to this translation unit.
  39. BlockByrefHelpers::~BlockByrefHelpers() {}
  40. /// Build the given block as a global block.
  41. static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
  42. const CGBlockInfo &blockInfo,
  43. llvm::Constant *blockFn);
  44. /// Build the helper function to copy a block.
  45. static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
  46. const CGBlockInfo &blockInfo) {
  47. return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
  48. }
  49. /// Build the helper function to dispose of a block.
  50. static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
  51. const CGBlockInfo &blockInfo) {
  52. return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
  53. }
  54. /// buildBlockDescriptor - Build the block descriptor meta-data for a block.
  55. /// buildBlockDescriptor is accessed from 5th field of the Block_literal
  56. /// meta-data and contains stationary information about the block literal.
  57. /// Its definition will have 4 (or optinally 6) words.
  58. /// \code
  59. /// struct Block_descriptor {
  60. /// unsigned long reserved;
  61. /// unsigned long size; // size of Block_literal metadata in bytes.
  62. /// void *copy_func_helper_decl; // optional copy helper.
  63. /// void *destroy_func_decl; // optioanl destructor helper.
  64. /// void *block_method_encoding_address; // @encode for block literal signature.
  65. /// void *block_layout_info; // encoding of captured block variables.
  66. /// };
  67. /// \endcode
  68. static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
  69. const CGBlockInfo &blockInfo) {
  70. ASTContext &C = CGM.getContext();
  71. llvm::IntegerType *ulong =
  72. cast<llvm::IntegerType>(CGM.getTypes().ConvertType(C.UnsignedLongTy));
  73. llvm::PointerType *i8p = nullptr;
  74. if (CGM.getLangOpts().OpenCL)
  75. i8p =
  76. llvm::Type::getInt8PtrTy(
  77. CGM.getLLVMContext(), C.getTargetAddressSpace(LangAS::opencl_constant));
  78. else
  79. i8p = CGM.VoidPtrTy;
  80. ConstantInitBuilder builder(CGM);
  81. auto elements = builder.beginStruct();
  82. // reserved
  83. elements.addInt(ulong, 0);
  84. // Size
  85. // FIXME: What is the right way to say this doesn't fit? We should give
  86. // a user diagnostic in that case. Better fix would be to change the
  87. // API to size_t.
  88. elements.addInt(ulong, blockInfo.BlockSize.getQuantity());
  89. // Optional copy/dispose helpers.
  90. if (blockInfo.NeedsCopyDispose) {
  91. // copy_func_helper_decl
  92. elements.add(buildCopyHelper(CGM, blockInfo));
  93. // destroy_func_decl
  94. elements.add(buildDisposeHelper(CGM, blockInfo));
  95. }
  96. // Signature. Mandatory ObjC-style method descriptor @encode sequence.
  97. std::string typeAtEncoding =
  98. CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
  99. elements.add(llvm::ConstantExpr::getBitCast(
  100. CGM.GetAddrOfConstantCString(typeAtEncoding).getPointer(), i8p));
  101. // GC layout.
  102. if (C.getLangOpts().ObjC1) {
  103. if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
  104. elements.add(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
  105. else
  106. elements.add(CGM.getObjCRuntime().BuildRCBlockLayout(CGM, blockInfo));
  107. }
  108. else
  109. elements.addNullPointer(i8p);
  110. unsigned AddrSpace = 0;
  111. if (C.getLangOpts().OpenCL)
  112. AddrSpace = C.getTargetAddressSpace(LangAS::opencl_constant);
  113. llvm::GlobalVariable *global =
  114. elements.finishAndCreateGlobal("__block_descriptor_tmp",
  115. CGM.getPointerAlign(),
  116. /*constant*/ true,
  117. llvm::GlobalValue::InternalLinkage,
  118. AddrSpace);
  119. return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
  120. }
  121. /*
  122. Purely notional variadic template describing the layout of a block.
  123. template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
  124. struct Block_literal {
  125. /// Initialized to one of:
  126. /// extern void *_NSConcreteStackBlock[];
  127. /// extern void *_NSConcreteGlobalBlock[];
  128. ///
  129. /// In theory, we could start one off malloc'ed by setting
  130. /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
  131. /// this isa:
  132. /// extern void *_NSConcreteMallocBlock[];
  133. struct objc_class *isa;
  134. /// These are the flags (with corresponding bit number) that the
  135. /// compiler is actually supposed to know about.
  136. /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
  137. /// descriptor provides copy and dispose helper functions
  138. /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
  139. /// object with a nontrivial destructor or copy constructor
  140. /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
  141. /// as global memory
  142. /// 29. BLOCK_USE_STRET - indicates that the block function
  143. /// uses stret, which objc_msgSend needs to know about
  144. /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
  145. /// @encoded signature string
  146. /// And we're not supposed to manipulate these:
  147. /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
  148. /// to malloc'ed memory
  149. /// 27. BLOCK_IS_GC - indicates that the block has been moved to
  150. /// to GC-allocated memory
  151. /// Additionally, the bottom 16 bits are a reference count which
  152. /// should be zero on the stack.
  153. int flags;
  154. /// Reserved; should be zero-initialized.
  155. int reserved;
  156. /// Function pointer generated from block literal.
  157. _ResultType (*invoke)(Block_literal *, _ParamTypes...);
  158. /// Block description metadata generated from block literal.
  159. struct Block_descriptor *block_descriptor;
  160. /// Captured values follow.
  161. _CapturesTypes captures...;
  162. };
  163. */
  164. namespace {
  165. /// A chunk of data that we actually have to capture in the block.
  166. struct BlockLayoutChunk {
  167. CharUnits Alignment;
  168. CharUnits Size;
  169. Qualifiers::ObjCLifetime Lifetime;
  170. const BlockDecl::Capture *Capture; // null for 'this'
  171. llvm::Type *Type;
  172. QualType FieldType;
  173. BlockLayoutChunk(CharUnits align, CharUnits size,
  174. Qualifiers::ObjCLifetime lifetime,
  175. const BlockDecl::Capture *capture,
  176. llvm::Type *type, QualType fieldType)
  177. : Alignment(align), Size(size), Lifetime(lifetime),
  178. Capture(capture), Type(type), FieldType(fieldType) {}
  179. /// Tell the block info that this chunk has the given field index.
  180. void setIndex(CGBlockInfo &info, unsigned index, CharUnits offset) {
  181. if (!Capture) {
  182. info.CXXThisIndex = index;
  183. info.CXXThisOffset = offset;
  184. } else {
  185. auto C = CGBlockInfo::Capture::makeIndex(index, offset, FieldType);
  186. info.Captures.insert({Capture->getVariable(), C});
  187. }
  188. }
  189. };
  190. /// Order by 1) all __strong together 2) next, all byfref together 3) next,
  191. /// all __weak together. Preserve descending alignment in all situations.
  192. bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
  193. if (left.Alignment != right.Alignment)
  194. return left.Alignment > right.Alignment;
  195. auto getPrefOrder = [](const BlockLayoutChunk &chunk) {
  196. if (chunk.Capture && chunk.Capture->isByRef())
  197. return 1;
  198. if (chunk.Lifetime == Qualifiers::OCL_Strong)
  199. return 0;
  200. if (chunk.Lifetime == Qualifiers::OCL_Weak)
  201. return 2;
  202. return 3;
  203. };
  204. return getPrefOrder(left) < getPrefOrder(right);
  205. }
  206. } // end anonymous namespace
  207. /// Determines if the given type is safe for constant capture in C++.
  208. static bool isSafeForCXXConstantCapture(QualType type) {
  209. const RecordType *recordType =
  210. type->getBaseElementTypeUnsafe()->getAs<RecordType>();
  211. // Only records can be unsafe.
  212. if (!recordType) return true;
  213. const auto *record = cast<CXXRecordDecl>(recordType->getDecl());
  214. // Maintain semantics for classes with non-trivial dtors or copy ctors.
  215. if (!record->hasTrivialDestructor()) return false;
  216. if (record->hasNonTrivialCopyConstructor()) return false;
  217. // Otherwise, we just have to make sure there aren't any mutable
  218. // fields that might have changed since initialization.
  219. return !record->hasMutableFields();
  220. }
  221. /// It is illegal to modify a const object after initialization.
  222. /// Therefore, if a const object has a constant initializer, we don't
  223. /// actually need to keep storage for it in the block; we'll just
  224. /// rematerialize it at the start of the block function. This is
  225. /// acceptable because we make no promises about address stability of
  226. /// captured variables.
  227. static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
  228. CodeGenFunction *CGF,
  229. const VarDecl *var) {
  230. // Return if this is a function paramter. We shouldn't try to
  231. // rematerialize default arguments of function parameters.
  232. if (isa<ParmVarDecl>(var))
  233. return nullptr;
  234. QualType type = var->getType();
  235. // We can only do this if the variable is const.
  236. if (!type.isConstQualified()) return nullptr;
  237. // Furthermore, in C++ we have to worry about mutable fields:
  238. // C++ [dcl.type.cv]p4:
  239. // Except that any class member declared mutable can be
  240. // modified, any attempt to modify a const object during its
  241. // lifetime results in undefined behavior.
  242. if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
  243. return nullptr;
  244. // If the variable doesn't have any initializer (shouldn't this be
  245. // invalid?), it's not clear what we should do. Maybe capture as
  246. // zero?
  247. const Expr *init = var->getInit();
  248. if (!init) return nullptr;
  249. return CGM.EmitConstantInit(*var, CGF);
  250. }
  251. /// Get the low bit of a nonzero character count. This is the
  252. /// alignment of the nth byte if the 0th byte is universally aligned.
  253. static CharUnits getLowBit(CharUnits v) {
  254. return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
  255. }
  256. static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
  257. SmallVectorImpl<llvm::Type*> &elementTypes) {
  258. // The header is basically 'struct { void *; int; int; void *; void *; }'.
  259. // Assert that that struct is packed.
  260. assert(CGM.getIntSize() <= CGM.getPointerSize());
  261. assert(CGM.getIntAlign() <= CGM.getPointerAlign());
  262. assert((2 * CGM.getIntSize()).isMultipleOf(CGM.getPointerAlign()));
  263. info.BlockAlign = CGM.getPointerAlign();
  264. info.BlockSize = 3 * CGM.getPointerSize() + 2 * CGM.getIntSize();
  265. assert(elementTypes.empty());
  266. elementTypes.push_back(CGM.VoidPtrTy);
  267. elementTypes.push_back(CGM.IntTy);
  268. elementTypes.push_back(CGM.IntTy);
  269. elementTypes.push_back(CGM.VoidPtrTy);
  270. elementTypes.push_back(CGM.getBlockDescriptorType());
  271. }
  272. /// Compute the layout of the given block. Attempts to lay the block
  273. /// out with minimal space requirements.
  274. static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
  275. CGBlockInfo &info) {
  276. ASTContext &C = CGM.getContext();
  277. const BlockDecl *block = info.getBlockDecl();
  278. SmallVector<llvm::Type*, 8> elementTypes;
  279. initializeForBlockHeader(CGM, info, elementTypes);
  280. if (!block->hasCaptures()) {
  281. info.StructureType =
  282. llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
  283. info.CanBeGlobal = true;
  284. return;
  285. }
  286. else if (C.getLangOpts().ObjC1 &&
  287. CGM.getLangOpts().getGC() == LangOptions::NonGC)
  288. info.HasCapturedVariableLayout = true;
  289. // Collect the layout chunks.
  290. SmallVector<BlockLayoutChunk, 16> layout;
  291. layout.reserve(block->capturesCXXThis() +
  292. (block->capture_end() - block->capture_begin()));
  293. CharUnits maxFieldAlign;
  294. // First, 'this'.
  295. if (block->capturesCXXThis()) {
  296. assert(CGF && CGF->CurFuncDecl && isa<CXXMethodDecl>(CGF->CurFuncDecl) &&
  297. "Can't capture 'this' outside a method");
  298. QualType thisType = cast<CXXMethodDecl>(CGF->CurFuncDecl)->getThisType(C);
  299. // Theoretically, this could be in a different address space, so
  300. // don't assume standard pointer size/align.
  301. llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
  302. std::pair<CharUnits,CharUnits> tinfo
  303. = CGM.getContext().getTypeInfoInChars(thisType);
  304. maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
  305. layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
  306. Qualifiers::OCL_None,
  307. nullptr, llvmType, thisType));
  308. }
  309. // Next, all the block captures.
  310. for (const auto &CI : block->captures()) {
  311. const VarDecl *variable = CI.getVariable();
  312. if (CI.isByRef()) {
  313. // We have to copy/dispose of the __block reference.
  314. info.NeedsCopyDispose = true;
  315. // Just use void* instead of a pointer to the byref type.
  316. CharUnits align = CGM.getPointerAlign();
  317. maxFieldAlign = std::max(maxFieldAlign, align);
  318. layout.push_back(BlockLayoutChunk(align, CGM.getPointerSize(),
  319. Qualifiers::OCL_None, &CI,
  320. CGM.VoidPtrTy, variable->getType()));
  321. continue;
  322. }
  323. // Otherwise, build a layout chunk with the size and alignment of
  324. // the declaration.
  325. if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
  326. info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
  327. continue;
  328. }
  329. // If we have a lifetime qualifier, honor it for capture purposes.
  330. // That includes *not* copying it if it's __unsafe_unretained.
  331. Qualifiers::ObjCLifetime lifetime =
  332. variable->getType().getObjCLifetime();
  333. if (lifetime) {
  334. switch (lifetime) {
  335. case Qualifiers::OCL_None: llvm_unreachable("impossible");
  336. case Qualifiers::OCL_ExplicitNone:
  337. case Qualifiers::OCL_Autoreleasing:
  338. break;
  339. case Qualifiers::OCL_Strong:
  340. case Qualifiers::OCL_Weak:
  341. info.NeedsCopyDispose = true;
  342. }
  343. // Block pointers require copy/dispose. So do Objective-C pointers.
  344. } else if (variable->getType()->isObjCRetainableType()) {
  345. // But honor the inert __unsafe_unretained qualifier, which doesn't
  346. // actually make it into the type system.
  347. if (variable->getType()->isObjCInertUnsafeUnretainedType()) {
  348. lifetime = Qualifiers::OCL_ExplicitNone;
  349. } else {
  350. info.NeedsCopyDispose = true;
  351. // used for mrr below.
  352. lifetime = Qualifiers::OCL_Strong;
  353. }
  354. // So do types that require non-trivial copy construction.
  355. } else if (CI.hasCopyExpr()) {
  356. info.NeedsCopyDispose = true;
  357. info.HasCXXObject = true;
  358. // And so do types with destructors.
  359. } else if (CGM.getLangOpts().CPlusPlus) {
  360. if (const CXXRecordDecl *record =
  361. variable->getType()->getAsCXXRecordDecl()) {
  362. if (!record->hasTrivialDestructor()) {
  363. info.HasCXXObject = true;
  364. info.NeedsCopyDispose = true;
  365. }
  366. }
  367. }
  368. QualType VT = variable->getType();
  369. // If the variable is captured by an enclosing block or lambda expression,
  370. // use the type of the capture field.
  371. if (CGF->BlockInfo && CI.isNested())
  372. VT = CGF->BlockInfo->getCapture(variable).fieldType();
  373. else if (auto *FD = CGF->LambdaCaptureFields.lookup(variable))
  374. VT = FD->getType();
  375. CharUnits size = C.getTypeSizeInChars(VT);
  376. CharUnits align = C.getDeclAlign(variable);
  377. maxFieldAlign = std::max(maxFieldAlign, align);
  378. llvm::Type *llvmType =
  379. CGM.getTypes().ConvertTypeForMem(VT);
  380. layout.push_back(
  381. BlockLayoutChunk(align, size, lifetime, &CI, llvmType, VT));
  382. }
  383. // If that was everything, we're done here.
  384. if (layout.empty()) {
  385. info.StructureType =
  386. llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
  387. info.CanBeGlobal = true;
  388. return;
  389. }
  390. // Sort the layout by alignment. We have to use a stable sort here
  391. // to get reproducible results. There should probably be an
  392. // llvm::array_pod_stable_sort.
  393. std::stable_sort(layout.begin(), layout.end());
  394. // Needed for blocks layout info.
  395. info.BlockHeaderForcedGapOffset = info.BlockSize;
  396. info.BlockHeaderForcedGapSize = CharUnits::Zero();
  397. CharUnits &blockSize = info.BlockSize;
  398. info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
  399. // Assuming that the first byte in the header is maximally aligned,
  400. // get the alignment of the first byte following the header.
  401. CharUnits endAlign = getLowBit(blockSize);
  402. // If the end of the header isn't satisfactorily aligned for the
  403. // maximum thing, look for things that are okay with the header-end
  404. // alignment, and keep appending them until we get something that's
  405. // aligned right. This algorithm is only guaranteed optimal if
  406. // that condition is satisfied at some point; otherwise we can get
  407. // things like:
  408. // header // next byte has alignment 4
  409. // something_with_size_5; // next byte has alignment 1
  410. // something_with_alignment_8;
  411. // which has 7 bytes of padding, as opposed to the naive solution
  412. // which might have less (?).
  413. if (endAlign < maxFieldAlign) {
  414. SmallVectorImpl<BlockLayoutChunk>::iterator
  415. li = layout.begin() + 1, le = layout.end();
  416. // Look for something that the header end is already
  417. // satisfactorily aligned for.
  418. for (; li != le && endAlign < li->Alignment; ++li)
  419. ;
  420. // If we found something that's naturally aligned for the end of
  421. // the header, keep adding things...
  422. if (li != le) {
  423. SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
  424. for (; li != le; ++li) {
  425. assert(endAlign >= li->Alignment);
  426. li->setIndex(info, elementTypes.size(), blockSize);
  427. elementTypes.push_back(li->Type);
  428. blockSize += li->Size;
  429. endAlign = getLowBit(blockSize);
  430. // ...until we get to the alignment of the maximum field.
  431. if (endAlign >= maxFieldAlign) {
  432. break;
  433. }
  434. }
  435. // Don't re-append everything we just appended.
  436. layout.erase(first, li);
  437. }
  438. }
  439. assert(endAlign == getLowBit(blockSize));
  440. // At this point, we just have to add padding if the end align still
  441. // isn't aligned right.
  442. if (endAlign < maxFieldAlign) {
  443. CharUnits newBlockSize = blockSize.alignTo(maxFieldAlign);
  444. CharUnits padding = newBlockSize - blockSize;
  445. // If we haven't yet added any fields, remember that there was an
  446. // initial gap; this need to go into the block layout bit map.
  447. if (blockSize == info.BlockHeaderForcedGapOffset) {
  448. info.BlockHeaderForcedGapSize = padding;
  449. }
  450. elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
  451. padding.getQuantity()));
  452. blockSize = newBlockSize;
  453. endAlign = getLowBit(blockSize); // might be > maxFieldAlign
  454. }
  455. assert(endAlign >= maxFieldAlign);
  456. assert(endAlign == getLowBit(blockSize));
  457. // Slam everything else on now. This works because they have
  458. // strictly decreasing alignment and we expect that size is always a
  459. // multiple of alignment.
  460. for (SmallVectorImpl<BlockLayoutChunk>::iterator
  461. li = layout.begin(), le = layout.end(); li != le; ++li) {
  462. if (endAlign < li->Alignment) {
  463. // size may not be multiple of alignment. This can only happen with
  464. // an over-aligned variable. We will be adding a padding field to
  465. // make the size be multiple of alignment.
  466. CharUnits padding = li->Alignment - endAlign;
  467. elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
  468. padding.getQuantity()));
  469. blockSize += padding;
  470. endAlign = getLowBit(blockSize);
  471. }
  472. assert(endAlign >= li->Alignment);
  473. li->setIndex(info, elementTypes.size(), blockSize);
  474. elementTypes.push_back(li->Type);
  475. blockSize += li->Size;
  476. endAlign = getLowBit(blockSize);
  477. }
  478. info.StructureType =
  479. llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
  480. }
  481. /// Enter the scope of a block. This should be run at the entrance to
  482. /// a full-expression so that the block's cleanups are pushed at the
  483. /// right place in the stack.
  484. static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
  485. assert(CGF.HaveInsertPoint());
  486. // Allocate the block info and place it at the head of the list.
  487. CGBlockInfo &blockInfo =
  488. *new CGBlockInfo(block, CGF.CurFn->getName());
  489. blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
  490. CGF.FirstBlockInfo = &blockInfo;
  491. // Compute information about the layout, etc., of this block,
  492. // pushing cleanups as necessary.
  493. computeBlockInfo(CGF.CGM, &CGF, blockInfo);
  494. // Nothing else to do if it can be global.
  495. if (blockInfo.CanBeGlobal) return;
  496. // Make the allocation for the block.
  497. blockInfo.LocalAddress = CGF.CreateTempAlloca(blockInfo.StructureType,
  498. blockInfo.BlockAlign, "block");
  499. // If there are cleanups to emit, enter them (but inactive).
  500. if (!blockInfo.NeedsCopyDispose) return;
  501. // Walk through the captures (in order) and find the ones not
  502. // captured by constant.
  503. for (const auto &CI : block->captures()) {
  504. // Ignore __block captures; there's nothing special in the
  505. // on-stack block that we need to do for them.
  506. if (CI.isByRef()) continue;
  507. // Ignore variables that are constant-captured.
  508. const VarDecl *variable = CI.getVariable();
  509. CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
  510. if (capture.isConstant()) continue;
  511. // Ignore objects that aren't destructed.
  512. QualType::DestructionKind dtorKind =
  513. variable->getType().isDestructedType();
  514. if (dtorKind == QualType::DK_none) continue;
  515. CodeGenFunction::Destroyer *destroyer;
  516. // Block captures count as local values and have imprecise semantics.
  517. // They also can't be arrays, so need to worry about that.
  518. if (dtorKind == QualType::DK_objc_strong_lifetime) {
  519. destroyer = CodeGenFunction::destroyARCStrongImprecise;
  520. } else {
  521. destroyer = CGF.getDestroyer(dtorKind);
  522. }
  523. // GEP down to the address.
  524. Address addr = CGF.Builder.CreateStructGEP(blockInfo.LocalAddress,
  525. capture.getIndex(),
  526. capture.getOffset());
  527. // We can use that GEP as the dominating IP.
  528. if (!blockInfo.DominatingIP)
  529. blockInfo.DominatingIP = cast<llvm::Instruction>(addr.getPointer());
  530. CleanupKind cleanupKind = InactiveNormalCleanup;
  531. bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
  532. if (useArrayEHCleanup)
  533. cleanupKind = InactiveNormalAndEHCleanup;
  534. CGF.pushDestroy(cleanupKind, addr, variable->getType(),
  535. destroyer, useArrayEHCleanup);
  536. // Remember where that cleanup was.
  537. capture.setCleanup(CGF.EHStack.stable_begin());
  538. }
  539. }
  540. /// Enter a full-expression with a non-trivial number of objects to
  541. /// clean up. This is in this file because, at the moment, the only
  542. /// kind of cleanup object is a BlockDecl*.
  543. void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) {
  544. assert(E->getNumObjects() != 0);
  545. ArrayRef<ExprWithCleanups::CleanupObject> cleanups = E->getObjects();
  546. for (ArrayRef<ExprWithCleanups::CleanupObject>::iterator
  547. i = cleanups.begin(), e = cleanups.end(); i != e; ++i) {
  548. enterBlockScope(*this, *i);
  549. }
  550. }
  551. /// Find the layout for the given block in a linked list and remove it.
  552. static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
  553. const BlockDecl *block) {
  554. while (true) {
  555. assert(head && *head);
  556. CGBlockInfo *cur = *head;
  557. // If this is the block we're looking for, splice it out of the list.
  558. if (cur->getBlockDecl() == block) {
  559. *head = cur->NextBlockInfo;
  560. return cur;
  561. }
  562. head = &cur->NextBlockInfo;
  563. }
  564. }
  565. /// Destroy a chain of block layouts.
  566. void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
  567. assert(head && "destroying an empty chain");
  568. do {
  569. CGBlockInfo *cur = head;
  570. head = cur->NextBlockInfo;
  571. delete cur;
  572. } while (head != nullptr);
  573. }
  574. /// Emit a block literal expression in the current function.
  575. llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
  576. // If the block has no captures, we won't have a pre-computed
  577. // layout for it.
  578. if (!blockExpr->getBlockDecl()->hasCaptures()) {
  579. CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
  580. computeBlockInfo(CGM, this, blockInfo);
  581. blockInfo.BlockExpression = blockExpr;
  582. return EmitBlockLiteral(blockInfo);
  583. }
  584. // Find the block info for this block and take ownership of it.
  585. std::unique_ptr<CGBlockInfo> blockInfo;
  586. blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
  587. blockExpr->getBlockDecl()));
  588. blockInfo->BlockExpression = blockExpr;
  589. return EmitBlockLiteral(*blockInfo);
  590. }
  591. llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
  592. // Using the computed layout, generate the actual block function.
  593. bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
  594. llvm::Constant *blockFn
  595. = CodeGenFunction(CGM, true).GenerateBlockFunction(CurGD, blockInfo,
  596. LocalDeclMap,
  597. isLambdaConv);
  598. blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
  599. // If there is nothing to capture, we can emit this as a global block.
  600. if (blockInfo.CanBeGlobal)
  601. return buildGlobalBlock(CGM, blockInfo, blockFn);
  602. // Otherwise, we have to emit this as a local block.
  603. llvm::Constant *isa = CGM.getNSConcreteStackBlock();
  604. isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
  605. // Build the block descriptor.
  606. llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
  607. Address blockAddr = blockInfo.LocalAddress;
  608. assert(blockAddr.isValid() && "block has no address!");
  609. // Compute the initial on-stack block flags.
  610. BlockFlags flags = BLOCK_HAS_SIGNATURE;
  611. if (blockInfo.HasCapturedVariableLayout) flags |= BLOCK_HAS_EXTENDED_LAYOUT;
  612. if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
  613. if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
  614. if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
  615. auto projectField =
  616. [&](unsigned index, CharUnits offset, const Twine &name) -> Address {
  617. return Builder.CreateStructGEP(blockAddr, index, offset, name);
  618. };
  619. auto storeField =
  620. [&](llvm::Value *value, unsigned index, CharUnits offset,
  621. const Twine &name) {
  622. Builder.CreateStore(value, projectField(index, offset, name));
  623. };
  624. // Initialize the block header.
  625. {
  626. // We assume all the header fields are densely packed.
  627. unsigned index = 0;
  628. CharUnits offset;
  629. auto addHeaderField =
  630. [&](llvm::Value *value, CharUnits size, const Twine &name) {
  631. storeField(value, index, offset, name);
  632. offset += size;
  633. index++;
  634. };
  635. addHeaderField(isa, getPointerSize(), "block.isa");
  636. addHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
  637. getIntSize(), "block.flags");
  638. addHeaderField(llvm::ConstantInt::get(IntTy, 0),
  639. getIntSize(), "block.reserved");
  640. addHeaderField(blockFn, getPointerSize(), "block.invoke");
  641. addHeaderField(descriptor, getPointerSize(), "block.descriptor");
  642. }
  643. // Finally, capture all the values into the block.
  644. const BlockDecl *blockDecl = blockInfo.getBlockDecl();
  645. // First, 'this'.
  646. if (blockDecl->capturesCXXThis()) {
  647. Address addr = projectField(blockInfo.CXXThisIndex, blockInfo.CXXThisOffset,
  648. "block.captured-this.addr");
  649. Builder.CreateStore(LoadCXXThis(), addr);
  650. }
  651. // Next, captured variables.
  652. for (const auto &CI : blockDecl->captures()) {
  653. const VarDecl *variable = CI.getVariable();
  654. const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
  655. // Ignore constant captures.
  656. if (capture.isConstant()) continue;
  657. QualType type = capture.fieldType();
  658. // This will be a [[type]]*, except that a byref entry will just be
  659. // an i8**.
  660. Address blockField =
  661. projectField(capture.getIndex(), capture.getOffset(), "block.captured");
  662. // Compute the address of the thing we're going to move into the
  663. // block literal.
  664. Address src = Address::invalid();
  665. if (blockDecl->isConversionFromLambda()) {
  666. // The lambda capture in a lambda's conversion-to-block-pointer is
  667. // special; we'll simply emit it directly.
  668. src = Address::invalid();
  669. } else if (CI.isByRef()) {
  670. if (BlockInfo && CI.isNested()) {
  671. // We need to use the capture from the enclosing block.
  672. const CGBlockInfo::Capture &enclosingCapture =
  673. BlockInfo->getCapture(variable);
  674. // This is a [[type]]*, except that a byref entry wil just be an i8**.
  675. src = Builder.CreateStructGEP(LoadBlockStruct(),
  676. enclosingCapture.getIndex(),
  677. enclosingCapture.getOffset(),
  678. "block.capture.addr");
  679. } else {
  680. auto I = LocalDeclMap.find(variable);
  681. assert(I != LocalDeclMap.end());
  682. src = I->second;
  683. }
  684. } else {
  685. DeclRefExpr declRef(const_cast<VarDecl *>(variable),
  686. /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
  687. type.getNonReferenceType(), VK_LValue,
  688. SourceLocation());
  689. src = EmitDeclRefLValue(&declRef).getAddress();
  690. };
  691. // For byrefs, we just write the pointer to the byref struct into
  692. // the block field. There's no need to chase the forwarding
  693. // pointer at this point, since we're building something that will
  694. // live a shorter life than the stack byref anyway.
  695. if (CI.isByRef()) {
  696. // Get a void* that points to the byref struct.
  697. llvm::Value *byrefPointer;
  698. if (CI.isNested())
  699. byrefPointer = Builder.CreateLoad(src, "byref.capture");
  700. else
  701. byrefPointer = Builder.CreateBitCast(src.getPointer(), VoidPtrTy);
  702. // Write that void* into the capture field.
  703. Builder.CreateStore(byrefPointer, blockField);
  704. // If we have a copy constructor, evaluate that into the block field.
  705. } else if (const Expr *copyExpr = CI.getCopyExpr()) {
  706. if (blockDecl->isConversionFromLambda()) {
  707. // If we have a lambda conversion, emit the expression
  708. // directly into the block instead.
  709. AggValueSlot Slot =
  710. AggValueSlot::forAddr(blockField, Qualifiers(),
  711. AggValueSlot::IsDestructed,
  712. AggValueSlot::DoesNotNeedGCBarriers,
  713. AggValueSlot::IsNotAliased);
  714. EmitAggExpr(copyExpr, Slot);
  715. } else {
  716. EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
  717. }
  718. // If it's a reference variable, copy the reference into the block field.
  719. } else if (type->isReferenceType()) {
  720. Builder.CreateStore(src.getPointer(), blockField);
  721. // If this is an ARC __strong block-pointer variable, don't do a
  722. // block copy.
  723. //
  724. // TODO: this can be generalized into the normal initialization logic:
  725. // we should never need to do a block-copy when initializing a local
  726. // variable, because the local variable's lifetime should be strictly
  727. // contained within the stack block's.
  728. } else if (type.getObjCLifetime() == Qualifiers::OCL_Strong &&
  729. type->isBlockPointerType()) {
  730. // Load the block and do a simple retain.
  731. llvm::Value *value = Builder.CreateLoad(src, "block.captured_block");
  732. value = EmitARCRetainNonBlock(value);
  733. // Do a primitive store to the block field.
  734. Builder.CreateStore(value, blockField);
  735. // Otherwise, fake up a POD copy into the block field.
  736. } else {
  737. // Fake up a new variable so that EmitScalarInit doesn't think
  738. // we're referring to the variable in its own initializer.
  739. ImplicitParamDecl blockFieldPseudoVar(getContext(), /*DC*/ nullptr,
  740. SourceLocation(), /*name*/ nullptr,
  741. type);
  742. // We use one of these or the other depending on whether the
  743. // reference is nested.
  744. DeclRefExpr declRef(const_cast<VarDecl *>(variable),
  745. /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
  746. type, VK_LValue, SourceLocation());
  747. ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
  748. &declRef, VK_RValue);
  749. // FIXME: Pass a specific location for the expr init so that the store is
  750. // attributed to a reasonable location - otherwise it may be attributed to
  751. // locations of subexpressions in the initialization.
  752. EmitExprAsInit(&l2r, &blockFieldPseudoVar,
  753. MakeAddrLValue(blockField, type, AlignmentSource::Decl),
  754. /*captured by init*/ false);
  755. }
  756. // Activate the cleanup if layout pushed one.
  757. if (!CI.isByRef()) {
  758. EHScopeStack::stable_iterator cleanup = capture.getCleanup();
  759. if (cleanup.isValid())
  760. ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
  761. }
  762. }
  763. // Cast to the converted block-pointer type, which happens (somewhat
  764. // unfortunately) to be a pointer to function type.
  765. llvm::Value *result =
  766. Builder.CreateBitCast(blockAddr.getPointer(),
  767. ConvertType(blockInfo.getBlockExpr()->getType()));
  768. return result;
  769. }
  770. llvm::Type *CodeGenModule::getBlockDescriptorType() {
  771. if (BlockDescriptorType)
  772. return BlockDescriptorType;
  773. llvm::Type *UnsignedLongTy =
  774. getTypes().ConvertType(getContext().UnsignedLongTy);
  775. // struct __block_descriptor {
  776. // unsigned long reserved;
  777. // unsigned long block_size;
  778. //
  779. // // later, the following will be added
  780. //
  781. // struct {
  782. // void (*copyHelper)();
  783. // void (*copyHelper)();
  784. // } helpers; // !!! optional
  785. //
  786. // const char *signature; // the block signature
  787. // const char *layout; // reserved
  788. // };
  789. BlockDescriptorType =
  790. llvm::StructType::create("struct.__block_descriptor",
  791. UnsignedLongTy, UnsignedLongTy, nullptr);
  792. // Now form a pointer to that.
  793. unsigned AddrSpace = 0;
  794. if (getLangOpts().OpenCL)
  795. AddrSpace = getContext().getTargetAddressSpace(LangAS::opencl_constant);
  796. BlockDescriptorType = llvm::PointerType::get(BlockDescriptorType, AddrSpace);
  797. return BlockDescriptorType;
  798. }
  799. llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
  800. if (GenericBlockLiteralType)
  801. return GenericBlockLiteralType;
  802. llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
  803. // struct __block_literal_generic {
  804. // void *__isa;
  805. // int __flags;
  806. // int __reserved;
  807. // void (*__invoke)(void *);
  808. // struct __block_descriptor *__descriptor;
  809. // };
  810. GenericBlockLiteralType =
  811. llvm::StructType::create("struct.__block_literal_generic",
  812. VoidPtrTy, IntTy, IntTy, VoidPtrTy,
  813. BlockDescPtrTy, nullptr);
  814. return GenericBlockLiteralType;
  815. }
  816. RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr *E,
  817. ReturnValueSlot ReturnValue) {
  818. const BlockPointerType *BPT =
  819. E->getCallee()->getType()->getAs<BlockPointerType>();
  820. llvm::Value *BlockPtr = EmitScalarExpr(E->getCallee());
  821. // Get a pointer to the generic block literal.
  822. llvm::Type *BlockLiteralTy =
  823. llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
  824. // Bitcast the callee to a block literal.
  825. BlockPtr = Builder.CreateBitCast(BlockPtr, BlockLiteralTy, "block.literal");
  826. // Get the function pointer from the literal.
  827. llvm::Value *FuncPtr =
  828. Builder.CreateStructGEP(CGM.getGenericBlockLiteralType(), BlockPtr, 3);
  829. BlockPtr = Builder.CreateBitCast(BlockPtr, VoidPtrTy);
  830. // Add the block literal.
  831. CallArgList Args;
  832. Args.add(RValue::get(BlockPtr), getContext().VoidPtrTy);
  833. QualType FnType = BPT->getPointeeType();
  834. // And the rest of the arguments.
  835. EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), E->arguments());
  836. // Load the function.
  837. llvm::Value *Func = Builder.CreateAlignedLoad(FuncPtr, getPointerAlign());
  838. const FunctionType *FuncTy = FnType->castAs<FunctionType>();
  839. const CGFunctionInfo &FnInfo =
  840. CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
  841. // Cast the function pointer to the right type.
  842. llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
  843. llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
  844. Func = Builder.CreateBitCast(Func, BlockFTyPtr);
  845. // Prepare the callee.
  846. CGCallee Callee(CGCalleeInfo(), Func);
  847. // And call the block.
  848. return EmitCall(FnInfo, Callee, ReturnValue, Args);
  849. }
  850. Address CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
  851. bool isByRef) {
  852. assert(BlockInfo && "evaluating block ref without block information?");
  853. const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
  854. // Handle constant captures.
  855. if (capture.isConstant()) return LocalDeclMap.find(variable)->second;
  856. Address addr =
  857. Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
  858. capture.getOffset(), "block.capture.addr");
  859. if (isByRef) {
  860. // addr should be a void** right now. Load, then cast the result
  861. // to byref*.
  862. auto &byrefInfo = getBlockByrefInfo(variable);
  863. addr = Address(Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
  864. auto byrefPointerType = llvm::PointerType::get(byrefInfo.Type, 0);
  865. addr = Builder.CreateBitCast(addr, byrefPointerType, "byref.addr");
  866. addr = emitBlockByrefAddress(addr, byrefInfo, /*follow*/ true,
  867. variable->getName());
  868. }
  869. if (auto refType = capture.fieldType()->getAs<ReferenceType>())
  870. addr = EmitLoadOfReference(addr, refType);
  871. return addr;
  872. }
  873. llvm::Constant *
  874. CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *BE,
  875. StringRef Name) {
  876. CGBlockInfo blockInfo(BE->getBlockDecl(), Name);
  877. blockInfo.BlockExpression = BE;
  878. // Compute information about the layout, etc., of this block.
  879. computeBlockInfo(*this, nullptr, blockInfo);
  880. // Using that metadata, generate the actual block function.
  881. llvm::Constant *blockFn;
  882. {
  883. CodeGenFunction::DeclMapTy LocalDeclMap;
  884. blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
  885. blockInfo,
  886. LocalDeclMap,
  887. false);
  888. }
  889. blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
  890. return buildGlobalBlock(*this, blockInfo, blockFn);
  891. }
  892. static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
  893. const CGBlockInfo &blockInfo,
  894. llvm::Constant *blockFn) {
  895. assert(blockInfo.CanBeGlobal);
  896. // Generate the constants for the block literal initializer.
  897. ConstantInitBuilder builder(CGM);
  898. auto fields = builder.beginStruct();
  899. // isa
  900. fields.add(CGM.getNSConcreteGlobalBlock());
  901. // __flags
  902. BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
  903. if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
  904. fields.addInt(CGM.IntTy, flags.getBitMask());
  905. // Reserved
  906. fields.addInt(CGM.IntTy, 0);
  907. // Function
  908. fields.add(blockFn);
  909. // Descriptor
  910. fields.add(buildBlockDescriptor(CGM, blockInfo));
  911. llvm::Constant *literal =
  912. fields.finishAndCreateGlobal("__block_literal_global",
  913. blockInfo.BlockAlign,
  914. /*constant*/ true);
  915. // Return a constant of the appropriately-casted type.
  916. llvm::Type *requiredType =
  917. CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
  918. return llvm::ConstantExpr::getBitCast(literal, requiredType);
  919. }
  920. void CodeGenFunction::setBlockContextParameter(const ImplicitParamDecl *D,
  921. unsigned argNum,
  922. llvm::Value *arg) {
  923. assert(BlockInfo && "not emitting prologue of block invocation function?!");
  924. llvm::Value *localAddr = nullptr;
  925. if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
  926. // Allocate a stack slot to let the debug info survive the RA.
  927. Address alloc = CreateMemTemp(D->getType(), D->getName() + ".addr");
  928. Builder.CreateStore(arg, alloc);
  929. localAddr = Builder.CreateLoad(alloc);
  930. }
  931. if (CGDebugInfo *DI = getDebugInfo()) {
  932. if (CGM.getCodeGenOpts().getDebugInfo() >=
  933. codegenoptions::LimitedDebugInfo) {
  934. DI->setLocation(D->getLocation());
  935. DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, arg, argNum,
  936. localAddr, Builder);
  937. }
  938. }
  939. SourceLocation StartLoc = BlockInfo->getBlockExpr()->getBody()->getLocStart();
  940. ApplyDebugLocation Scope(*this, StartLoc);
  941. // Instead of messing around with LocalDeclMap, just set the value
  942. // directly as BlockPointer.
  943. BlockPointer = Builder.CreateBitCast(arg,
  944. BlockInfo->StructureType->getPointerTo(),
  945. "block");
  946. }
  947. Address CodeGenFunction::LoadBlockStruct() {
  948. assert(BlockInfo && "not in a block invocation function!");
  949. assert(BlockPointer && "no block pointer set!");
  950. return Address(BlockPointer, BlockInfo->BlockAlign);
  951. }
  952. llvm::Function *
  953. CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
  954. const CGBlockInfo &blockInfo,
  955. const DeclMapTy &ldm,
  956. bool IsLambdaConversionToBlock) {
  957. const BlockDecl *blockDecl = blockInfo.getBlockDecl();
  958. CurGD = GD;
  959. CurEHLocation = blockInfo.getBlockExpr()->getLocEnd();
  960. BlockInfo = &blockInfo;
  961. // Arrange for local static and local extern declarations to appear
  962. // to be local to this function as well, in case they're directly
  963. // referenced in a block.
  964. for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
  965. const auto *var = dyn_cast<VarDecl>(i->first);
  966. if (var && !var->hasLocalStorage())
  967. setAddrOfLocalVar(var, i->second);
  968. }
  969. // Begin building the function declaration.
  970. // Build the argument list.
  971. FunctionArgList args;
  972. // The first argument is the block pointer. Just take it as a void*
  973. // and cast it later.
  974. QualType selfTy = getContext().VoidPtrTy;
  975. IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
  976. ImplicitParamDecl selfDecl(getContext(), const_cast<BlockDecl*>(blockDecl),
  977. SourceLocation(), II, selfTy);
  978. args.push_back(&selfDecl);
  979. // Now add the rest of the parameters.
  980. args.append(blockDecl->param_begin(), blockDecl->param_end());
  981. // Create the function declaration.
  982. const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
  983. const CGFunctionInfo &fnInfo =
  984. CGM.getTypes().arrangeBlockFunctionDeclaration(fnType, args);
  985. if (CGM.ReturnSlotInterferesWithArgs(fnInfo))
  986. blockInfo.UsesStret = true;
  987. llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
  988. StringRef name = CGM.getBlockMangledName(GD, blockDecl);
  989. llvm::Function *fn = llvm::Function::Create(
  990. fnLLVMType, llvm::GlobalValue::InternalLinkage, name, &CGM.getModule());
  991. CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
  992. // Begin generating the function.
  993. StartFunction(blockDecl, fnType->getReturnType(), fn, fnInfo, args,
  994. blockDecl->getLocation(),
  995. blockInfo.getBlockExpr()->getBody()->getLocStart());
  996. // Okay. Undo some of what StartFunction did.
  997. // At -O0 we generate an explicit alloca for the BlockPointer, so the RA
  998. // won't delete the dbg.declare intrinsics for captured variables.
  999. llvm::Value *BlockPointerDbgLoc = BlockPointer;
  1000. if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
  1001. // Allocate a stack slot for it, so we can point the debugger to it
  1002. Address Alloca = CreateTempAlloca(BlockPointer->getType(),
  1003. getPointerAlign(),
  1004. "block.addr");
  1005. // Set the DebugLocation to empty, so the store is recognized as a
  1006. // frame setup instruction by llvm::DwarfDebug::beginFunction().
  1007. auto NL = ApplyDebugLocation::CreateEmpty(*this);
  1008. Builder.CreateStore(BlockPointer, Alloca);
  1009. BlockPointerDbgLoc = Alloca.getPointer();
  1010. }
  1011. // If we have a C++ 'this' reference, go ahead and force it into
  1012. // existence now.
  1013. if (blockDecl->capturesCXXThis()) {
  1014. Address addr =
  1015. Builder.CreateStructGEP(LoadBlockStruct(), blockInfo.CXXThisIndex,
  1016. blockInfo.CXXThisOffset, "block.captured-this");
  1017. CXXThisValue = Builder.CreateLoad(addr, "this");
  1018. }
  1019. // Also force all the constant captures.
  1020. for (const auto &CI : blockDecl->captures()) {
  1021. const VarDecl *variable = CI.getVariable();
  1022. const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
  1023. if (!capture.isConstant()) continue;
  1024. CharUnits align = getContext().getDeclAlign(variable);
  1025. Address alloca =
  1026. CreateMemTemp(variable->getType(), align, "block.captured-const");
  1027. Builder.CreateStore(capture.getConstant(), alloca);
  1028. setAddrOfLocalVar(variable, alloca);
  1029. }
  1030. // Save a spot to insert the debug information for all the DeclRefExprs.
  1031. llvm::BasicBlock *entry = Builder.GetInsertBlock();
  1032. llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
  1033. --entry_ptr;
  1034. if (IsLambdaConversionToBlock)
  1035. EmitLambdaBlockInvokeBody();
  1036. else {
  1037. PGO.assignRegionCounters(GlobalDecl(blockDecl), fn);
  1038. incrementProfileCounter(blockDecl->getBody());
  1039. EmitStmt(blockDecl->getBody());
  1040. }
  1041. // Remember where we were...
  1042. llvm::BasicBlock *resume = Builder.GetInsertBlock();
  1043. // Go back to the entry.
  1044. ++entry_ptr;
  1045. Builder.SetInsertPoint(entry, entry_ptr);
  1046. // Emit debug information for all the DeclRefExprs.
  1047. // FIXME: also for 'this'
  1048. if (CGDebugInfo *DI = getDebugInfo()) {
  1049. for (const auto &CI : blockDecl->captures()) {
  1050. const VarDecl *variable = CI.getVariable();
  1051. DI->EmitLocation(Builder, variable->getLocation());
  1052. if (CGM.getCodeGenOpts().getDebugInfo() >=
  1053. codegenoptions::LimitedDebugInfo) {
  1054. const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
  1055. if (capture.isConstant()) {
  1056. auto addr = LocalDeclMap.find(variable)->second;
  1057. DI->EmitDeclareOfAutoVariable(variable, addr.getPointer(),
  1058. Builder);
  1059. continue;
  1060. }
  1061. DI->EmitDeclareOfBlockDeclRefVariable(
  1062. variable, BlockPointerDbgLoc, Builder, blockInfo,
  1063. entry_ptr == entry->end() ? nullptr : &*entry_ptr);
  1064. }
  1065. }
  1066. // Recover location if it was changed in the above loop.
  1067. DI->EmitLocation(Builder,
  1068. cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
  1069. }
  1070. // And resume where we left off.
  1071. if (resume == nullptr)
  1072. Builder.ClearInsertionPoint();
  1073. else
  1074. Builder.SetInsertPoint(resume);
  1075. FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
  1076. return fn;
  1077. }
  1078. /*
  1079. notes.push_back(HelperInfo());
  1080. HelperInfo &note = notes.back();
  1081. note.index = capture.getIndex();
  1082. note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
  1083. note.cxxbar_import = ci->getCopyExpr();
  1084. if (ci->isByRef()) {
  1085. note.flag = BLOCK_FIELD_IS_BYREF;
  1086. if (type.isObjCGCWeak())
  1087. note.flag |= BLOCK_FIELD_IS_WEAK;
  1088. } else if (type->isBlockPointerType()) {
  1089. note.flag = BLOCK_FIELD_IS_BLOCK;
  1090. } else {
  1091. note.flag = BLOCK_FIELD_IS_OBJECT;
  1092. }
  1093. */
  1094. /// Generate the copy-helper function for a block closure object:
  1095. /// static void block_copy_helper(block_t *dst, block_t *src);
  1096. /// The runtime will have previously initialized 'dst' by doing a
  1097. /// bit-copy of 'src'.
  1098. ///
  1099. /// Note that this copies an entire block closure object to the heap;
  1100. /// it should not be confused with a 'byref copy helper', which moves
  1101. /// the contents of an individual __block variable to the heap.
  1102. llvm::Constant *
  1103. CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
  1104. ASTContext &C = getContext();
  1105. FunctionArgList args;
  1106. ImplicitParamDecl dstDecl(getContext(), nullptr, SourceLocation(), nullptr,
  1107. C.VoidPtrTy);
  1108. args.push_back(&dstDecl);
  1109. ImplicitParamDecl srcDecl(getContext(), nullptr, SourceLocation(), nullptr,
  1110. C.VoidPtrTy);
  1111. args.push_back(&srcDecl);
  1112. const CGFunctionInfo &FI =
  1113. CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, args);
  1114. // FIXME: it would be nice if these were mergeable with things with
  1115. // identical semantics.
  1116. llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
  1117. llvm::Function *Fn =
  1118. llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
  1119. "__copy_helper_block_", &CGM.getModule());
  1120. IdentifierInfo *II
  1121. = &CGM.getContext().Idents.get("__copy_helper_block_");
  1122. FunctionDecl *FD = FunctionDecl::Create(C,
  1123. C.getTranslationUnitDecl(),
  1124. SourceLocation(),
  1125. SourceLocation(), II, C.VoidTy,
  1126. nullptr, SC_Static,
  1127. false,
  1128. false);
  1129. CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
  1130. auto NL = ApplyDebugLocation::CreateEmpty(*this);
  1131. StartFunction(FD, C.VoidTy, Fn, FI, args);
  1132. // Create a scope with an artificial location for the body of this function.
  1133. auto AL = ApplyDebugLocation::CreateArtificial(*this);
  1134. llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
  1135. Address src = GetAddrOfLocalVar(&srcDecl);
  1136. src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
  1137. src = Builder.CreateBitCast(src, structPtrTy, "block.source");
  1138. Address dst = GetAddrOfLocalVar(&dstDecl);
  1139. dst = Address(Builder.CreateLoad(dst), blockInfo.BlockAlign);
  1140. dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
  1141. const BlockDecl *blockDecl = blockInfo.getBlockDecl();
  1142. for (const auto &CI : blockDecl->captures()) {
  1143. const VarDecl *variable = CI.getVariable();
  1144. QualType type = variable->getType();
  1145. const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
  1146. if (capture.isConstant()) continue;
  1147. const Expr *copyExpr = CI.getCopyExpr();
  1148. BlockFieldFlags flags;
  1149. bool useARCWeakCopy = false;
  1150. bool useARCStrongCopy = false;
  1151. if (copyExpr) {
  1152. assert(!CI.isByRef());
  1153. // don't bother computing flags
  1154. } else if (CI.isByRef()) {
  1155. flags = BLOCK_FIELD_IS_BYREF;
  1156. if (type.isObjCGCWeak())
  1157. flags |= BLOCK_FIELD_IS_WEAK;
  1158. } else if (type->isObjCRetainableType()) {
  1159. flags = BLOCK_FIELD_IS_OBJECT;
  1160. bool isBlockPointer = type->isBlockPointerType();
  1161. if (isBlockPointer)
  1162. flags = BLOCK_FIELD_IS_BLOCK;
  1163. // Special rules for ARC captures:
  1164. Qualifiers qs = type.getQualifiers();
  1165. // We need to register __weak direct captures with the runtime.
  1166. if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
  1167. useARCWeakCopy = true;
  1168. // We need to retain the copied value for __strong direct captures.
  1169. } else if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
  1170. // If it's a block pointer, we have to copy the block and
  1171. // assign that to the destination pointer, so we might as
  1172. // well use _Block_object_assign. Otherwise we can avoid that.
  1173. if (!isBlockPointer)
  1174. useARCStrongCopy = true;
  1175. // Non-ARC captures of retainable pointers are strong and
  1176. // therefore require a call to _Block_object_assign.
  1177. } else if (!qs.getObjCLifetime() && !getLangOpts().ObjCAutoRefCount) {
  1178. // fall through
  1179. // Otherwise the memcpy is fine.
  1180. } else {
  1181. continue;
  1182. }
  1183. // For all other types, the memcpy is fine.
  1184. } else {
  1185. continue;
  1186. }
  1187. unsigned index = capture.getIndex();
  1188. Address srcField = Builder.CreateStructGEP(src, index, capture.getOffset());
  1189. Address dstField = Builder.CreateStructGEP(dst, index, capture.getOffset());
  1190. // If there's an explicit copy expression, we do that.
  1191. if (copyExpr) {
  1192. EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
  1193. } else if (useARCWeakCopy) {
  1194. EmitARCCopyWeak(dstField, srcField);
  1195. } else {
  1196. llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
  1197. if (useARCStrongCopy) {
  1198. // At -O0, store null into the destination field (so that the
  1199. // storeStrong doesn't over-release) and then call storeStrong.
  1200. // This is a workaround to not having an initStrong call.
  1201. if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
  1202. auto *ty = cast<llvm::PointerType>(srcValue->getType());
  1203. llvm::Value *null = llvm::ConstantPointerNull::get(ty);
  1204. Builder.CreateStore(null, dstField);
  1205. EmitARCStoreStrongCall(dstField, srcValue, true);
  1206. // With optimization enabled, take advantage of the fact that
  1207. // the blocks runtime guarantees a memcpy of the block data, and
  1208. // just emit a retain of the src field.
  1209. } else {
  1210. EmitARCRetainNonBlock(srcValue);
  1211. // We don't need this anymore, so kill it. It's not quite
  1212. // worth the annoyance to avoid creating it in the first place.
  1213. cast<llvm::Instruction>(dstField.getPointer())->eraseFromParent();
  1214. }
  1215. } else {
  1216. srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
  1217. llvm::Value *dstAddr =
  1218. Builder.CreateBitCast(dstField.getPointer(), VoidPtrTy);
  1219. llvm::Value *args[] = {
  1220. dstAddr, srcValue, llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
  1221. };
  1222. bool copyCanThrow = false;
  1223. if (CI.isByRef() && variable->getType()->getAsCXXRecordDecl()) {
  1224. const Expr *copyExpr =
  1225. CGM.getContext().getBlockVarCopyInits(variable);
  1226. if (copyExpr) {
  1227. copyCanThrow = true; // FIXME: reuse the noexcept logic
  1228. }
  1229. }
  1230. if (copyCanThrow) {
  1231. EmitRuntimeCallOrInvoke(CGM.getBlockObjectAssign(), args);
  1232. } else {
  1233. EmitNounwindRuntimeCall(CGM.getBlockObjectAssign(), args);
  1234. }
  1235. }
  1236. }
  1237. }
  1238. FinishFunction();
  1239. return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
  1240. }
  1241. /// Generate the destroy-helper function for a block closure object:
  1242. /// static void block_destroy_helper(block_t *theBlock);
  1243. ///
  1244. /// Note that this destroys a heap-allocated block closure object;
  1245. /// it should not be confused with a 'byref destroy helper', which
  1246. /// destroys the heap-allocated contents of an individual __block
  1247. /// variable.
  1248. llvm::Constant *
  1249. CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
  1250. ASTContext &C = getContext();
  1251. FunctionArgList args;
  1252. ImplicitParamDecl srcDecl(getContext(), nullptr, SourceLocation(), nullptr,
  1253. C.VoidPtrTy);
  1254. args.push_back(&srcDecl);
  1255. const CGFunctionInfo &FI =
  1256. CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, args);
  1257. // FIXME: We'd like to put these into a mergable by content, with
  1258. // internal linkage.
  1259. llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
  1260. llvm::Function *Fn =
  1261. llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
  1262. "__destroy_helper_block_", &CGM.getModule());
  1263. IdentifierInfo *II
  1264. = &CGM.getContext().Idents.get("__destroy_helper_block_");
  1265. FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
  1266. SourceLocation(),
  1267. SourceLocation(), II, C.VoidTy,
  1268. nullptr, SC_Static,
  1269. false, false);
  1270. CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
  1271. // Create a scope with an artificial location for the body of this function.
  1272. auto NL = ApplyDebugLocation::CreateEmpty(*this);
  1273. StartFunction(FD, C.VoidTy, Fn, FI, args);
  1274. auto AL = ApplyDebugLocation::CreateArtificial(*this);
  1275. llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
  1276. Address src = GetAddrOfLocalVar(&srcDecl);
  1277. src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
  1278. src = Builder.CreateBitCast(src, structPtrTy, "block");
  1279. const BlockDecl *blockDecl = blockInfo.getBlockDecl();
  1280. CodeGenFunction::RunCleanupsScope cleanups(*this);
  1281. for (const auto &CI : blockDecl->captures()) {
  1282. const VarDecl *variable = CI.getVariable();
  1283. QualType type = variable->getType();
  1284. const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
  1285. if (capture.isConstant()) continue;
  1286. BlockFieldFlags flags;
  1287. const CXXDestructorDecl *dtor = nullptr;
  1288. bool useARCWeakDestroy = false;
  1289. bool useARCStrongDestroy = false;
  1290. if (CI.isByRef()) {
  1291. flags = BLOCK_FIELD_IS_BYREF;
  1292. if (type.isObjCGCWeak())
  1293. flags |= BLOCK_FIELD_IS_WEAK;
  1294. } else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
  1295. if (record->hasTrivialDestructor())
  1296. continue;
  1297. dtor = record->getDestructor();
  1298. } else if (type->isObjCRetainableType()) {
  1299. flags = BLOCK_FIELD_IS_OBJECT;
  1300. if (type->isBlockPointerType())
  1301. flags = BLOCK_FIELD_IS_BLOCK;
  1302. // Special rules for ARC captures.
  1303. Qualifiers qs = type.getQualifiers();
  1304. // Use objc_storeStrong for __strong direct captures; the
  1305. // dynamic tools really like it when we do this.
  1306. if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
  1307. useARCStrongDestroy = true;
  1308. // Support __weak direct captures.
  1309. } else if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
  1310. useARCWeakDestroy = true;
  1311. // Non-ARC captures are strong, and we need to use _Block_object_dispose.
  1312. } else if (!qs.hasObjCLifetime() && !getLangOpts().ObjCAutoRefCount) {
  1313. // fall through
  1314. // Otherwise, we have nothing to do.
  1315. } else {
  1316. continue;
  1317. }
  1318. } else {
  1319. continue;
  1320. }
  1321. Address srcField =
  1322. Builder.CreateStructGEP(src, capture.getIndex(), capture.getOffset());
  1323. // If there's an explicit copy expression, we do that.
  1324. if (dtor) {
  1325. PushDestructorCleanup(dtor, srcField);
  1326. // If this is a __weak capture, emit the release directly.
  1327. } else if (useARCWeakDestroy) {
  1328. EmitARCDestroyWeak(srcField);
  1329. // Destroy strong objects with a call if requested.
  1330. } else if (useARCStrongDestroy) {
  1331. EmitARCDestroyStrong(srcField, ARCImpreciseLifetime);
  1332. // Otherwise we call _Block_object_dispose. It wouldn't be too
  1333. // hard to just emit this as a cleanup if we wanted to make sure
  1334. // that things were done in reverse.
  1335. } else {
  1336. llvm::Value *value = Builder.CreateLoad(srcField);
  1337. value = Builder.CreateBitCast(value, VoidPtrTy);
  1338. BuildBlockRelease(value, flags);
  1339. }
  1340. }
  1341. cleanups.ForceCleanup();
  1342. FinishFunction();
  1343. return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
  1344. }
  1345. namespace {
  1346. /// Emits the copy/dispose helper functions for a __block object of id type.
  1347. class ObjectByrefHelpers final : public BlockByrefHelpers {
  1348. BlockFieldFlags Flags;
  1349. public:
  1350. ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
  1351. : BlockByrefHelpers(alignment), Flags(flags) {}
  1352. void emitCopy(CodeGenFunction &CGF, Address destField,
  1353. Address srcField) override {
  1354. destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
  1355. srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
  1356. llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
  1357. unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
  1358. llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
  1359. llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
  1360. llvm::Value *args[] = { destField.getPointer(), srcValue, flagsVal };
  1361. CGF.EmitNounwindRuntimeCall(fn, args);
  1362. }
  1363. void emitDispose(CodeGenFunction &CGF, Address field) override {
  1364. field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
  1365. llvm::Value *value = CGF.Builder.CreateLoad(field);
  1366. CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
  1367. }
  1368. void profileImpl(llvm::FoldingSetNodeID &id) const override {
  1369. id.AddInteger(Flags.getBitMask());
  1370. }
  1371. };
  1372. /// Emits the copy/dispose helpers for an ARC __block __weak variable.
  1373. class ARCWeakByrefHelpers final : public BlockByrefHelpers {
  1374. public:
  1375. ARCWeakByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
  1376. void emitCopy(CodeGenFunction &CGF, Address destField,
  1377. Address srcField) override {
  1378. CGF.EmitARCMoveWeak(destField, srcField);
  1379. }
  1380. void emitDispose(CodeGenFunction &CGF, Address field) override {
  1381. CGF.EmitARCDestroyWeak(field);
  1382. }
  1383. void profileImpl(llvm::FoldingSetNodeID &id) const override {
  1384. // 0 is distinguishable from all pointers and byref flags
  1385. id.AddInteger(0);
  1386. }
  1387. };
  1388. /// Emits the copy/dispose helpers for an ARC __block __strong variable
  1389. /// that's not of block-pointer type.
  1390. class ARCStrongByrefHelpers final : public BlockByrefHelpers {
  1391. public:
  1392. ARCStrongByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
  1393. void emitCopy(CodeGenFunction &CGF, Address destField,
  1394. Address srcField) override {
  1395. // Do a "move" by copying the value and then zeroing out the old
  1396. // variable.
  1397. llvm::Value *value = CGF.Builder.CreateLoad(srcField);
  1398. llvm::Value *null =
  1399. llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
  1400. if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
  1401. CGF.Builder.CreateStore(null, destField);
  1402. CGF.EmitARCStoreStrongCall(destField, value, /*ignored*/ true);
  1403. CGF.EmitARCStoreStrongCall(srcField, null, /*ignored*/ true);
  1404. return;
  1405. }
  1406. CGF.Builder.CreateStore(value, destField);
  1407. CGF.Builder.CreateStore(null, srcField);
  1408. }
  1409. void emitDispose(CodeGenFunction &CGF, Address field) override {
  1410. CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
  1411. }
  1412. void profileImpl(llvm::FoldingSetNodeID &id) const override {
  1413. // 1 is distinguishable from all pointers and byref flags
  1414. id.AddInteger(1);
  1415. }
  1416. };
  1417. /// Emits the copy/dispose helpers for an ARC __block __strong
  1418. /// variable that's of block-pointer type.
  1419. class ARCStrongBlockByrefHelpers final : public BlockByrefHelpers {
  1420. public:
  1421. ARCStrongBlockByrefHelpers(CharUnits alignment)
  1422. : BlockByrefHelpers(alignment) {}
  1423. void emitCopy(CodeGenFunction &CGF, Address destField,
  1424. Address srcField) override {
  1425. // Do the copy with objc_retainBlock; that's all that
  1426. // _Block_object_assign would do anyway, and we'd have to pass the
  1427. // right arguments to make sure it doesn't get no-op'ed.
  1428. llvm::Value *oldValue = CGF.Builder.CreateLoad(srcField);
  1429. llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
  1430. CGF.Builder.CreateStore(copy, destField);
  1431. }
  1432. void emitDispose(CodeGenFunction &CGF, Address field) override {
  1433. CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
  1434. }
  1435. void profileImpl(llvm::FoldingSetNodeID &id) const override {
  1436. // 2 is distinguishable from all pointers and byref flags
  1437. id.AddInteger(2);
  1438. }
  1439. };
  1440. /// Emits the copy/dispose helpers for a __block variable with a
  1441. /// nontrivial copy constructor or destructor.
  1442. class CXXByrefHelpers final : public BlockByrefHelpers {
  1443. QualType VarType;
  1444. const Expr *CopyExpr;
  1445. public:
  1446. CXXByrefHelpers(CharUnits alignment, QualType type,
  1447. const Expr *copyExpr)
  1448. : BlockByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
  1449. bool needsCopy() const override { return CopyExpr != nullptr; }
  1450. void emitCopy(CodeGenFunction &CGF, Address destField,
  1451. Address srcField) override {
  1452. if (!CopyExpr) return;
  1453. CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
  1454. }
  1455. void emitDispose(CodeGenFunction &CGF, Address field) override {
  1456. EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
  1457. CGF.PushDestructorCleanup(VarType, field);
  1458. CGF.PopCleanupBlocks(cleanupDepth);
  1459. }
  1460. void profileImpl(llvm::FoldingSetNodeID &id) const override {
  1461. id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
  1462. }
  1463. };
  1464. } // end anonymous namespace
  1465. static llvm::Constant *
  1466. generateByrefCopyHelper(CodeGenFunction &CGF, const BlockByrefInfo &byrefInfo,
  1467. BlockByrefHelpers &generator) {
  1468. ASTContext &Context = CGF.getContext();
  1469. QualType R = Context.VoidTy;
  1470. FunctionArgList args;
  1471. ImplicitParamDecl dst(CGF.getContext(), nullptr, SourceLocation(), nullptr,
  1472. Context.VoidPtrTy);
  1473. args.push_back(&dst);
  1474. ImplicitParamDecl src(CGF.getContext(), nullptr, SourceLocation(), nullptr,
  1475. Context.VoidPtrTy);
  1476. args.push_back(&src);
  1477. const CGFunctionInfo &FI =
  1478. CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args);
  1479. llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
  1480. // FIXME: We'd like to put these into a mergable by content, with
  1481. // internal linkage.
  1482. llvm::Function *Fn =
  1483. llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
  1484. "__Block_byref_object_copy_", &CGF.CGM.getModule());
  1485. IdentifierInfo *II
  1486. = &Context.Idents.get("__Block_byref_object_copy_");
  1487. FunctionDecl *FD = FunctionDecl::Create(Context,
  1488. Context.getTranslationUnitDecl(),
  1489. SourceLocation(),
  1490. SourceLocation(), II, R, nullptr,
  1491. SC_Static,
  1492. false, false);
  1493. CGF.CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
  1494. CGF.StartFunction(FD, R, Fn, FI, args);
  1495. if (generator.needsCopy()) {
  1496. llvm::Type *byrefPtrType = byrefInfo.Type->getPointerTo(0);
  1497. // dst->x
  1498. Address destField = CGF.GetAddrOfLocalVar(&dst);
  1499. destField = Address(CGF.Builder.CreateLoad(destField),
  1500. byrefInfo.ByrefAlignment);
  1501. destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
  1502. destField = CGF.emitBlockByrefAddress(destField, byrefInfo, false,
  1503. "dest-object");
  1504. // src->x
  1505. Address srcField = CGF.GetAddrOfLocalVar(&src);
  1506. srcField = Address(CGF.Builder.CreateLoad(srcField),
  1507. byrefInfo.ByrefAlignment);
  1508. srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
  1509. srcField = CGF.emitBlockByrefAddress(srcField, byrefInfo, false,
  1510. "src-object");
  1511. generator.emitCopy(CGF, destField, srcField);
  1512. }
  1513. CGF.FinishFunction();
  1514. return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
  1515. }
  1516. /// Build the copy helper for a __block variable.
  1517. static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
  1518. const BlockByrefInfo &byrefInfo,
  1519. BlockByrefHelpers &generator) {
  1520. CodeGenFunction CGF(CGM);
  1521. return generateByrefCopyHelper(CGF, byrefInfo, generator);
  1522. }
  1523. /// Generate code for a __block variable's dispose helper.
  1524. static llvm::Constant *
  1525. generateByrefDisposeHelper(CodeGenFunction &CGF,
  1526. const BlockByrefInfo &byrefInfo,
  1527. BlockByrefHelpers &generator) {
  1528. ASTContext &Context = CGF.getContext();
  1529. QualType R = Context.VoidTy;
  1530. FunctionArgList args;
  1531. ImplicitParamDecl src(CGF.getContext(), nullptr, SourceLocation(), nullptr,
  1532. Context.VoidPtrTy);
  1533. args.push_back(&src);
  1534. const CGFunctionInfo &FI =
  1535. CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args);
  1536. llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
  1537. // FIXME: We'd like to put these into a mergable by content, with
  1538. // internal linkage.
  1539. llvm::Function *Fn =
  1540. llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
  1541. "__Block_byref_object_dispose_",
  1542. &CGF.CGM.getModule());
  1543. IdentifierInfo *II
  1544. = &Context.Idents.get("__Block_byref_object_dispose_");
  1545. FunctionDecl *FD = FunctionDecl::Create(Context,
  1546. Context.getTranslationUnitDecl(),
  1547. SourceLocation(),
  1548. SourceLocation(), II, R, nullptr,
  1549. SC_Static,
  1550. false, false);
  1551. CGF.CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
  1552. CGF.StartFunction(FD, R, Fn, FI, args);
  1553. if (generator.needsDispose()) {
  1554. Address addr = CGF.GetAddrOfLocalVar(&src);
  1555. addr = Address(CGF.Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
  1556. auto byrefPtrType = byrefInfo.Type->getPointerTo(0);
  1557. addr = CGF.Builder.CreateBitCast(addr, byrefPtrType);
  1558. addr = CGF.emitBlockByrefAddress(addr, byrefInfo, false, "object");
  1559. generator.emitDispose(CGF, addr);
  1560. }
  1561. CGF.FinishFunction();
  1562. return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
  1563. }
  1564. /// Build the dispose helper for a __block variable.
  1565. static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
  1566. const BlockByrefInfo &byrefInfo,
  1567. BlockByrefHelpers &generator) {
  1568. CodeGenFunction CGF(CGM);
  1569. return generateByrefDisposeHelper(CGF, byrefInfo, generator);
  1570. }
  1571. /// Lazily build the copy and dispose helpers for a __block variable
  1572. /// with the given information.
  1573. template <class T>
  1574. static T *buildByrefHelpers(CodeGenModule &CGM, const BlockByrefInfo &byrefInfo,
  1575. T &&generator) {
  1576. llvm::FoldingSetNodeID id;
  1577. generator.Profile(id);
  1578. void *insertPos;
  1579. BlockByrefHelpers *node
  1580. = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
  1581. if (node) return static_cast<T*>(node);
  1582. generator.CopyHelper = buildByrefCopyHelper(CGM, byrefInfo, generator);
  1583. generator.DisposeHelper = buildByrefDisposeHelper(CGM, byrefInfo, generator);
  1584. T *copy = new (CGM.getContext()) T(std::forward<T>(generator));
  1585. CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
  1586. return copy;
  1587. }
  1588. /// Build the copy and dispose helpers for the given __block variable
  1589. /// emission. Places the helpers in the global cache. Returns null
  1590. /// if no helpers are required.
  1591. BlockByrefHelpers *
  1592. CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
  1593. const AutoVarEmission &emission) {
  1594. const VarDecl &var = *emission.Variable;
  1595. QualType type = var.getType();
  1596. auto &byrefInfo = getBlockByrefInfo(&var);
  1597. // The alignment we care about for the purposes of uniquing byref
  1598. // helpers is the alignment of the actual byref value field.
  1599. CharUnits valueAlignment =
  1600. byrefInfo.ByrefAlignment.alignmentAtOffset(byrefInfo.FieldOffset);
  1601. if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
  1602. const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
  1603. if (!copyExpr && record->hasTrivialDestructor()) return nullptr;
  1604. return ::buildByrefHelpers(
  1605. CGM, byrefInfo, CXXByrefHelpers(valueAlignment, type, copyExpr));
  1606. }
  1607. // Otherwise, if we don't have a retainable type, there's nothing to do.
  1608. // that the runtime does extra copies.
  1609. if (!type->isObjCRetainableType()) return nullptr;
  1610. Qualifiers qs = type.getQualifiers();
  1611. // If we have lifetime, that dominates.
  1612. if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
  1613. switch (lifetime) {
  1614. case Qualifiers::OCL_None: llvm_unreachable("impossible");
  1615. // These are just bits as far as the runtime is concerned.
  1616. case Qualifiers::OCL_ExplicitNone:
  1617. case Qualifiers::OCL_Autoreleasing:
  1618. return nullptr;
  1619. // Tell the runtime that this is ARC __weak, called by the
  1620. // byref routines.
  1621. case Qualifiers::OCL_Weak:
  1622. return ::buildByrefHelpers(CGM, byrefInfo,
  1623. ARCWeakByrefHelpers(valueAlignment));
  1624. // ARC __strong __block variables need to be retained.
  1625. case Qualifiers::OCL_Strong:
  1626. // Block pointers need to be copied, and there's no direct
  1627. // transfer possible.
  1628. if (type->isBlockPointerType()) {
  1629. return ::buildByrefHelpers(CGM, byrefInfo,
  1630. ARCStrongBlockByrefHelpers(valueAlignment));
  1631. // Otherwise, we transfer ownership of the retain from the stack
  1632. // to the heap.
  1633. } else {
  1634. return ::buildByrefHelpers(CGM, byrefInfo,
  1635. ARCStrongByrefHelpers(valueAlignment));
  1636. }
  1637. }
  1638. llvm_unreachable("fell out of lifetime switch!");
  1639. }
  1640. BlockFieldFlags flags;
  1641. if (type->isBlockPointerType()) {
  1642. flags |= BLOCK_FIELD_IS_BLOCK;
  1643. } else if (CGM.getContext().isObjCNSObjectType(type) ||
  1644. type->isObjCObjectPointerType()) {
  1645. flags |= BLOCK_FIELD_IS_OBJECT;
  1646. } else {
  1647. return nullptr;
  1648. }
  1649. if (type.isObjCGCWeak())
  1650. flags |= BLOCK_FIELD_IS_WEAK;
  1651. return ::buildByrefHelpers(CGM, byrefInfo,
  1652. ObjectByrefHelpers(valueAlignment, flags));
  1653. }
  1654. Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
  1655. const VarDecl *var,
  1656. bool followForward) {
  1657. auto &info = getBlockByrefInfo(var);
  1658. return emitBlockByrefAddress(baseAddr, info, followForward, var->getName());
  1659. }
  1660. Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
  1661. const BlockByrefInfo &info,
  1662. bool followForward,
  1663. const llvm::Twine &name) {
  1664. // Chase the forwarding address if requested.
  1665. if (followForward) {
  1666. Address forwardingAddr =
  1667. Builder.CreateStructGEP(baseAddr, 1, getPointerSize(), "forwarding");
  1668. baseAddr = Address(Builder.CreateLoad(forwardingAddr), info.ByrefAlignment);
  1669. }
  1670. return Builder.CreateStructGEP(baseAddr, info.FieldIndex,
  1671. info.FieldOffset, name);
  1672. }
  1673. /// BuildByrefInfo - This routine changes a __block variable declared as T x
  1674. /// into:
  1675. ///
  1676. /// struct {
  1677. /// void *__isa;
  1678. /// void *__forwarding;
  1679. /// int32_t __flags;
  1680. /// int32_t __size;
  1681. /// void *__copy_helper; // only if needed
  1682. /// void *__destroy_helper; // only if needed
  1683. /// void *__byref_variable_layout;// only if needed
  1684. /// char padding[X]; // only if needed
  1685. /// T x;
  1686. /// } x
  1687. ///
  1688. const BlockByrefInfo &CodeGenFunction::getBlockByrefInfo(const VarDecl *D) {
  1689. auto it = BlockByrefInfos.find(D);
  1690. if (it != BlockByrefInfos.end())
  1691. return it->second;
  1692. llvm::StructType *byrefType =
  1693. llvm::StructType::create(getLLVMContext(),
  1694. "struct.__block_byref_" + D->getNameAsString());
  1695. QualType Ty = D->getType();
  1696. CharUnits size;
  1697. SmallVector<llvm::Type *, 8> types;
  1698. // void *__isa;
  1699. types.push_back(Int8PtrTy);
  1700. size += getPointerSize();
  1701. // void *__forwarding;
  1702. types.push_back(llvm::PointerType::getUnqual(byrefType));
  1703. size += getPointerSize();
  1704. // int32_t __flags;
  1705. types.push_back(Int32Ty);
  1706. size += CharUnits::fromQuantity(4);
  1707. // int32_t __size;
  1708. types.push_back(Int32Ty);
  1709. size += CharUnits::fromQuantity(4);
  1710. // Note that this must match *exactly* the logic in buildByrefHelpers.
  1711. bool hasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
  1712. if (hasCopyAndDispose) {
  1713. /// void *__copy_helper;
  1714. types.push_back(Int8PtrTy);
  1715. size += getPointerSize();
  1716. /// void *__destroy_helper;
  1717. types.push_back(Int8PtrTy);
  1718. size += getPointerSize();
  1719. }
  1720. bool HasByrefExtendedLayout = false;
  1721. Qualifiers::ObjCLifetime Lifetime;
  1722. if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
  1723. HasByrefExtendedLayout) {
  1724. /// void *__byref_variable_layout;
  1725. types.push_back(Int8PtrTy);
  1726. size += CharUnits::fromQuantity(PointerSizeInBytes);
  1727. }
  1728. // T x;
  1729. llvm::Type *varTy = ConvertTypeForMem(Ty);
  1730. bool packed = false;
  1731. CharUnits varAlign = getContext().getDeclAlign(D);
  1732. CharUnits varOffset = size.alignTo(varAlign);
  1733. // We may have to insert padding.
  1734. if (varOffset != size) {
  1735. llvm::Type *paddingTy =
  1736. llvm::ArrayType::get(Int8Ty, (varOffset - size).getQuantity());
  1737. types.push_back(paddingTy);
  1738. size = varOffset;
  1739. // Conversely, we might have to prevent LLVM from inserting padding.
  1740. } else if (CGM.getDataLayout().getABITypeAlignment(varTy)
  1741. > varAlign.getQuantity()) {
  1742. packed = true;
  1743. }
  1744. types.push_back(varTy);
  1745. byrefType->setBody(types, packed);
  1746. BlockByrefInfo info;
  1747. info.Type = byrefType;
  1748. info.FieldIndex = types.size() - 1;
  1749. info.FieldOffset = varOffset;
  1750. info.ByrefAlignment = std::max(varAlign, getPointerAlign());
  1751. auto pair = BlockByrefInfos.insert({D, info});
  1752. assert(pair.second && "info was inserted recursively?");
  1753. return pair.first->second;
  1754. }
  1755. /// Initialize the structural components of a __block variable, i.e.
  1756. /// everything but the actual object.
  1757. void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
  1758. // Find the address of the local.
  1759. Address addr = emission.Addr;
  1760. // That's an alloca of the byref structure type.
  1761. llvm::StructType *byrefType = cast<llvm::StructType>(
  1762. cast<llvm::PointerType>(addr.getPointer()->getType())->getElementType());
  1763. unsigned nextHeaderIndex = 0;
  1764. CharUnits nextHeaderOffset;
  1765. auto storeHeaderField = [&](llvm::Value *value, CharUnits fieldSize,
  1766. const Twine &name) {
  1767. auto fieldAddr = Builder.CreateStructGEP(addr, nextHeaderIndex,
  1768. nextHeaderOffset, name);
  1769. Builder.CreateStore(value, fieldAddr);
  1770. nextHeaderIndex++;
  1771. nextHeaderOffset += fieldSize;
  1772. };
  1773. // Build the byref helpers if necessary. This is null if we don't need any.
  1774. BlockByrefHelpers *helpers = buildByrefHelpers(*byrefType, emission);
  1775. const VarDecl &D = *emission.Variable;
  1776. QualType type = D.getType();
  1777. bool HasByrefExtendedLayout;
  1778. Qualifiers::ObjCLifetime ByrefLifetime;
  1779. bool ByRefHasLifetime =
  1780. getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
  1781. llvm::Value *V;
  1782. // Initialize the 'isa', which is just 0 or 1.
  1783. int isa = 0;
  1784. if (type.isObjCGCWeak())
  1785. isa = 1;
  1786. V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
  1787. storeHeaderField(V, getPointerSize(), "byref.isa");
  1788. // Store the address of the variable into its own forwarding pointer.
  1789. storeHeaderField(addr.getPointer(), getPointerSize(), "byref.forwarding");
  1790. // Blocks ABI:
  1791. // c) the flags field is set to either 0 if no helper functions are
  1792. // needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
  1793. BlockFlags flags;
  1794. if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
  1795. if (ByRefHasLifetime) {
  1796. if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
  1797. else switch (ByrefLifetime) {
  1798. case Qualifiers::OCL_Strong:
  1799. flags |= BLOCK_BYREF_LAYOUT_STRONG;
  1800. break;
  1801. case Qualifiers::OCL_Weak:
  1802. flags |= BLOCK_BYREF_LAYOUT_WEAK;
  1803. break;
  1804. case Qualifiers::OCL_ExplicitNone:
  1805. flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
  1806. break;
  1807. case Qualifiers::OCL_None:
  1808. if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
  1809. flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
  1810. break;
  1811. default:
  1812. break;
  1813. }
  1814. if (CGM.getLangOpts().ObjCGCBitmapPrint) {
  1815. printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
  1816. if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
  1817. printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
  1818. if (flags & BLOCK_BYREF_LAYOUT_MASK) {
  1819. BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
  1820. if (ThisFlag == BLOCK_BYREF_LAYOUT_EXTENDED)
  1821. printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
  1822. if (ThisFlag == BLOCK_BYREF_LAYOUT_STRONG)
  1823. printf(" BLOCK_BYREF_LAYOUT_STRONG");
  1824. if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
  1825. printf(" BLOCK_BYREF_LAYOUT_WEAK");
  1826. if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
  1827. printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
  1828. if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
  1829. printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
  1830. }
  1831. printf("\n");
  1832. }
  1833. }
  1834. storeHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
  1835. getIntSize(), "byref.flags");
  1836. CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
  1837. V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
  1838. storeHeaderField(V, getIntSize(), "byref.size");
  1839. if (helpers) {
  1840. storeHeaderField(helpers->CopyHelper, getPointerSize(),
  1841. "byref.copyHelper");
  1842. storeHeaderField(helpers->DisposeHelper, getPointerSize(),
  1843. "byref.disposeHelper");
  1844. }
  1845. if (ByRefHasLifetime && HasByrefExtendedLayout) {
  1846. auto layoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
  1847. storeHeaderField(layoutInfo, getPointerSize(), "byref.layout");
  1848. }
  1849. }
  1850. void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
  1851. llvm::Value *F = CGM.getBlockObjectDispose();
  1852. llvm::Value *args[] = {
  1853. Builder.CreateBitCast(V, Int8PtrTy),
  1854. llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
  1855. };
  1856. EmitNounwindRuntimeCall(F, args); // FIXME: throwing destructors?
  1857. }
  1858. namespace {
  1859. /// Release a __block variable.
  1860. struct CallBlockRelease final : EHScopeStack::Cleanup {
  1861. llvm::Value *Addr;
  1862. CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
  1863. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1864. // Should we be passing FIELD_IS_WEAK here?
  1865. CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
  1866. }
  1867. };
  1868. } // end anonymous namespace
  1869. /// Enter a cleanup to destroy a __block variable. Note that this
  1870. /// cleanup should be a no-op if the variable hasn't left the stack
  1871. /// yet; if a cleanup is required for the variable itself, that needs
  1872. /// to be done externally.
  1873. void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
  1874. // We don't enter this cleanup if we're in pure-GC mode.
  1875. if (CGM.getLangOpts().getGC() == LangOptions::GCOnly)
  1876. return;
  1877. EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup,
  1878. emission.Addr.getPointer());
  1879. }
  1880. /// Adjust the declaration of something from the blocks API.
  1881. static void configureBlocksRuntimeObject(CodeGenModule &CGM,
  1882. llvm::Constant *C) {
  1883. auto *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
  1884. if (CGM.getTarget().getTriple().isOSBinFormatCOFF()) {
  1885. IdentifierInfo &II = CGM.getContext().Idents.get(C->getName());
  1886. TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
  1887. DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
  1888. assert((isa<llvm::Function>(C->stripPointerCasts()) ||
  1889. isa<llvm::GlobalVariable>(C->stripPointerCasts())) &&
  1890. "expected Function or GlobalVariable");
  1891. const NamedDecl *ND = nullptr;
  1892. for (const auto &Result : DC->lookup(&II))
  1893. if ((ND = dyn_cast<FunctionDecl>(Result)) ||
  1894. (ND = dyn_cast<VarDecl>(Result)))
  1895. break;
  1896. // TODO: support static blocks runtime
  1897. if (GV->isDeclaration() && (!ND || !ND->hasAttr<DLLExportAttr>())) {
  1898. GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
  1899. GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
  1900. } else {
  1901. GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
  1902. GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
  1903. }
  1904. }
  1905. if (!CGM.getLangOpts().BlocksRuntimeOptional)
  1906. return;
  1907. if (GV->isDeclaration() && GV->hasExternalLinkage())
  1908. GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
  1909. }
  1910. llvm::Constant *CodeGenModule::getBlockObjectDispose() {
  1911. if (BlockObjectDispose)
  1912. return BlockObjectDispose;
  1913. llvm::Type *args[] = { Int8PtrTy, Int32Ty };
  1914. llvm::FunctionType *fty
  1915. = llvm::FunctionType::get(VoidTy, args, false);
  1916. BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
  1917. configureBlocksRuntimeObject(*this, BlockObjectDispose);
  1918. return BlockObjectDispose;
  1919. }
  1920. llvm::Constant *CodeGenModule::getBlockObjectAssign() {
  1921. if (BlockObjectAssign)
  1922. return BlockObjectAssign;
  1923. llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
  1924. llvm::FunctionType *fty
  1925. = llvm::FunctionType::get(VoidTy, args, false);
  1926. BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
  1927. configureBlocksRuntimeObject(*this, BlockObjectAssign);
  1928. return BlockObjectAssign;
  1929. }
  1930. llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
  1931. if (NSConcreteGlobalBlock)
  1932. return NSConcreteGlobalBlock;
  1933. NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
  1934. Int8PtrTy->getPointerTo(),
  1935. nullptr);
  1936. configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
  1937. return NSConcreteGlobalBlock;
  1938. }
  1939. llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
  1940. if (NSConcreteStackBlock)
  1941. return NSConcreteStackBlock;
  1942. NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
  1943. Int8PtrTy->getPointerTo(),
  1944. nullptr);
  1945. configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
  1946. return NSConcreteStackBlock;
  1947. }