1 //===--- CGBlocks.cpp - Emit LLVM Code for declarations -------------------===// 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 14 #include "CGDebugInfo.h" 15 #include "CodeGenFunction.h" 16 #include "CGObjCRuntime.h" 17 #include "CodeGenModule.h" 18 #include "CGBlocks.h" 19 #include "clang/AST/DeclObjC.h" 20 #include "llvm/Module.h" 21 #include "llvm/ADT/SmallSet.h" 22 #include "llvm/Target/TargetData.h" 23 #include <algorithm> 24 25 using namespace clang; 26 using namespace CodeGen; 27 28 CGBlockInfo::CGBlockInfo(const BlockExpr *blockExpr, const char *N) 29 : Name(N), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false), 30 HasCXXObject(false), UsesStret(false), StructureType(0), Block(blockExpr) { 31 32 // Skip asm prefix, if any. 33 if (Name && Name[0] == '\01') 34 ++Name; 35 } 36 37 // Anchor the vtable to this translation unit. 38 CodeGenModule::ByrefHelpers::~ByrefHelpers() {} 39 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 45 /// Build the helper function to copy a block. 46 static llvm::Constant *buildCopyHelper(CodeGenModule &CGM, 47 const CGBlockInfo &blockInfo) { 48 return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo); 49 } 50 51 /// Build the helper function to dipose of a block. 52 static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM, 53 const CGBlockInfo &blockInfo) { 54 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo); 55 } 56 57 /// Build the block descriptor constant for a block. 58 static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM, 59 const CGBlockInfo &blockInfo) { 60 ASTContext &C = CGM.getContext(); 61 62 const llvm::Type *ulong = CGM.getTypes().ConvertType(C.UnsignedLongTy); 63 const llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy); 64 65 llvm::SmallVector<llvm::Constant*, 6> elements; 66 67 // reserved 68 elements.push_back(llvm::ConstantInt::get(ulong, 0)); 69 70 // Size 71 // FIXME: What is the right way to say this doesn't fit? We should give 72 // a user diagnostic in that case. Better fix would be to change the 73 // API to size_t. 74 elements.push_back(llvm::ConstantInt::get(ulong, 75 blockInfo.BlockSize.getQuantity())); 76 77 // Optional copy/dispose helpers. 78 if (blockInfo.NeedsCopyDispose) { 79 // copy_func_helper_decl 80 elements.push_back(buildCopyHelper(CGM, blockInfo)); 81 82 // destroy_func_decl 83 elements.push_back(buildDisposeHelper(CGM, blockInfo)); 84 } 85 86 // Signature. Mandatory ObjC-style method descriptor @encode sequence. 87 std::string typeAtEncoding = 88 CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr()); 89 elements.push_back(llvm::ConstantExpr::getBitCast( 90 CGM.GetAddrOfConstantCString(typeAtEncoding), i8p)); 91 92 // GC layout. 93 if (C.getLangOptions().ObjC1) 94 elements.push_back(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo)); 95 else 96 elements.push_back(llvm::Constant::getNullValue(i8p)); 97 98 llvm::Constant *init = 99 llvm::ConstantStruct::get(CGM.getLLVMContext(), elements.data(), 100 elements.size(), false); 101 102 llvm::GlobalVariable *global = 103 new llvm::GlobalVariable(CGM.getModule(), init->getType(), true, 104 llvm::GlobalValue::InternalLinkage, 105 init, "__block_descriptor_tmp"); 106 107 return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType()); 108 } 109 110 /* 111 Purely notional variadic template describing the layout of a block. 112 113 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes> 114 struct Block_literal { 115 /// Initialized to one of: 116 /// extern void *_NSConcreteStackBlock[]; 117 /// extern void *_NSConcreteGlobalBlock[]; 118 /// 119 /// In theory, we could start one off malloc'ed by setting 120 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using 121 /// this isa: 122 /// extern void *_NSConcreteMallocBlock[]; 123 struct objc_class *isa; 124 125 /// These are the flags (with corresponding bit number) that the 126 /// compiler is actually supposed to know about. 127 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block 128 /// descriptor provides copy and dispose helper functions 129 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured 130 /// object with a nontrivial destructor or copy constructor 131 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated 132 /// as global memory 133 /// 29. BLOCK_USE_STRET - indicates that the block function 134 /// uses stret, which objc_msgSend needs to know about 135 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an 136 /// @encoded signature string 137 /// And we're not supposed to manipulate these: 138 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved 139 /// to malloc'ed memory 140 /// 27. BLOCK_IS_GC - indicates that the block has been moved to 141 /// to GC-allocated memory 142 /// Additionally, the bottom 16 bits are a reference count which 143 /// should be zero on the stack. 144 int flags; 145 146 /// Reserved; should be zero-initialized. 147 int reserved; 148 149 /// Function pointer generated from block literal. 150 _ResultType (*invoke)(Block_literal *, _ParamTypes...); 151 152 /// Block description metadata generated from block literal. 153 struct Block_descriptor *block_descriptor; 154 155 /// Captured values follow. 156 _CapturesTypes captures...; 157 }; 158 */ 159 160 /// The number of fields in a block header. 161 const unsigned BlockHeaderSize = 5; 162 163 namespace { 164 /// A chunk of data that we actually have to capture in the block. 165 struct BlockLayoutChunk { 166 CharUnits Alignment; 167 CharUnits Size; 168 const BlockDecl::Capture *Capture; // null for 'this' 169 const llvm::Type *Type; 170 171 BlockLayoutChunk(CharUnits align, CharUnits size, 172 const BlockDecl::Capture *capture, 173 const llvm::Type *type) 174 : Alignment(align), Size(size), Capture(capture), Type(type) {} 175 176 /// Tell the block info that this chunk has the given field index. 177 void setIndex(CGBlockInfo &info, unsigned index) { 178 if (!Capture) 179 info.CXXThisIndex = index; 180 else 181 info.Captures[Capture->getVariable()] 182 = CGBlockInfo::Capture::makeIndex(index); 183 } 184 }; 185 186 /// Order by descending alignment. 187 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) { 188 return left.Alignment > right.Alignment; 189 } 190 } 191 192 /// Determines if the given record type has a mutable field. 193 static bool hasMutableField(const CXXRecordDecl *record) { 194 for (CXXRecordDecl::field_iterator 195 i = record->field_begin(), e = record->field_end(); i != e; ++i) 196 if ((*i)->isMutable()) 197 return true; 198 199 for (CXXRecordDecl::base_class_const_iterator 200 i = record->bases_begin(), e = record->bases_end(); i != e; ++i) { 201 const RecordType *record = i->getType()->castAs<RecordType>(); 202 if (hasMutableField(cast<CXXRecordDecl>(record->getDecl()))) 203 return true; 204 } 205 206 return false; 207 } 208 209 /// Determines if the given type is safe for constant capture in C++. 210 static bool isSafeForCXXConstantCapture(QualType type) { 211 const RecordType *recordType = 212 type->getBaseElementTypeUnsafe()->getAs<RecordType>(); 213 214 // Only records can be unsafe. 215 if (!recordType) return true; 216 217 const CXXRecordDecl *record = cast<CXXRecordDecl>(recordType->getDecl()); 218 219 // Maintain semantics for classes with non-trivial dtors or copy ctors. 220 if (!record->hasTrivialDestructor()) return false; 221 if (!record->hasTrivialCopyConstructor()) return false; 222 223 // Otherwise, we just have to make sure there aren't any mutable 224 // fields that might have changed since initialization. 225 return !hasMutableField(record); 226 } 227 228 /// It is illegal to modify a const object after initialization. 229 /// Therefore, if a const object has a constant initializer, we don't 230 /// actually need to keep storage for it in the block; we'll just 231 /// rematerialize it at the start of the block function. This is 232 /// acceptable because we make no promises about address stability of 233 /// captured variables. 234 static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM, 235 const VarDecl *var) { 236 QualType type = var->getType(); 237 238 // We can only do this if the variable is const. 239 if (!type.isConstQualified()) return 0; 240 241 // Furthermore, in C++ we have to worry about mutable fields: 242 // C++ [dcl.type.cv]p4: 243 // Except that any class member declared mutable can be 244 // modified, any attempt to modify a const object during its 245 // lifetime results in undefined behavior. 246 if (CGM.getLangOptions().CPlusPlus && !isSafeForCXXConstantCapture(type)) 247 return 0; 248 249 // If the variable doesn't have any initializer (shouldn't this be 250 // invalid?), it's not clear what we should do. Maybe capture as 251 // zero? 252 const Expr *init = var->getInit(); 253 if (!init) return 0; 254 255 return CGM.EmitConstantExpr(init, var->getType()); 256 } 257 258 /// Get the low bit of a nonzero character count. This is the 259 /// alignment of the nth byte if the 0th byte is universally aligned. 260 static CharUnits getLowBit(CharUnits v) { 261 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1)); 262 } 263 264 static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info, 265 std::vector<const llvm::Type*> &elementTypes) { 266 ASTContext &C = CGM.getContext(); 267 268 // The header is basically a 'struct { void *; int; int; void *; void *; }'. 269 CharUnits ptrSize, ptrAlign, intSize, intAlign; 270 llvm::tie(ptrSize, ptrAlign) = C.getTypeInfoInChars(C.VoidPtrTy); 271 llvm::tie(intSize, intAlign) = C.getTypeInfoInChars(C.IntTy); 272 273 // Are there crazy embedded platforms where this isn't true? 274 assert(intSize <= ptrSize && "layout assumptions horribly violated"); 275 276 CharUnits headerSize = ptrSize; 277 if (2 * intSize < ptrAlign) headerSize += ptrSize; 278 else headerSize += 2 * intSize; 279 headerSize += 2 * ptrSize; 280 281 info.BlockAlign = ptrAlign; 282 info.BlockSize = headerSize; 283 284 assert(elementTypes.empty()); 285 const llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy); 286 const llvm::Type *intTy = CGM.getTypes().ConvertType(C.IntTy); 287 elementTypes.push_back(i8p); 288 elementTypes.push_back(intTy); 289 elementTypes.push_back(intTy); 290 elementTypes.push_back(i8p); 291 elementTypes.push_back(CGM.getBlockDescriptorType()); 292 293 assert(elementTypes.size() == BlockHeaderSize); 294 } 295 296 /// Compute the layout of the given block. Attempts to lay the block 297 /// out with minimal space requirements. 298 static void computeBlockInfo(CodeGenModule &CGM, CGBlockInfo &info) { 299 ASTContext &C = CGM.getContext(); 300 const BlockDecl *block = info.getBlockDecl(); 301 302 std::vector<const llvm::Type*> elementTypes; 303 initializeForBlockHeader(CGM, info, elementTypes); 304 305 if (!block->hasCaptures()) { 306 info.StructureType = 307 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true); 308 info.CanBeGlobal = true; 309 return; 310 } 311 312 // Collect the layout chunks. 313 llvm::SmallVector<BlockLayoutChunk, 16> layout; 314 layout.reserve(block->capturesCXXThis() + 315 (block->capture_end() - block->capture_begin())); 316 317 CharUnits maxFieldAlign; 318 319 // First, 'this'. 320 if (block->capturesCXXThis()) { 321 const DeclContext *DC = block->getDeclContext(); 322 for (; isa<BlockDecl>(DC); DC = cast<BlockDecl>(DC)->getDeclContext()) 323 ; 324 QualType thisType = cast<CXXMethodDecl>(DC)->getThisType(C); 325 326 const llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType); 327 std::pair<CharUnits,CharUnits> tinfo 328 = CGM.getContext().getTypeInfoInChars(thisType); 329 maxFieldAlign = std::max(maxFieldAlign, tinfo.second); 330 331 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first, 0, llvmType)); 332 } 333 334 // Next, all the block captures. 335 for (BlockDecl::capture_const_iterator ci = block->capture_begin(), 336 ce = block->capture_end(); ci != ce; ++ci) { 337 const VarDecl *variable = ci->getVariable(); 338 339 if (ci->isByRef()) { 340 // We have to copy/dispose of the __block reference. 341 info.NeedsCopyDispose = true; 342 343 // Just use void* instead of a pointer to the byref type. 344 QualType byRefPtrTy = C.VoidPtrTy; 345 346 const llvm::Type *llvmType = CGM.getTypes().ConvertType(byRefPtrTy); 347 std::pair<CharUnits,CharUnits> tinfo 348 = CGM.getContext().getTypeInfoInChars(byRefPtrTy); 349 maxFieldAlign = std::max(maxFieldAlign, tinfo.second); 350 351 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first, 352 &*ci, llvmType)); 353 continue; 354 } 355 356 // Otherwise, build a layout chunk with the size and alignment of 357 // the declaration. 358 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, variable)) { 359 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant); 360 continue; 361 } 362 363 // Block pointers require copy/dispose. 364 if (variable->getType()->isBlockPointerType()) { 365 info.NeedsCopyDispose = true; 366 367 // So do Objective-C pointers. 368 } else if (variable->getType()->isObjCObjectPointerType() || 369 C.isObjCNSObjectType(variable->getType())) { 370 info.NeedsCopyDispose = true; 371 372 // So do types that require non-trivial copy construction. 373 } else if (ci->hasCopyExpr()) { 374 info.NeedsCopyDispose = true; 375 info.HasCXXObject = true; 376 377 // And so do types with destructors. 378 } else if (CGM.getLangOptions().CPlusPlus) { 379 if (const CXXRecordDecl *record = 380 variable->getType()->getAsCXXRecordDecl()) { 381 if (!record->hasTrivialDestructor()) { 382 info.HasCXXObject = true; 383 info.NeedsCopyDispose = true; 384 } 385 } 386 } 387 388 CharUnits size = C.getTypeSizeInChars(variable->getType()); 389 CharUnits align = C.getDeclAlign(variable); 390 maxFieldAlign = std::max(maxFieldAlign, align); 391 392 const llvm::Type *llvmType = 393 CGM.getTypes().ConvertTypeForMem(variable->getType()); 394 395 layout.push_back(BlockLayoutChunk(align, size, &*ci, llvmType)); 396 } 397 398 // If that was everything, we're done here. 399 if (layout.empty()) { 400 info.StructureType = 401 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true); 402 info.CanBeGlobal = true; 403 return; 404 } 405 406 // Sort the layout by alignment. We have to use a stable sort here 407 // to get reproducible results. There should probably be an 408 // llvm::array_pod_stable_sort. 409 std::stable_sort(layout.begin(), layout.end()); 410 411 CharUnits &blockSize = info.BlockSize; 412 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign); 413 414 // Assuming that the first byte in the header is maximally aligned, 415 // get the alignment of the first byte following the header. 416 CharUnits endAlign = getLowBit(blockSize); 417 418 // If the end of the header isn't satisfactorily aligned for the 419 // maximum thing, look for things that are okay with the header-end 420 // alignment, and keep appending them until we get something that's 421 // aligned right. This algorithm is only guaranteed optimal if 422 // that condition is satisfied at some point; otherwise we can get 423 // things like: 424 // header // next byte has alignment 4 425 // something_with_size_5; // next byte has alignment 1 426 // something_with_alignment_8; 427 // which has 7 bytes of padding, as opposed to the naive solution 428 // which might have less (?). 429 if (endAlign < maxFieldAlign) { 430 llvm::SmallVectorImpl<BlockLayoutChunk>::iterator 431 li = layout.begin() + 1, le = layout.end(); 432 433 // Look for something that the header end is already 434 // satisfactorily aligned for. 435 for (; li != le && endAlign < li->Alignment; ++li) 436 ; 437 438 // If we found something that's naturally aligned for the end of 439 // the header, keep adding things... 440 if (li != le) { 441 llvm::SmallVectorImpl<BlockLayoutChunk>::iterator first = li; 442 for (; li != le; ++li) { 443 assert(endAlign >= li->Alignment); 444 445 li->setIndex(info, elementTypes.size()); 446 elementTypes.push_back(li->Type); 447 blockSize += li->Size; 448 endAlign = getLowBit(blockSize); 449 450 // ...until we get to the alignment of the maximum field. 451 if (endAlign >= maxFieldAlign) 452 break; 453 } 454 455 // Don't re-append everything we just appended. 456 layout.erase(first, li); 457 } 458 } 459 460 // At this point, we just have to add padding if the end align still 461 // isn't aligned right. 462 if (endAlign < maxFieldAlign) { 463 CharUnits padding = maxFieldAlign - endAlign; 464 465 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty, 466 padding.getQuantity())); 467 blockSize += padding; 468 469 endAlign = getLowBit(blockSize); 470 assert(endAlign >= maxFieldAlign); 471 } 472 473 // Slam everything else on now. This works because they have 474 // strictly decreasing alignment and we expect that size is always a 475 // multiple of alignment. 476 for (llvm::SmallVectorImpl<BlockLayoutChunk>::iterator 477 li = layout.begin(), le = layout.end(); li != le; ++li) { 478 assert(endAlign >= li->Alignment); 479 li->setIndex(info, elementTypes.size()); 480 elementTypes.push_back(li->Type); 481 blockSize += li->Size; 482 endAlign = getLowBit(blockSize); 483 } 484 485 info.StructureType = 486 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true); 487 } 488 489 /// Emit a block literal expression in the current function. 490 llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) { 491 std::string Name = CurFn->getName(); 492 CGBlockInfo blockInfo(blockExpr, Name.c_str()); 493 494 // Compute information about the layout, etc., of this block. 495 computeBlockInfo(CGM, blockInfo); 496 497 // Using that metadata, generate the actual block function. 498 llvm::Constant *blockFn 499 = CodeGenFunction(CGM).GenerateBlockFunction(CurGD, blockInfo, 500 CurFuncDecl, LocalDeclMap); 501 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy); 502 503 // If there is nothing to capture, we can emit this as a global block. 504 if (blockInfo.CanBeGlobal) 505 return buildGlobalBlock(CGM, blockInfo, blockFn); 506 507 // Otherwise, we have to emit this as a local block. 508 509 llvm::Constant *isa = CGM.getNSConcreteStackBlock(); 510 isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy); 511 512 // Build the block descriptor. 513 llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo); 514 515 const llvm::Type *intTy = ConvertType(getContext().IntTy); 516 517 llvm::AllocaInst *blockAddr = 518 CreateTempAlloca(blockInfo.StructureType, "block"); 519 blockAddr->setAlignment(blockInfo.BlockAlign.getQuantity()); 520 521 // Compute the initial on-stack block flags. 522 BlockFlags flags = BLOCK_HAS_SIGNATURE; 523 if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE; 524 if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ; 525 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET; 526 527 // Initialize the block literal. 528 Builder.CreateStore(isa, Builder.CreateStructGEP(blockAddr, 0, "block.isa")); 529 Builder.CreateStore(llvm::ConstantInt::get(intTy, flags.getBitMask()), 530 Builder.CreateStructGEP(blockAddr, 1, "block.flags")); 531 Builder.CreateStore(llvm::ConstantInt::get(intTy, 0), 532 Builder.CreateStructGEP(blockAddr, 2, "block.reserved")); 533 Builder.CreateStore(blockFn, Builder.CreateStructGEP(blockAddr, 3, 534 "block.invoke")); 535 Builder.CreateStore(descriptor, Builder.CreateStructGEP(blockAddr, 4, 536 "block.descriptor")); 537 538 // Finally, capture all the values into the block. 539 const BlockDecl *blockDecl = blockInfo.getBlockDecl(); 540 541 // First, 'this'. 542 if (blockDecl->capturesCXXThis()) { 543 llvm::Value *addr = Builder.CreateStructGEP(blockAddr, 544 blockInfo.CXXThisIndex, 545 "block.captured-this.addr"); 546 Builder.CreateStore(LoadCXXThis(), addr); 547 } 548 549 // Next, captured variables. 550 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(), 551 ce = blockDecl->capture_end(); ci != ce; ++ci) { 552 const VarDecl *variable = ci->getVariable(); 553 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable); 554 555 // Ignore constant captures. 556 if (capture.isConstant()) continue; 557 558 QualType type = variable->getType(); 559 560 // This will be a [[type]]*, except that a byref entry will just be 561 // an i8**. 562 llvm::Value *blockField = 563 Builder.CreateStructGEP(blockAddr, capture.getIndex(), 564 "block.captured"); 565 566 // Compute the address of the thing we're going to move into the 567 // block literal. 568 llvm::Value *src; 569 if (ci->isNested()) { 570 // We need to use the capture from the enclosing block. 571 const CGBlockInfo::Capture &enclosingCapture = 572 BlockInfo->getCapture(variable); 573 574 // This is a [[type]]*, except that a byref entry wil just be an i8**. 575 src = Builder.CreateStructGEP(LoadBlockStruct(), 576 enclosingCapture.getIndex(), 577 "block.capture.addr"); 578 } else { 579 // This is a [[type]]*. 580 src = LocalDeclMap[variable]; 581 } 582 583 // For byrefs, we just write the pointer to the byref struct into 584 // the block field. There's no need to chase the forwarding 585 // pointer at this point, since we're building something that will 586 // live a shorter life than the stack byref anyway. 587 if (ci->isByRef()) { 588 // Get a void* that points to the byref struct. 589 if (ci->isNested()) 590 src = Builder.CreateLoad(src, "byref.capture"); 591 else 592 src = Builder.CreateBitCast(src, VoidPtrTy); 593 594 // Write that void* into the capture field. 595 Builder.CreateStore(src, blockField); 596 597 // If we have a copy constructor, evaluate that into the block field. 598 } else if (const Expr *copyExpr = ci->getCopyExpr()) { 599 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr); 600 601 // If it's a reference variable, copy the reference into the block field. 602 } else if (type->isReferenceType()) { 603 Builder.CreateStore(Builder.CreateLoad(src, "ref.val"), blockField); 604 605 // Otherwise, fake up a POD copy into the block field. 606 } else { 607 // We use one of these or the other depending on whether the 608 // reference is nested. 609 DeclRefExpr notNested(const_cast<VarDecl*>(variable), type, VK_LValue, 610 SourceLocation()); 611 BlockDeclRefExpr nested(const_cast<VarDecl*>(variable), type, 612 VK_LValue, SourceLocation(), /*byref*/ false); 613 614 Expr *declRef = 615 (ci->isNested() ? static_cast<Expr*>(&nested) : ¬Nested); 616 617 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue, 618 declRef, VK_RValue); 619 EmitExprAsInit(&l2r, variable, blockField, 620 getContext().getDeclAlign(variable), 621 /*captured by init*/ false); 622 } 623 624 // Push a destructor if necessary. The semantics for when this 625 // actually gets run are really obscure. 626 if (!ci->isByRef() && CGM.getLangOptions().CPlusPlus) 627 PushDestructorCleanup(type, blockField); 628 } 629 630 // Cast to the converted block-pointer type, which happens (somewhat 631 // unfortunately) to be a pointer to function type. 632 llvm::Value *result = 633 Builder.CreateBitCast(blockAddr, 634 ConvertType(blockInfo.getBlockExpr()->getType())); 635 636 return result; 637 } 638 639 640 const llvm::Type *CodeGenModule::getBlockDescriptorType() { 641 if (BlockDescriptorType) 642 return BlockDescriptorType; 643 644 const llvm::Type *UnsignedLongTy = 645 getTypes().ConvertType(getContext().UnsignedLongTy); 646 647 // struct __block_descriptor { 648 // unsigned long reserved; 649 // unsigned long block_size; 650 // 651 // // later, the following will be added 652 // 653 // struct { 654 // void (*copyHelper)(); 655 // void (*copyHelper)(); 656 // } helpers; // !!! optional 657 // 658 // const char *signature; // the block signature 659 // const char *layout; // reserved 660 // }; 661 BlockDescriptorType = llvm::StructType::get(UnsignedLongTy->getContext(), 662 UnsignedLongTy, 663 UnsignedLongTy, 664 NULL); 665 666 getModule().addTypeName("struct.__block_descriptor", 667 BlockDescriptorType); 668 669 // Now form a pointer to that. 670 BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType); 671 return BlockDescriptorType; 672 } 673 674 const llvm::Type *CodeGenModule::getGenericBlockLiteralType() { 675 if (GenericBlockLiteralType) 676 return GenericBlockLiteralType; 677 678 const llvm::Type *BlockDescPtrTy = getBlockDescriptorType(); 679 680 // struct __block_literal_generic { 681 // void *__isa; 682 // int __flags; 683 // int __reserved; 684 // void (*__invoke)(void *); 685 // struct __block_descriptor *__descriptor; 686 // }; 687 GenericBlockLiteralType = llvm::StructType::get(getLLVMContext(), 688 VoidPtrTy, 689 IntTy, 690 IntTy, 691 VoidPtrTy, 692 BlockDescPtrTy, 693 NULL); 694 695 getModule().addTypeName("struct.__block_literal_generic", 696 GenericBlockLiteralType); 697 698 return GenericBlockLiteralType; 699 } 700 701 702 RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E, 703 ReturnValueSlot ReturnValue) { 704 const BlockPointerType *BPT = 705 E->getCallee()->getType()->getAs<BlockPointerType>(); 706 707 llvm::Value *Callee = EmitScalarExpr(E->getCallee()); 708 709 // Get a pointer to the generic block literal. 710 const llvm::Type *BlockLiteralTy = 711 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType()); 712 713 // Bitcast the callee to a block literal. 714 llvm::Value *BlockLiteral = 715 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal"); 716 717 // Get the function pointer from the literal. 718 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp"); 719 720 BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy, "tmp"); 721 722 // Add the block literal. 723 QualType VoidPtrTy = getContext().getPointerType(getContext().VoidTy); 724 CallArgList Args; 725 Args.push_back(std::make_pair(RValue::get(BlockLiteral), VoidPtrTy)); 726 727 QualType FnType = BPT->getPointeeType(); 728 729 // And the rest of the arguments. 730 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), 731 E->arg_begin(), E->arg_end()); 732 733 // Load the function. 734 llvm::Value *Func = Builder.CreateLoad(FuncPtr, "tmp"); 735 736 const FunctionType *FuncTy = FnType->castAs<FunctionType>(); 737 QualType ResultType = FuncTy->getResultType(); 738 739 const CGFunctionInfo &FnInfo = 740 CGM.getTypes().getFunctionInfo(ResultType, Args, 741 FuncTy->getExtInfo()); 742 743 // Cast the function pointer to the right type. 744 const llvm::Type *BlockFTy = 745 CGM.getTypes().GetFunctionType(FnInfo, false); 746 747 const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy); 748 Func = Builder.CreateBitCast(Func, BlockFTyPtr); 749 750 // And call the block. 751 return EmitCall(FnInfo, Func, ReturnValue, Args); 752 } 753 754 llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable, 755 bool isByRef) { 756 assert(BlockInfo && "evaluating block ref without block information?"); 757 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable); 758 759 // Handle constant captures. 760 if (capture.isConstant()) return LocalDeclMap[variable]; 761 762 llvm::Value *addr = 763 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(), 764 "block.capture.addr"); 765 766 if (isByRef) { 767 // addr should be a void** right now. Load, then cast the result 768 // to byref*. 769 770 addr = Builder.CreateLoad(addr); 771 const llvm::PointerType *byrefPointerType 772 = llvm::PointerType::get(BuildByRefType(variable), 0); 773 addr = Builder.CreateBitCast(addr, byrefPointerType, 774 "byref.addr"); 775 776 // Follow the forwarding pointer. 777 addr = Builder.CreateStructGEP(addr, 1, "byref.forwarding"); 778 addr = Builder.CreateLoad(addr, "byref.addr.forwarded"); 779 780 // Cast back to byref* and GEP over to the actual object. 781 addr = Builder.CreateBitCast(addr, byrefPointerType); 782 addr = Builder.CreateStructGEP(addr, getByRefValueLLVMField(variable), 783 variable->getNameAsString()); 784 } 785 786 if (variable->getType()->isReferenceType()) 787 addr = Builder.CreateLoad(addr, "ref.tmp"); 788 789 return addr; 790 } 791 792 llvm::Constant * 793 CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr, 794 const char *name) { 795 CGBlockInfo blockInfo(blockExpr, name); 796 797 // Compute information about the layout, etc., of this block. 798 computeBlockInfo(*this, blockInfo); 799 800 // Using that metadata, generate the actual block function. 801 llvm::Constant *blockFn; 802 { 803 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap; 804 blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(), 805 blockInfo, 806 0, LocalDeclMap); 807 } 808 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy); 809 810 return buildGlobalBlock(*this, blockInfo, blockFn); 811 } 812 813 static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM, 814 const CGBlockInfo &blockInfo, 815 llvm::Constant *blockFn) { 816 assert(blockInfo.CanBeGlobal); 817 818 // Generate the constants for the block literal initializer. 819 llvm::Constant *fields[BlockHeaderSize]; 820 821 // isa 822 fields[0] = CGM.getNSConcreteGlobalBlock(); 823 824 // __flags 825 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE; 826 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET; 827 828 fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask()); 829 830 // Reserved 831 fields[2] = llvm::Constant::getNullValue(CGM.IntTy); 832 833 // Function 834 fields[3] = blockFn; 835 836 // Descriptor 837 fields[4] = buildBlockDescriptor(CGM, blockInfo); 838 839 llvm::Constant *init = 840 llvm::ConstantStruct::get(CGM.getLLVMContext(), fields, BlockHeaderSize, 841 /*packed*/ false); 842 843 llvm::GlobalVariable *literal = 844 new llvm::GlobalVariable(CGM.getModule(), 845 init->getType(), 846 /*constant*/ true, 847 llvm::GlobalVariable::InternalLinkage, 848 init, 849 "__block_literal_global"); 850 literal->setAlignment(blockInfo.BlockAlign.getQuantity()); 851 852 // Return a constant of the appropriately-casted type. 853 const llvm::Type *requiredType = 854 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType()); 855 return llvm::ConstantExpr::getBitCast(literal, requiredType); 856 } 857 858 llvm::Function * 859 CodeGenFunction::GenerateBlockFunction(GlobalDecl GD, 860 const CGBlockInfo &blockInfo, 861 const Decl *outerFnDecl, 862 const DeclMapTy &ldm) { 863 const BlockDecl *blockDecl = blockInfo.getBlockDecl(); 864 865 // Check if we should generate debug info for this block function. 866 if (CGM.getModuleDebugInfo()) 867 DebugInfo = CGM.getModuleDebugInfo(); 868 869 BlockInfo = &blockInfo; 870 871 // Arrange for local static and local extern declarations to appear 872 // to be local to this function as well, in case they're directly 873 // referenced in a block. 874 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) { 875 const VarDecl *var = dyn_cast<VarDecl>(i->first); 876 if (var && !var->hasLocalStorage()) 877 LocalDeclMap[var] = i->second; 878 } 879 880 // Begin building the function declaration. 881 882 // Build the argument list. 883 FunctionArgList args; 884 885 // The first argument is the block pointer. Just take it as a void* 886 // and cast it later. 887 QualType selfTy = getContext().VoidPtrTy; 888 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor"); 889 890 ImplicitParamDecl selfDecl(const_cast<BlockDecl*>(blockDecl), 891 SourceLocation(), II, selfTy); 892 args.push_back(&selfDecl); 893 894 // Now add the rest of the parameters. 895 for (BlockDecl::param_const_iterator i = blockDecl->param_begin(), 896 e = blockDecl->param_end(); i != e; ++i) 897 args.push_back(*i); 898 899 // Create the function declaration. 900 const FunctionProtoType *fnType = 901 cast<FunctionProtoType>(blockInfo.getBlockExpr()->getFunctionType()); 902 const CGFunctionInfo &fnInfo = 903 CGM.getTypes().getFunctionInfo(fnType->getResultType(), args, 904 fnType->getExtInfo()); 905 if (CGM.ReturnTypeUsesSRet(fnInfo)) 906 blockInfo.UsesStret = true; 907 908 const llvm::FunctionType *fnLLVMType = 909 CGM.getTypes().GetFunctionType(fnInfo, fnType->isVariadic()); 910 911 MangleBuffer name; 912 CGM.getBlockMangledName(GD, name, blockDecl); 913 llvm::Function *fn = 914 llvm::Function::Create(fnLLVMType, llvm::GlobalValue::InternalLinkage, 915 name.getString(), &CGM.getModule()); 916 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo); 917 918 // Begin generating the function. 919 StartFunction(blockDecl, fnType->getResultType(), fn, fnInfo, args, 920 blockInfo.getBlockExpr()->getBody()->getLocStart()); 921 CurFuncDecl = outerFnDecl; // StartFunction sets this to blockDecl 922 923 // Okay. Undo some of what StartFunction did. 924 925 // Pull the 'self' reference out of the local decl map. 926 llvm::Value *blockAddr = LocalDeclMap[&selfDecl]; 927 LocalDeclMap.erase(&selfDecl); 928 BlockPointer = Builder.CreateBitCast(blockAddr, 929 blockInfo.StructureType->getPointerTo(), 930 "block"); 931 932 // If we have a C++ 'this' reference, go ahead and force it into 933 // existence now. 934 if (blockDecl->capturesCXXThis()) { 935 llvm::Value *addr = Builder.CreateStructGEP(BlockPointer, 936 blockInfo.CXXThisIndex, 937 "block.captured-this"); 938 CXXThisValue = Builder.CreateLoad(addr, "this"); 939 } 940 941 // LoadObjCSelf() expects there to be an entry for 'self' in LocalDeclMap; 942 // appease it. 943 if (const ObjCMethodDecl *method 944 = dyn_cast_or_null<ObjCMethodDecl>(CurFuncDecl)) { 945 const VarDecl *self = method->getSelfDecl(); 946 947 // There might not be a capture for 'self', but if there is... 948 if (blockInfo.Captures.count(self)) { 949 const CGBlockInfo::Capture &capture = blockInfo.getCapture(self); 950 llvm::Value *selfAddr = Builder.CreateStructGEP(BlockPointer, 951 capture.getIndex(), 952 "block.captured-self"); 953 LocalDeclMap[self] = selfAddr; 954 } 955 } 956 957 // Also force all the constant captures. 958 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(), 959 ce = blockDecl->capture_end(); ci != ce; ++ci) { 960 const VarDecl *variable = ci->getVariable(); 961 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable); 962 if (!capture.isConstant()) continue; 963 964 unsigned align = getContext().getDeclAlign(variable).getQuantity(); 965 966 llvm::AllocaInst *alloca = 967 CreateMemTemp(variable->getType(), "block.captured-const"); 968 alloca->setAlignment(align); 969 970 Builder.CreateStore(capture.getConstant(), alloca, align); 971 972 LocalDeclMap[variable] = alloca; 973 } 974 975 // Save a spot to insert the debug information for all the BlockDeclRefDecls. 976 llvm::BasicBlock *entry = Builder.GetInsertBlock(); 977 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint(); 978 --entry_ptr; 979 980 EmitStmt(blockDecl->getBody()); 981 982 // Remember where we were... 983 llvm::BasicBlock *resume = Builder.GetInsertBlock(); 984 985 // Go back to the entry. 986 ++entry_ptr; 987 Builder.SetInsertPoint(entry, entry_ptr); 988 989 // Emit debug information for all the BlockDeclRefDecls. 990 // FIXME: also for 'this' 991 if (CGDebugInfo *DI = getDebugInfo()) { 992 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(), 993 ce = blockDecl->capture_end(); ci != ce; ++ci) { 994 const VarDecl *variable = ci->getVariable(); 995 DI->setLocation(variable->getLocation()); 996 997 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable); 998 if (capture.isConstant()) { 999 DI->EmitDeclareOfAutoVariable(variable, LocalDeclMap[variable], 1000 Builder); 1001 continue; 1002 } 1003 1004 DI->EmitDeclareOfBlockDeclRefVariable(variable, BlockPointer, 1005 Builder, blockInfo); 1006 } 1007 } 1008 1009 // And resume where we left off. 1010 if (resume == 0) 1011 Builder.ClearInsertionPoint(); 1012 else 1013 Builder.SetInsertPoint(resume); 1014 1015 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc()); 1016 1017 return fn; 1018 } 1019 1020 /* 1021 notes.push_back(HelperInfo()); 1022 HelperInfo ¬e = notes.back(); 1023 note.index = capture.getIndex(); 1024 note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type)); 1025 note.cxxbar_import = ci->getCopyExpr(); 1026 1027 if (ci->isByRef()) { 1028 note.flag = BLOCK_FIELD_IS_BYREF; 1029 if (type.isObjCGCWeak()) 1030 note.flag |= BLOCK_FIELD_IS_WEAK; 1031 } else if (type->isBlockPointerType()) { 1032 note.flag = BLOCK_FIELD_IS_BLOCK; 1033 } else { 1034 note.flag = BLOCK_FIELD_IS_OBJECT; 1035 } 1036 */ 1037 1038 1039 1040 1041 1042 llvm::Constant * 1043 CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) { 1044 ASTContext &C = getContext(); 1045 1046 FunctionArgList args; 1047 ImplicitParamDecl dstDecl(0, SourceLocation(), 0, C.VoidPtrTy); 1048 args.push_back(&dstDecl); 1049 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy); 1050 args.push_back(&srcDecl); 1051 1052 const CGFunctionInfo &FI = 1053 CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo()); 1054 1055 // FIXME: it would be nice if these were mergeable with things with 1056 // identical semantics. 1057 const llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false); 1058 1059 llvm::Function *Fn = 1060 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage, 1061 "__copy_helper_block_", &CGM.getModule()); 1062 1063 IdentifierInfo *II 1064 = &CGM.getContext().Idents.get("__copy_helper_block_"); 1065 1066 FunctionDecl *FD = FunctionDecl::Create(C, 1067 C.getTranslationUnitDecl(), 1068 SourceLocation(), 1069 SourceLocation(), II, C.VoidTy, 0, 1070 SC_Static, 1071 SC_None, 1072 false, 1073 true); 1074 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation()); 1075 1076 const llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo(); 1077 1078 llvm::Value *src = GetAddrOfLocalVar(&srcDecl); 1079 src = Builder.CreateLoad(src); 1080 src = Builder.CreateBitCast(src, structPtrTy, "block.source"); 1081 1082 llvm::Value *dst = GetAddrOfLocalVar(&dstDecl); 1083 dst = Builder.CreateLoad(dst); 1084 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest"); 1085 1086 const BlockDecl *blockDecl = blockInfo.getBlockDecl(); 1087 1088 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(), 1089 ce = blockDecl->capture_end(); ci != ce; ++ci) { 1090 const VarDecl *variable = ci->getVariable(); 1091 QualType type = variable->getType(); 1092 1093 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable); 1094 if (capture.isConstant()) continue; 1095 1096 const Expr *copyExpr = ci->getCopyExpr(); 1097 unsigned flags = 0; 1098 1099 if (copyExpr) { 1100 assert(!ci->isByRef()); 1101 // don't bother computing flags 1102 } else if (ci->isByRef()) { 1103 flags = BLOCK_FIELD_IS_BYREF; 1104 if (type.isObjCGCWeak()) flags |= BLOCK_FIELD_IS_WEAK; 1105 } else if (type->isBlockPointerType()) { 1106 flags = BLOCK_FIELD_IS_BLOCK; 1107 } else if (type->isObjCObjectPointerType() || C.isObjCNSObjectType(type)) { 1108 flags = BLOCK_FIELD_IS_OBJECT; 1109 } 1110 1111 if (!copyExpr && !flags) continue; 1112 1113 unsigned index = capture.getIndex(); 1114 llvm::Value *srcField = Builder.CreateStructGEP(src, index); 1115 llvm::Value *dstField = Builder.CreateStructGEP(dst, index); 1116 1117 // If there's an explicit copy expression, we do that. 1118 if (copyExpr) { 1119 EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr); 1120 } else { 1121 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src"); 1122 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy); 1123 llvm::Value *dstAddr = Builder.CreateBitCast(dstField, VoidPtrTy); 1124 Builder.CreateCall3(CGM.getBlockObjectAssign(), dstAddr, srcValue, 1125 llvm::ConstantInt::get(Int32Ty, flags)); 1126 } 1127 } 1128 1129 FinishFunction(); 1130 1131 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy); 1132 } 1133 1134 llvm::Constant * 1135 CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) { 1136 ASTContext &C = getContext(); 1137 1138 FunctionArgList args; 1139 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy); 1140 args.push_back(&srcDecl); 1141 1142 const CGFunctionInfo &FI = 1143 CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo()); 1144 1145 // FIXME: We'd like to put these into a mergable by content, with 1146 // internal linkage. 1147 const llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false); 1148 1149 llvm::Function *Fn = 1150 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage, 1151 "__destroy_helper_block_", &CGM.getModule()); 1152 1153 IdentifierInfo *II 1154 = &CGM.getContext().Idents.get("__destroy_helper_block_"); 1155 1156 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(), 1157 SourceLocation(), 1158 SourceLocation(), II, C.VoidTy, 0, 1159 SC_Static, 1160 SC_None, 1161 false, true); 1162 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation()); 1163 1164 const llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo(); 1165 1166 llvm::Value *src = GetAddrOfLocalVar(&srcDecl); 1167 src = Builder.CreateLoad(src); 1168 src = Builder.CreateBitCast(src, structPtrTy, "block"); 1169 1170 const BlockDecl *blockDecl = blockInfo.getBlockDecl(); 1171 1172 CodeGenFunction::RunCleanupsScope cleanups(*this); 1173 1174 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(), 1175 ce = blockDecl->capture_end(); ci != ce; ++ci) { 1176 const VarDecl *variable = ci->getVariable(); 1177 QualType type = variable->getType(); 1178 1179 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable); 1180 if (capture.isConstant()) continue; 1181 1182 BlockFieldFlags flags; 1183 const CXXDestructorDecl *dtor = 0; 1184 1185 if (ci->isByRef()) { 1186 flags = BLOCK_FIELD_IS_BYREF; 1187 if (type.isObjCGCWeak()) flags |= BLOCK_FIELD_IS_WEAK; 1188 } else if (type->isBlockPointerType()) { 1189 flags = BLOCK_FIELD_IS_BLOCK; 1190 } else if (type->isObjCObjectPointerType() || C.isObjCNSObjectType(type)) { 1191 flags = BLOCK_FIELD_IS_OBJECT; 1192 } else if (C.getLangOptions().CPlusPlus) { 1193 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) 1194 if (!record->hasTrivialDestructor()) 1195 dtor = record->getDestructor(); 1196 } 1197 1198 if (!dtor && flags.empty()) continue; 1199 1200 unsigned index = capture.getIndex(); 1201 llvm::Value *srcField = Builder.CreateStructGEP(src, index); 1202 1203 // If there's an explicit copy expression, we do that. 1204 if (dtor) { 1205 PushDestructorCleanup(dtor, srcField); 1206 1207 // Otherwise we call _Block_object_dispose. It wouldn't be too 1208 // hard to just emit this as a cleanup if we wanted to make sure 1209 // that things were done in reverse. 1210 } else { 1211 llvm::Value *value = Builder.CreateLoad(srcField); 1212 value = Builder.CreateBitCast(value, VoidPtrTy); 1213 BuildBlockRelease(value, flags); 1214 } 1215 } 1216 1217 cleanups.ForceCleanup(); 1218 1219 FinishFunction(); 1220 1221 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy); 1222 } 1223 1224 namespace { 1225 1226 /// Emits the copy/dispose helper functions for a __block object of id type. 1227 class ObjectByrefHelpers : public CodeGenModule::ByrefHelpers { 1228 BlockFieldFlags Flags; 1229 1230 public: 1231 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags) 1232 : ByrefHelpers(alignment), Flags(flags) {} 1233 1234 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField, 1235 llvm::Value *srcField) { 1236 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy); 1237 1238 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy); 1239 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField); 1240 1241 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask(); 1242 1243 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags); 1244 llvm::Value *fn = CGF.CGM.getBlockObjectAssign(); 1245 CGF.Builder.CreateCall3(fn, destField, srcValue, flagsVal); 1246 } 1247 1248 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) { 1249 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0)); 1250 llvm::Value *value = CGF.Builder.CreateLoad(field); 1251 1252 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER); 1253 } 1254 1255 void profileImpl(llvm::FoldingSetNodeID &id) const { 1256 id.AddInteger(Flags.getBitMask()); 1257 } 1258 }; 1259 1260 /// Emits the copy/dispose helpers for a __block variable with a 1261 /// nontrivial copy constructor or destructor. 1262 class CXXByrefHelpers : public CodeGenModule::ByrefHelpers { 1263 QualType VarType; 1264 const Expr *CopyExpr; 1265 1266 public: 1267 CXXByrefHelpers(CharUnits alignment, QualType type, 1268 const Expr *copyExpr) 1269 : ByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {} 1270 1271 bool needsCopy() const { return CopyExpr != 0; } 1272 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField, 1273 llvm::Value *srcField) { 1274 if (!CopyExpr) return; 1275 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr); 1276 } 1277 1278 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) { 1279 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin(); 1280 CGF.PushDestructorCleanup(VarType, field); 1281 CGF.PopCleanupBlocks(cleanupDepth); 1282 } 1283 1284 void profileImpl(llvm::FoldingSetNodeID &id) const { 1285 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr()); 1286 } 1287 }; 1288 } // end anonymous namespace 1289 1290 static llvm::Constant * 1291 generateByrefCopyHelper(CodeGenFunction &CGF, 1292 const llvm::StructType &byrefType, 1293 CodeGenModule::ByrefHelpers &byrefInfo) { 1294 ASTContext &Context = CGF.getContext(); 1295 1296 QualType R = Context.VoidTy; 1297 1298 FunctionArgList args; 1299 ImplicitParamDecl dst(0, SourceLocation(), 0, Context.VoidPtrTy); 1300 args.push_back(&dst); 1301 1302 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy); 1303 args.push_back(&src); 1304 1305 const CGFunctionInfo &FI = 1306 CGF.CGM.getTypes().getFunctionInfo(R, args, FunctionType::ExtInfo()); 1307 1308 CodeGenTypes &Types = CGF.CGM.getTypes(); 1309 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false); 1310 1311 // FIXME: We'd like to put these into a mergable by content, with 1312 // internal linkage. 1313 llvm::Function *Fn = 1314 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage, 1315 "__Block_byref_object_copy_", &CGF.CGM.getModule()); 1316 1317 IdentifierInfo *II 1318 = &Context.Idents.get("__Block_byref_object_copy_"); 1319 1320 FunctionDecl *FD = FunctionDecl::Create(Context, 1321 Context.getTranslationUnitDecl(), 1322 SourceLocation(), 1323 SourceLocation(), II, R, 0, 1324 SC_Static, 1325 SC_None, 1326 false, true); 1327 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation()); 1328 1329 if (byrefInfo.needsCopy()) { 1330 const llvm::Type *byrefPtrType = byrefType.getPointerTo(0); 1331 1332 // dst->x 1333 llvm::Value *destField = CGF.GetAddrOfLocalVar(&dst); 1334 destField = CGF.Builder.CreateLoad(destField); 1335 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType); 1336 destField = CGF.Builder.CreateStructGEP(destField, 6, "x"); 1337 1338 // src->x 1339 llvm::Value *srcField = CGF.GetAddrOfLocalVar(&src); 1340 srcField = CGF.Builder.CreateLoad(srcField); 1341 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType); 1342 srcField = CGF.Builder.CreateStructGEP(srcField, 6, "x"); 1343 1344 byrefInfo.emitCopy(CGF, destField, srcField); 1345 } 1346 1347 CGF.FinishFunction(); 1348 1349 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy); 1350 } 1351 1352 /// Build the copy helper for a __block variable. 1353 static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM, 1354 const llvm::StructType &byrefType, 1355 CodeGenModule::ByrefHelpers &info) { 1356 CodeGenFunction CGF(CGM); 1357 return generateByrefCopyHelper(CGF, byrefType, info); 1358 } 1359 1360 /// Generate code for a __block variable's dispose helper. 1361 static llvm::Constant * 1362 generateByrefDisposeHelper(CodeGenFunction &CGF, 1363 const llvm::StructType &byrefType, 1364 CodeGenModule::ByrefHelpers &byrefInfo) { 1365 ASTContext &Context = CGF.getContext(); 1366 QualType R = Context.VoidTy; 1367 1368 FunctionArgList args; 1369 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy); 1370 args.push_back(&src); 1371 1372 const CGFunctionInfo &FI = 1373 CGF.CGM.getTypes().getFunctionInfo(R, args, FunctionType::ExtInfo()); 1374 1375 CodeGenTypes &Types = CGF.CGM.getTypes(); 1376 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false); 1377 1378 // FIXME: We'd like to put these into a mergable by content, with 1379 // internal linkage. 1380 llvm::Function *Fn = 1381 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage, 1382 "__Block_byref_object_dispose_", 1383 &CGF.CGM.getModule()); 1384 1385 IdentifierInfo *II 1386 = &Context.Idents.get("__Block_byref_object_dispose_"); 1387 1388 FunctionDecl *FD = FunctionDecl::Create(Context, 1389 Context.getTranslationUnitDecl(), 1390 SourceLocation(), 1391 SourceLocation(), II, R, 0, 1392 SC_Static, 1393 SC_None, 1394 false, true); 1395 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation()); 1396 1397 if (byrefInfo.needsDispose()) { 1398 llvm::Value *V = CGF.GetAddrOfLocalVar(&src); 1399 V = CGF.Builder.CreateLoad(V); 1400 V = CGF.Builder.CreateBitCast(V, byrefType.getPointerTo(0)); 1401 V = CGF.Builder.CreateStructGEP(V, 6, "x"); 1402 1403 byrefInfo.emitDispose(CGF, V); 1404 } 1405 1406 CGF.FinishFunction(); 1407 1408 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy); 1409 } 1410 1411 /// Build the dispose helper for a __block variable. 1412 static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM, 1413 const llvm::StructType &byrefType, 1414 CodeGenModule::ByrefHelpers &info) { 1415 CodeGenFunction CGF(CGM); 1416 return generateByrefDisposeHelper(CGF, byrefType, info); 1417 } 1418 1419 /// 1420 template <class T> static T *buildByrefHelpers(CodeGenModule &CGM, 1421 const llvm::StructType &byrefTy, 1422 T &byrefInfo) { 1423 // Increase the field's alignment to be at least pointer alignment, 1424 // since the layout of the byref struct will guarantee at least that. 1425 byrefInfo.Alignment = std::max(byrefInfo.Alignment, 1426 CharUnits::fromQuantity(CGM.PointerAlignInBytes)); 1427 1428 llvm::FoldingSetNodeID id; 1429 byrefInfo.Profile(id); 1430 1431 void *insertPos; 1432 CodeGenModule::ByrefHelpers *node 1433 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos); 1434 if (node) return static_cast<T*>(node); 1435 1436 byrefInfo.CopyHelper = buildByrefCopyHelper(CGM, byrefTy, byrefInfo); 1437 byrefInfo.DisposeHelper = buildByrefDisposeHelper(CGM, byrefTy, byrefInfo); 1438 1439 T *copy = new (CGM.getContext()) T(byrefInfo); 1440 CGM.ByrefHelpersCache.InsertNode(copy, insertPos); 1441 return copy; 1442 } 1443 1444 CodeGenModule::ByrefHelpers * 1445 CodeGenFunction::buildByrefHelpers(const llvm::StructType &byrefType, 1446 const AutoVarEmission &emission) { 1447 const VarDecl &var = *emission.Variable; 1448 QualType type = var.getType(); 1449 1450 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) { 1451 const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var); 1452 if (!copyExpr && record->hasTrivialDestructor()) return 0; 1453 1454 CXXByrefHelpers byrefInfo(emission.Alignment, type, copyExpr); 1455 return ::buildByrefHelpers(CGM, byrefType, byrefInfo); 1456 } 1457 1458 BlockFieldFlags flags; 1459 if (type->isBlockPointerType()) { 1460 flags |= BLOCK_FIELD_IS_BLOCK; 1461 } else if (CGM.getContext().isObjCNSObjectType(type) || 1462 type->isObjCObjectPointerType()) { 1463 flags |= BLOCK_FIELD_IS_OBJECT; 1464 } else { 1465 return 0; 1466 } 1467 1468 if (type.isObjCGCWeak()) 1469 flags |= BLOCK_FIELD_IS_WEAK; 1470 1471 ObjectByrefHelpers byrefInfo(emission.Alignment, flags); 1472 return ::buildByrefHelpers(CGM, byrefType, byrefInfo); 1473 } 1474 1475 unsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const { 1476 assert(ByRefValueInfo.count(VD) && "Did not find value!"); 1477 1478 return ByRefValueInfo.find(VD)->second.second; 1479 } 1480 1481 llvm::Value *CodeGenFunction::BuildBlockByrefAddress(llvm::Value *BaseAddr, 1482 const VarDecl *V) { 1483 llvm::Value *Loc = Builder.CreateStructGEP(BaseAddr, 1, "forwarding"); 1484 Loc = Builder.CreateLoad(Loc); 1485 Loc = Builder.CreateStructGEP(Loc, getByRefValueLLVMField(V), 1486 V->getNameAsString()); 1487 return Loc; 1488 } 1489 1490 /// BuildByRefType - This routine changes a __block variable declared as T x 1491 /// into: 1492 /// 1493 /// struct { 1494 /// void *__isa; 1495 /// void *__forwarding; 1496 /// int32_t __flags; 1497 /// int32_t __size; 1498 /// void *__copy_helper; // only if needed 1499 /// void *__destroy_helper; // only if needed 1500 /// char padding[X]; // only if needed 1501 /// T x; 1502 /// } x 1503 /// 1504 const llvm::Type *CodeGenFunction::BuildByRefType(const VarDecl *D) { 1505 std::pair<const llvm::Type *, unsigned> &Info = ByRefValueInfo[D]; 1506 if (Info.first) 1507 return Info.first; 1508 1509 QualType Ty = D->getType(); 1510 1511 std::vector<const llvm::Type *> Types; 1512 1513 llvm::PATypeHolder ByRefTypeHolder = llvm::OpaqueType::get(getLLVMContext()); 1514 1515 // void *__isa; 1516 Types.push_back(Int8PtrTy); 1517 1518 // void *__forwarding; 1519 Types.push_back(llvm::PointerType::getUnqual(ByRefTypeHolder)); 1520 1521 // int32_t __flags; 1522 Types.push_back(Int32Ty); 1523 1524 // int32_t __size; 1525 Types.push_back(Int32Ty); 1526 1527 bool HasCopyAndDispose = getContext().BlockRequiresCopying(Ty); 1528 if (HasCopyAndDispose) { 1529 /// void *__copy_helper; 1530 Types.push_back(Int8PtrTy); 1531 1532 /// void *__destroy_helper; 1533 Types.push_back(Int8PtrTy); 1534 } 1535 1536 bool Packed = false; 1537 CharUnits Align = getContext().getDeclAlign(D); 1538 if (Align > getContext().toCharUnitsFromBits(Target.getPointerAlign(0))) { 1539 // We have to insert padding. 1540 1541 // The struct above has 2 32-bit integers. 1542 unsigned CurrentOffsetInBytes = 4 * 2; 1543 1544 // And either 2 or 4 pointers. 1545 CurrentOffsetInBytes += (HasCopyAndDispose ? 4 : 2) * 1546 CGM.getTargetData().getTypeAllocSize(Int8PtrTy); 1547 1548 // Align the offset. 1549 unsigned AlignedOffsetInBytes = 1550 llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity()); 1551 1552 unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes; 1553 if (NumPaddingBytes > 0) { 1554 const llvm::Type *Ty = llvm::Type::getInt8Ty(getLLVMContext()); 1555 // FIXME: We need a sema error for alignment larger than the minimum of 1556 // the maximal stack alignmint and the alignment of malloc on the system. 1557 if (NumPaddingBytes > 1) 1558 Ty = llvm::ArrayType::get(Ty, NumPaddingBytes); 1559 1560 Types.push_back(Ty); 1561 1562 // We want a packed struct. 1563 Packed = true; 1564 } 1565 } 1566 1567 // T x; 1568 Types.push_back(ConvertTypeForMem(Ty)); 1569 1570 const llvm::Type *T = llvm::StructType::get(getLLVMContext(), Types, Packed); 1571 1572 cast<llvm::OpaqueType>(ByRefTypeHolder.get())->refineAbstractTypeTo(T); 1573 CGM.getModule().addTypeName("struct.__block_byref_" + D->getNameAsString(), 1574 ByRefTypeHolder.get()); 1575 1576 Info.first = ByRefTypeHolder.get(); 1577 1578 Info.second = Types.size() - 1; 1579 1580 return Info.first; 1581 } 1582 1583 /// Initialize the structural components of a __block variable, i.e. 1584 /// everything but the actual object. 1585 void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) { 1586 // Find the address of the local. 1587 llvm::Value *addr = emission.Address; 1588 1589 // That's an alloca of the byref structure type. 1590 const llvm::StructType *byrefType = cast<llvm::StructType>( 1591 cast<llvm::PointerType>(addr->getType())->getElementType()); 1592 1593 // Build the byref helpers if necessary. This is null if we don't need any. 1594 CodeGenModule::ByrefHelpers *helpers = 1595 buildByrefHelpers(*byrefType, emission); 1596 1597 const VarDecl &D = *emission.Variable; 1598 QualType type = D.getType(); 1599 1600 llvm::Value *V; 1601 1602 // Initialize the 'isa', which is just 0 or 1. 1603 int isa = 0; 1604 if (type.isObjCGCWeak()) 1605 isa = 1; 1606 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa"); 1607 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 0, "byref.isa")); 1608 1609 // Store the address of the variable into its own forwarding pointer. 1610 Builder.CreateStore(addr, 1611 Builder.CreateStructGEP(addr, 1, "byref.forwarding")); 1612 1613 // Blocks ABI: 1614 // c) the flags field is set to either 0 if no helper functions are 1615 // needed or BLOCK_HAS_COPY_DISPOSE if they are, 1616 BlockFlags flags; 1617 if (helpers) flags |= BLOCK_HAS_COPY_DISPOSE; 1618 Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()), 1619 Builder.CreateStructGEP(addr, 2, "byref.flags")); 1620 1621 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType); 1622 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity()); 1623 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 3, "byref.size")); 1624 1625 if (helpers) { 1626 llvm::Value *copy_helper = Builder.CreateStructGEP(addr, 4); 1627 Builder.CreateStore(helpers->CopyHelper, copy_helper); 1628 1629 llvm::Value *destroy_helper = Builder.CreateStructGEP(addr, 5); 1630 Builder.CreateStore(helpers->DisposeHelper, destroy_helper); 1631 } 1632 } 1633 1634 void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) { 1635 llvm::Value *F = CGM.getBlockObjectDispose(); 1636 llvm::Value *N; 1637 V = Builder.CreateBitCast(V, Int8PtrTy); 1638 N = llvm::ConstantInt::get(Int32Ty, flags.getBitMask()); 1639 Builder.CreateCall2(F, V, N); 1640 } 1641 1642 namespace { 1643 struct CallBlockRelease : EHScopeStack::Cleanup { 1644 llvm::Value *Addr; 1645 CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {} 1646 1647 void Emit(CodeGenFunction &CGF, bool IsForEH) { 1648 CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF); 1649 } 1650 }; 1651 } 1652 1653 /// Enter a cleanup to destroy a __block variable. Note that this 1654 /// cleanup should be a no-op if the variable hasn't left the stack 1655 /// yet; if a cleanup is required for the variable itself, that needs 1656 /// to be done externally. 1657 void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) { 1658 // We don't enter this cleanup if we're in pure-GC mode. 1659 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly) 1660 return; 1661 1662 EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup, emission.Address); 1663 } 1664