1 //===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===// 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 // Hacks and fun related to the code rewriter. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Rewrite/Frontend/ASTConsumers.h" 15 #include "clang/AST/AST.h" 16 #include "clang/AST/ASTConsumer.h" 17 #include "clang/AST/Attr.h" 18 #include "clang/AST/ParentMap.h" 19 #include "clang/Basic/CharInfo.h" 20 #include "clang/Basic/Diagnostic.h" 21 #include "clang/Basic/IdentifierTable.h" 22 #include "clang/Basic/SourceManager.h" 23 #include "clang/Basic/TargetInfo.h" 24 #include "clang/Lex/Lexer.h" 25 #include "clang/Rewrite/Core/Rewriter.h" 26 #include "llvm/ADT/DenseSet.h" 27 #include "llvm/ADT/SmallPtrSet.h" 28 #include "llvm/ADT/StringExtras.h" 29 #include "llvm/Support/MemoryBuffer.h" 30 #include "llvm/Support/raw_ostream.h" 31 #include <memory> 32 33 #ifdef CLANG_ENABLE_OBJC_REWRITER 34 35 using namespace clang; 36 using llvm::utostr; 37 38 namespace { 39 class RewriteModernObjC : public ASTConsumer { 40 protected: 41 42 enum { 43 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)), 44 block, ... */ 45 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */ 46 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the 47 __block variable */ 48 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy 49 helpers */ 50 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose 51 support routines */ 52 BLOCK_BYREF_CURRENT_MAX = 256 53 }; 54 55 enum { 56 BLOCK_NEEDS_FREE = (1 << 24), 57 BLOCK_HAS_COPY_DISPOSE = (1 << 25), 58 BLOCK_HAS_CXX_OBJ = (1 << 26), 59 BLOCK_IS_GC = (1 << 27), 60 BLOCK_IS_GLOBAL = (1 << 28), 61 BLOCK_HAS_DESCRIPTOR = (1 << 29) 62 }; 63 64 Rewriter Rewrite; 65 DiagnosticsEngine &Diags; 66 const LangOptions &LangOpts; 67 ASTContext *Context; 68 SourceManager *SM; 69 TranslationUnitDecl *TUDecl; 70 FileID MainFileID; 71 const char *MainFileStart, *MainFileEnd; 72 Stmt *CurrentBody; 73 ParentMap *PropParentMap; // created lazily. 74 std::string InFileName; 75 raw_ostream* OutFile; 76 std::string Preamble; 77 78 TypeDecl *ProtocolTypeDecl; 79 VarDecl *GlobalVarDecl; 80 Expr *GlobalConstructionExp; 81 unsigned RewriteFailedDiag; 82 unsigned GlobalBlockRewriteFailedDiag; 83 // ObjC string constant support. 84 unsigned NumObjCStringLiterals; 85 VarDecl *ConstantStringClassReference; 86 RecordDecl *NSStringRecord; 87 88 // ObjC foreach break/continue generation support. 89 int BcLabelCount; 90 91 unsigned TryFinallyContainsReturnDiag; 92 // Needed for super. 93 ObjCMethodDecl *CurMethodDef; 94 RecordDecl *SuperStructDecl; 95 RecordDecl *ConstantStringDecl; 96 97 FunctionDecl *MsgSendFunctionDecl; 98 FunctionDecl *MsgSendSuperFunctionDecl; 99 FunctionDecl *MsgSendStretFunctionDecl; 100 FunctionDecl *MsgSendSuperStretFunctionDecl; 101 FunctionDecl *MsgSendFpretFunctionDecl; 102 FunctionDecl *GetClassFunctionDecl; 103 FunctionDecl *GetMetaClassFunctionDecl; 104 FunctionDecl *GetSuperClassFunctionDecl; 105 FunctionDecl *SelGetUidFunctionDecl; 106 FunctionDecl *CFStringFunctionDecl; 107 FunctionDecl *SuperConstructorFunctionDecl; 108 FunctionDecl *CurFunctionDef; 109 110 /* Misc. containers needed for meta-data rewrite. */ 111 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation; 112 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation; 113 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs; 114 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols; 115 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces; 116 llvm::SmallPtrSet<TagDecl*, 32> GlobalDefinedTags; 117 SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen; 118 /// DefinedNonLazyClasses - List of defined "non-lazy" classes. 119 SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses; 120 121 /// DefinedNonLazyCategories - List of defined "non-lazy" categories. 122 SmallVector<ObjCCategoryDecl *, 8> DefinedNonLazyCategories; 123 124 SmallVector<Stmt *, 32> Stmts; 125 SmallVector<int, 8> ObjCBcLabelNo; 126 // Remember all the @protocol(<expr>) expressions. 127 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls; 128 129 llvm::DenseSet<uint64_t> CopyDestroyCache; 130 131 // Block expressions. 132 SmallVector<BlockExpr *, 32> Blocks; 133 SmallVector<int, 32> InnerDeclRefsCount; 134 SmallVector<DeclRefExpr *, 32> InnerDeclRefs; 135 136 SmallVector<DeclRefExpr *, 32> BlockDeclRefs; 137 138 139 // Block related declarations. 140 SmallVector<ValueDecl *, 8> BlockByCopyDecls; 141 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet; 142 SmallVector<ValueDecl *, 8> BlockByRefDecls; 143 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet; 144 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo; 145 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls; 146 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls; 147 148 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs; 149 llvm::DenseMap<ObjCInterfaceDecl *, 150 llvm::SmallPtrSet<ObjCIvarDecl *, 8> > ReferencedIvars; 151 152 // ivar bitfield grouping containers 153 llvm::DenseSet<const ObjCInterfaceDecl *> ObjCInterefaceHasBitfieldGroups; 154 llvm::DenseMap<const ObjCIvarDecl* , unsigned> IvarGroupNumber; 155 // This container maps an <class, group number for ivar> tuple to the type 156 // of the struct where the bitfield belongs. 157 llvm::DenseMap<std::pair<const ObjCInterfaceDecl*, unsigned>, QualType> GroupRecordType; 158 SmallVector<FunctionDecl*, 32> FunctionDefinitionsSeen; 159 160 // This maps an original source AST to it's rewritten form. This allows 161 // us to avoid rewriting the same node twice (which is very uncommon). 162 // This is needed to support some of the exotic property rewriting. 163 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes; 164 165 // Needed for header files being rewritten 166 bool IsHeader; 167 bool SilenceRewriteMacroWarning; 168 bool GenerateLineInfo; 169 bool objc_impl_method; 170 171 bool DisableReplaceStmt; 172 class DisableReplaceStmtScope { 173 RewriteModernObjC &R; 174 bool SavedValue; 175 176 public: 177 DisableReplaceStmtScope(RewriteModernObjC &R) 178 : R(R), SavedValue(R.DisableReplaceStmt) { 179 R.DisableReplaceStmt = true; 180 } 181 ~DisableReplaceStmtScope() { 182 R.DisableReplaceStmt = SavedValue; 183 } 184 }; 185 void InitializeCommon(ASTContext &context); 186 187 public: 188 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames; 189 // Top Level Driver code. 190 bool HandleTopLevelDecl(DeclGroupRef D) override { 191 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) { 192 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) { 193 if (!Class->isThisDeclarationADefinition()) { 194 RewriteForwardClassDecl(D); 195 break; 196 } else { 197 // Keep track of all interface declarations seen. 198 ObjCInterfacesSeen.push_back(Class); 199 break; 200 } 201 } 202 203 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) { 204 if (!Proto->isThisDeclarationADefinition()) { 205 RewriteForwardProtocolDecl(D); 206 break; 207 } 208 } 209 210 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(*I)) { 211 // Under modern abi, we cannot translate body of the function 212 // yet until all class extensions and its implementation is seen. 213 // This is because they may introduce new bitfields which must go 214 // into their grouping struct. 215 if (FDecl->isThisDeclarationADefinition() && 216 // Not c functions defined inside an objc container. 217 !FDecl->isTopLevelDeclInObjCContainer()) { 218 FunctionDefinitionsSeen.push_back(FDecl); 219 break; 220 } 221 } 222 HandleTopLevelSingleDecl(*I); 223 } 224 return true; 225 } 226 227 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override { 228 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) { 229 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(*I)) { 230 if (isTopLevelBlockPointerType(TD->getUnderlyingType())) 231 RewriteBlockPointerDecl(TD); 232 else if (TD->getUnderlyingType()->isFunctionPointerType()) 233 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD); 234 else 235 RewriteObjCQualifiedInterfaceTypes(TD); 236 } 237 } 238 return; 239 } 240 241 void HandleTopLevelSingleDecl(Decl *D); 242 void HandleDeclInMainFile(Decl *D); 243 RewriteModernObjC(std::string inFile, raw_ostream *OS, 244 DiagnosticsEngine &D, const LangOptions &LOpts, 245 bool silenceMacroWarn, bool LineInfo); 246 247 ~RewriteModernObjC() {} 248 249 void HandleTranslationUnit(ASTContext &C) override; 250 251 void ReplaceStmt(Stmt *Old, Stmt *New) { 252 ReplaceStmtWithRange(Old, New, Old->getSourceRange()); 253 } 254 255 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) { 256 assert(Old != nullptr && New != nullptr && "Expected non-null Stmt's"); 257 258 Stmt *ReplacingStmt = ReplacedNodes[Old]; 259 if (ReplacingStmt) 260 return; // We can't rewrite the same node twice. 261 262 if (DisableReplaceStmt) 263 return; 264 265 // Measure the old text. 266 int Size = Rewrite.getRangeSize(SrcRange); 267 if (Size == -1) { 268 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag) 269 << Old->getSourceRange(); 270 return; 271 } 272 // Get the new text. 273 std::string SStr; 274 llvm::raw_string_ostream S(SStr); 275 New->printPretty(S, nullptr, PrintingPolicy(LangOpts)); 276 const std::string &Str = S.str(); 277 278 // If replacement succeeded or warning disabled return with no warning. 279 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) { 280 ReplacedNodes[Old] = New; 281 return; 282 } 283 if (SilenceRewriteMacroWarning) 284 return; 285 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag) 286 << Old->getSourceRange(); 287 } 288 289 void InsertText(SourceLocation Loc, StringRef Str, 290 bool InsertAfter = true) { 291 // If insertion succeeded or warning disabled return with no warning. 292 if (!Rewrite.InsertText(Loc, Str, InsertAfter) || 293 SilenceRewriteMacroWarning) 294 return; 295 296 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag); 297 } 298 299 void ReplaceText(SourceLocation Start, unsigned OrigLength, 300 StringRef Str) { 301 // If removal succeeded or warning disabled return with no warning. 302 if (!Rewrite.ReplaceText(Start, OrigLength, Str) || 303 SilenceRewriteMacroWarning) 304 return; 305 306 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag); 307 } 308 309 // Syntactic Rewriting. 310 void RewriteRecordBody(RecordDecl *RD); 311 void RewriteInclude(); 312 void RewriteLineDirective(const Decl *D); 313 void ConvertSourceLocationToLineDirective(SourceLocation Loc, 314 std::string &LineString); 315 void RewriteForwardClassDecl(DeclGroupRef D); 316 void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG); 317 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl, 318 const std::string &typedefString); 319 void RewriteImplementations(); 320 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, 321 ObjCImplementationDecl *IMD, 322 ObjCCategoryImplDecl *CID); 323 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl); 324 void RewriteImplementationDecl(Decl *Dcl); 325 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl, 326 ObjCMethodDecl *MDecl, std::string &ResultStr); 327 void RewriteTypeIntoString(QualType T, std::string &ResultStr, 328 const FunctionType *&FPRetType); 329 void RewriteByRefString(std::string &ResultStr, const std::string &Name, 330 ValueDecl *VD, bool def=false); 331 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl); 332 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl); 333 void RewriteForwardProtocolDecl(DeclGroupRef D); 334 void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG); 335 void RewriteMethodDeclaration(ObjCMethodDecl *Method); 336 void RewriteProperty(ObjCPropertyDecl *prop); 337 void RewriteFunctionDecl(FunctionDecl *FD); 338 void RewriteBlockPointerType(std::string& Str, QualType Type); 339 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD); 340 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD); 341 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl); 342 void RewriteTypeOfDecl(VarDecl *VD); 343 void RewriteObjCQualifiedInterfaceTypes(Expr *E); 344 345 std::string getIvarAccessString(ObjCIvarDecl *D); 346 347 // Expression Rewriting. 348 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S); 349 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp); 350 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo); 351 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo); 352 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp); 353 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp); 354 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp); 355 Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp); 356 Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp); 357 Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp); 358 Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp); 359 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp); 360 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S); 361 Stmt *RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S); 362 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S); 363 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S); 364 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S, 365 SourceLocation OrigEnd); 366 Stmt *RewriteBreakStmt(BreakStmt *S); 367 Stmt *RewriteContinueStmt(ContinueStmt *S); 368 void RewriteCastExpr(CStyleCastExpr *CE); 369 void RewriteImplicitCastObjCExpr(CastExpr *IE); 370 void RewriteLinkageSpec(LinkageSpecDecl *LSD); 371 372 // Computes ivar bitfield group no. 373 unsigned ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV); 374 // Names field decl. for ivar bitfield group. 375 void ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV, std::string &Result); 376 // Names struct type for ivar bitfield group. 377 void ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV, std::string &Result); 378 // Names symbol for ivar bitfield group field offset. 379 void ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV, std::string &Result); 380 // Given an ivar bitfield, it builds (or finds) its group record type. 381 QualType GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV); 382 QualType SynthesizeBitfieldGroupStructType( 383 ObjCIvarDecl *IV, 384 SmallVectorImpl<ObjCIvarDecl *> &IVars); 385 386 // Block rewriting. 387 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D); 388 389 // Block specific rewrite rules. 390 void RewriteBlockPointerDecl(NamedDecl *VD); 391 void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl); 392 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD); 393 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE); 394 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD); 395 396 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl, 397 std::string &Result); 398 399 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result); 400 bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag, 401 bool &IsNamedDefinition); 402 void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl, 403 std::string &Result); 404 405 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result); 406 407 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl, 408 std::string &Result); 409 410 void Initialize(ASTContext &context) override; 411 412 // Misc. AST transformation routines. Sometimes they end up calling 413 // rewriting routines on the new ASTs. 414 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD, 415 Expr **args, unsigned nargs, 416 SourceLocation StartLoc=SourceLocation(), 417 SourceLocation EndLoc=SourceLocation()); 418 419 Expr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor, 420 QualType returnType, 421 SmallVectorImpl<QualType> &ArgTypes, 422 SmallVectorImpl<Expr*> &MsgExprs, 423 ObjCMethodDecl *Method); 424 425 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp, 426 SourceLocation StartLoc=SourceLocation(), 427 SourceLocation EndLoc=SourceLocation()); 428 429 void SynthCountByEnumWithState(std::string &buf); 430 void SynthMsgSendFunctionDecl(); 431 void SynthMsgSendSuperFunctionDecl(); 432 void SynthMsgSendStretFunctionDecl(); 433 void SynthMsgSendFpretFunctionDecl(); 434 void SynthMsgSendSuperStretFunctionDecl(); 435 void SynthGetClassFunctionDecl(); 436 void SynthGetMetaClassFunctionDecl(); 437 void SynthGetSuperClassFunctionDecl(); 438 void SynthSelGetUidFunctionDecl(); 439 void SynthSuperConstructorFunctionDecl(); 440 441 // Rewriting metadata 442 template<typename MethodIterator> 443 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin, 444 MethodIterator MethodEnd, 445 bool IsInstanceMethod, 446 StringRef prefix, 447 StringRef ClassName, 448 std::string &Result); 449 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol, 450 std::string &Result); 451 void RewriteObjCProtocolListMetaData( 452 const ObjCList<ObjCProtocolDecl> &Prots, 453 StringRef prefix, StringRef ClassName, std::string &Result); 454 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl, 455 std::string &Result); 456 void RewriteClassSetupInitHook(std::string &Result); 457 458 void RewriteMetaDataIntoBuffer(std::string &Result); 459 void WriteImageInfo(std::string &Result); 460 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl, 461 std::string &Result); 462 void RewriteCategorySetupInitHook(std::string &Result); 463 464 // Rewriting ivar 465 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar, 466 std::string &Result); 467 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV); 468 469 470 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag); 471 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i, 472 StringRef funcName, std::string Tag); 473 std::string SynthesizeBlockFunc(BlockExpr *CE, int i, 474 StringRef funcName, std::string Tag); 475 std::string SynthesizeBlockImpl(BlockExpr *CE, 476 std::string Tag, std::string Desc); 477 std::string SynthesizeBlockDescriptor(std::string DescTag, 478 std::string ImplTag, 479 int i, StringRef funcName, 480 unsigned hasCopy); 481 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp); 482 void SynthesizeBlockLiterals(SourceLocation FunLocStart, 483 StringRef FunName); 484 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name); 485 Stmt *SynthBlockInitExpr(BlockExpr *Exp, 486 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs); 487 488 // Misc. helper routines. 489 QualType getProtocolType(); 490 void WarnAboutReturnGotoStmts(Stmt *S); 491 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND); 492 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD); 493 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD); 494 495 bool IsDeclStmtInForeachHeader(DeclStmt *DS); 496 void CollectBlockDeclRefInfo(BlockExpr *Exp); 497 void GetBlockDeclRefExprs(Stmt *S); 498 void GetInnerBlockDeclRefExprs(Stmt *S, 499 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs, 500 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts); 501 502 // We avoid calling Type::isBlockPointerType(), since it operates on the 503 // canonical type. We only care if the top-level type is a closure pointer. 504 bool isTopLevelBlockPointerType(QualType T) { 505 return isa<BlockPointerType>(T); 506 } 507 508 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type 509 /// to a function pointer type and upon success, returns true; false 510 /// otherwise. 511 bool convertBlockPointerToFunctionPointer(QualType &T) { 512 if (isTopLevelBlockPointerType(T)) { 513 const BlockPointerType *BPT = T->getAs<BlockPointerType>(); 514 T = Context->getPointerType(BPT->getPointeeType()); 515 return true; 516 } 517 return false; 518 } 519 520 bool convertObjCTypeToCStyleType(QualType &T); 521 522 bool needToScanForQualifiers(QualType T); 523 QualType getSuperStructType(); 524 QualType getConstantStringStructType(); 525 QualType convertFunctionTypeOfBlocks(const FunctionType *FT); 526 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf); 527 528 void convertToUnqualifiedObjCType(QualType &T) { 529 if (T->isObjCQualifiedIdType()) { 530 bool isConst = T.isConstQualified(); 531 T = isConst ? Context->getObjCIdType().withConst() 532 : Context->getObjCIdType(); 533 } 534 else if (T->isObjCQualifiedClassType()) 535 T = Context->getObjCClassType(); 536 else if (T->isObjCObjectPointerType() && 537 T->getPointeeType()->isObjCQualifiedInterfaceType()) { 538 if (const ObjCObjectPointerType * OBJPT = 539 T->getAsObjCInterfacePointerType()) { 540 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType(); 541 T = QualType(IFaceT, 0); 542 T = Context->getPointerType(T); 543 } 544 } 545 } 546 547 // FIXME: This predicate seems like it would be useful to add to ASTContext. 548 bool isObjCType(QualType T) { 549 if (!LangOpts.ObjC1 && !LangOpts.ObjC2) 550 return false; 551 552 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType(); 553 554 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) || 555 OCT == Context->getCanonicalType(Context->getObjCClassType())) 556 return true; 557 558 if (const PointerType *PT = OCT->getAs<PointerType>()) { 559 if (isa<ObjCInterfaceType>(PT->getPointeeType()) || 560 PT->getPointeeType()->isObjCQualifiedIdType()) 561 return true; 562 } 563 return false; 564 } 565 bool PointerTypeTakesAnyBlockArguments(QualType QT); 566 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT); 567 void GetExtentOfArgList(const char *Name, const char *&LParen, 568 const char *&RParen); 569 570 void QuoteDoublequotes(std::string &From, std::string &To) { 571 for (unsigned i = 0; i < From.length(); i++) { 572 if (From[i] == '"') 573 To += "\\\""; 574 else 575 To += From[i]; 576 } 577 } 578 579 QualType getSimpleFunctionType(QualType result, 580 ArrayRef<QualType> args, 581 bool variadic = false) { 582 if (result == Context->getObjCInstanceType()) 583 result = Context->getObjCIdType(); 584 FunctionProtoType::ExtProtoInfo fpi; 585 fpi.Variadic = variadic; 586 return Context->getFunctionType(result, args, fpi); 587 } 588 589 // Helper function: create a CStyleCastExpr with trivial type source info. 590 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty, 591 CastKind Kind, Expr *E) { 592 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation()); 593 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, nullptr, 594 TInfo, SourceLocation(), SourceLocation()); 595 } 596 597 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const { 598 IdentifierInfo* II = &Context->Idents.get("load"); 599 Selector LoadSel = Context->Selectors.getSelector(0, &II); 600 return OD->getClassMethod(LoadSel) != nullptr; 601 } 602 603 StringLiteral *getStringLiteral(StringRef Str) { 604 QualType StrType = Context->getConstantArrayType( 605 Context->CharTy, llvm::APInt(32, Str.size() + 1), ArrayType::Normal, 606 0); 607 return StringLiteral::Create(*Context, Str, StringLiteral::Ascii, 608 /*Pascal=*/false, StrType, SourceLocation()); 609 } 610 }; 611 612 } 613 614 void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType, 615 NamedDecl *D) { 616 if (const FunctionProtoType *fproto 617 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) { 618 for (const auto &I : fproto->param_types()) 619 if (isTopLevelBlockPointerType(I)) { 620 // All the args are checked/rewritten. Don't call twice! 621 RewriteBlockPointerDecl(D); 622 break; 623 } 624 } 625 } 626 627 void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) { 628 const PointerType *PT = funcType->getAs<PointerType>(); 629 if (PT && PointerTypeTakesAnyBlockArguments(funcType)) 630 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND); 631 } 632 633 static bool IsHeaderFile(const std::string &Filename) { 634 std::string::size_type DotPos = Filename.rfind('.'); 635 636 if (DotPos == std::string::npos) { 637 // no file extension 638 return false; 639 } 640 641 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end()); 642 // C header: .h 643 // C++ header: .hh or .H; 644 return Ext == "h" || Ext == "hh" || Ext == "H"; 645 } 646 647 RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS, 648 DiagnosticsEngine &D, const LangOptions &LOpts, 649 bool silenceMacroWarn, 650 bool LineInfo) 651 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS), 652 SilenceRewriteMacroWarning(silenceMacroWarn), GenerateLineInfo(LineInfo) { 653 IsHeader = IsHeaderFile(inFile); 654 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning, 655 "rewriting sub-expression within a macro (may not be correct)"); 656 // FIXME. This should be an error. But if block is not called, it is OK. And it 657 // may break including some headers. 658 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning, 659 "rewriting block literal declared in global scope is not implemented"); 660 661 TryFinallyContainsReturnDiag = Diags.getCustomDiagID( 662 DiagnosticsEngine::Warning, 663 "rewriter doesn't support user-specified control flow semantics " 664 "for @try/@finally (code may not execute properly)"); 665 } 666 667 std::unique_ptr<ASTConsumer> clang::CreateModernObjCRewriter( 668 const std::string &InFile, raw_ostream *OS, DiagnosticsEngine &Diags, 669 const LangOptions &LOpts, bool SilenceRewriteMacroWarning, bool LineInfo) { 670 return llvm::make_unique<RewriteModernObjC>( 671 InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning, LineInfo); 672 } 673 674 void RewriteModernObjC::InitializeCommon(ASTContext &context) { 675 Context = &context; 676 SM = &Context->getSourceManager(); 677 TUDecl = Context->getTranslationUnitDecl(); 678 MsgSendFunctionDecl = nullptr; 679 MsgSendSuperFunctionDecl = nullptr; 680 MsgSendStretFunctionDecl = nullptr; 681 MsgSendSuperStretFunctionDecl = nullptr; 682 MsgSendFpretFunctionDecl = nullptr; 683 GetClassFunctionDecl = nullptr; 684 GetMetaClassFunctionDecl = nullptr; 685 GetSuperClassFunctionDecl = nullptr; 686 SelGetUidFunctionDecl = nullptr; 687 CFStringFunctionDecl = nullptr; 688 ConstantStringClassReference = nullptr; 689 NSStringRecord = nullptr; 690 CurMethodDef = nullptr; 691 CurFunctionDef = nullptr; 692 GlobalVarDecl = nullptr; 693 GlobalConstructionExp = nullptr; 694 SuperStructDecl = nullptr; 695 ProtocolTypeDecl = nullptr; 696 ConstantStringDecl = nullptr; 697 BcLabelCount = 0; 698 SuperConstructorFunctionDecl = nullptr; 699 NumObjCStringLiterals = 0; 700 PropParentMap = nullptr; 701 CurrentBody = nullptr; 702 DisableReplaceStmt = false; 703 objc_impl_method = false; 704 705 // Get the ID and start/end of the main file. 706 MainFileID = SM->getMainFileID(); 707 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID); 708 MainFileStart = MainBuf->getBufferStart(); 709 MainFileEnd = MainBuf->getBufferEnd(); 710 711 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts()); 712 } 713 714 //===----------------------------------------------------------------------===// 715 // Top Level Driver Code 716 //===----------------------------------------------------------------------===// 717 718 void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) { 719 if (Diags.hasErrorOccurred()) 720 return; 721 722 // Two cases: either the decl could be in the main file, or it could be in a 723 // #included file. If the former, rewrite it now. If the later, check to see 724 // if we rewrote the #include/#import. 725 SourceLocation Loc = D->getLocation(); 726 Loc = SM->getExpansionLoc(Loc); 727 728 // If this is for a builtin, ignore it. 729 if (Loc.isInvalid()) return; 730 731 // Look for built-in declarations that we need to refer during the rewrite. 732 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 733 RewriteFunctionDecl(FD); 734 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) { 735 // declared in <Foundation/NSString.h> 736 if (FVD->getName() == "_NSConstantStringClassReference") { 737 ConstantStringClassReference = FVD; 738 return; 739 } 740 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) { 741 RewriteCategoryDecl(CD); 742 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) { 743 if (PD->isThisDeclarationADefinition()) 744 RewriteProtocolDecl(PD); 745 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) { 746 // FIXME. This will not work in all situations and leaving it out 747 // is harmless. 748 // RewriteLinkageSpec(LSD); 749 750 // Recurse into linkage specifications 751 for (DeclContext::decl_iterator DI = LSD->decls_begin(), 752 DIEnd = LSD->decls_end(); 753 DI != DIEnd; ) { 754 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) { 755 if (!IFace->isThisDeclarationADefinition()) { 756 SmallVector<Decl *, 8> DG; 757 SourceLocation StartLoc = IFace->getLocStart(); 758 do { 759 if (isa<ObjCInterfaceDecl>(*DI) && 760 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() && 761 StartLoc == (*DI)->getLocStart()) 762 DG.push_back(*DI); 763 else 764 break; 765 766 ++DI; 767 } while (DI != DIEnd); 768 RewriteForwardClassDecl(DG); 769 continue; 770 } 771 else { 772 // Keep track of all interface declarations seen. 773 ObjCInterfacesSeen.push_back(IFace); 774 ++DI; 775 continue; 776 } 777 } 778 779 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) { 780 if (!Proto->isThisDeclarationADefinition()) { 781 SmallVector<Decl *, 8> DG; 782 SourceLocation StartLoc = Proto->getLocStart(); 783 do { 784 if (isa<ObjCProtocolDecl>(*DI) && 785 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() && 786 StartLoc == (*DI)->getLocStart()) 787 DG.push_back(*DI); 788 else 789 break; 790 791 ++DI; 792 } while (DI != DIEnd); 793 RewriteForwardProtocolDecl(DG); 794 continue; 795 } 796 } 797 798 HandleTopLevelSingleDecl(*DI); 799 ++DI; 800 } 801 } 802 // If we have a decl in the main file, see if we should rewrite it. 803 if (SM->isWrittenInMainFile(Loc)) 804 return HandleDeclInMainFile(D); 805 } 806 807 //===----------------------------------------------------------------------===// 808 // Syntactic (non-AST) Rewriting Code 809 //===----------------------------------------------------------------------===// 810 811 void RewriteModernObjC::RewriteInclude() { 812 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID); 813 StringRef MainBuf = SM->getBufferData(MainFileID); 814 const char *MainBufStart = MainBuf.begin(); 815 const char *MainBufEnd = MainBuf.end(); 816 size_t ImportLen = strlen("import"); 817 818 // Loop over the whole file, looking for includes. 819 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) { 820 if (*BufPtr == '#') { 821 if (++BufPtr == MainBufEnd) 822 return; 823 while (*BufPtr == ' ' || *BufPtr == '\t') 824 if (++BufPtr == MainBufEnd) 825 return; 826 if (!strncmp(BufPtr, "import", ImportLen)) { 827 // replace import with include 828 SourceLocation ImportLoc = 829 LocStart.getLocWithOffset(BufPtr-MainBufStart); 830 ReplaceText(ImportLoc, ImportLen, "include"); 831 BufPtr += ImportLen; 832 } 833 } 834 } 835 } 836 837 static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl, 838 ObjCIvarDecl *IvarDecl, std::string &Result) { 839 Result += "OBJC_IVAR_$_"; 840 Result += IDecl->getName(); 841 Result += "$"; 842 Result += IvarDecl->getName(); 843 } 844 845 std::string 846 RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) { 847 const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface(); 848 849 // Build name of symbol holding ivar offset. 850 std::string IvarOffsetName; 851 if (D->isBitField()) 852 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName); 853 else 854 WriteInternalIvarName(ClassDecl, D, IvarOffsetName); 855 856 857 std::string S = "(*("; 858 QualType IvarT = D->getType(); 859 if (D->isBitField()) 860 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D); 861 862 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) { 863 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl(); 864 RD = RD->getDefinition(); 865 if (RD && !RD->getDeclName().getAsIdentifierInfo()) { 866 // decltype(((Foo_IMPL*)0)->bar) * 867 ObjCContainerDecl *CDecl = 868 dyn_cast<ObjCContainerDecl>(D->getDeclContext()); 869 // ivar in class extensions requires special treatment. 870 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl)) 871 CDecl = CatDecl->getClassInterface(); 872 std::string RecName = CDecl->getName(); 873 RecName += "_IMPL"; 874 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl, 875 SourceLocation(), SourceLocation(), 876 &Context->Idents.get(RecName.c_str())); 877 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD)); 878 unsigned UnsignedIntSize = 879 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy)); 880 Expr *Zero = IntegerLiteral::Create(*Context, 881 llvm::APInt(UnsignedIntSize, 0), 882 Context->UnsignedIntTy, SourceLocation()); 883 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero); 884 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), 885 Zero); 886 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), 887 SourceLocation(), 888 &Context->Idents.get(D->getNameAsString()), 889 IvarT, nullptr, 890 /*BitWidth=*/nullptr, /*Mutable=*/true, 891 ICIS_NoInit); 892 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(), 893 FD->getType(), VK_LValue, 894 OK_Ordinary); 895 IvarT = Context->getDecltypeType(ME, ME->getType()); 896 } 897 } 898 convertObjCTypeToCStyleType(IvarT); 899 QualType castT = Context->getPointerType(IvarT); 900 std::string TypeString(castT.getAsString(Context->getPrintingPolicy())); 901 S += TypeString; 902 S += ")"; 903 904 // ((char *)self + IVAR_OFFSET_SYMBOL_NAME) 905 S += "((char *)self + "; 906 S += IvarOffsetName; 907 S += "))"; 908 if (D->isBitField()) { 909 S += "."; 910 S += D->getNameAsString(); 911 } 912 ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D); 913 return S; 914 } 915 916 /// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not 917 /// been found in the class implementation. In this case, it must be synthesized. 918 static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP, 919 ObjCPropertyDecl *PD, 920 bool getter) { 921 return getter ? !IMP->getInstanceMethod(PD->getGetterName()) 922 : !IMP->getInstanceMethod(PD->getSetterName()); 923 924 } 925 926 void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, 927 ObjCImplementationDecl *IMD, 928 ObjCCategoryImplDecl *CID) { 929 static bool objcGetPropertyDefined = false; 930 static bool objcSetPropertyDefined = false; 931 SourceLocation startGetterSetterLoc; 932 933 if (PID->getLocStart().isValid()) { 934 SourceLocation startLoc = PID->getLocStart(); 935 InsertText(startLoc, "// "); 936 const char *startBuf = SM->getCharacterData(startLoc); 937 assert((*startBuf == '@') && "bogus @synthesize location"); 938 const char *semiBuf = strchr(startBuf, ';'); 939 assert((*semiBuf == ';') && "@synthesize: can't find ';'"); 940 startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1); 941 } 942 else 943 startGetterSetterLoc = IMD ? IMD->getLocEnd() : CID->getLocEnd(); 944 945 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic) 946 return; // FIXME: is this correct? 947 948 // Generate the 'getter' function. 949 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 950 ObjCIvarDecl *OID = PID->getPropertyIvarDecl(); 951 assert(IMD && OID && "Synthesized ivars must be attached to @implementation"); 952 953 unsigned Attributes = PD->getPropertyAttributes(); 954 if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) { 955 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) && 956 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain | 957 ObjCPropertyDecl::OBJC_PR_copy)); 958 std::string Getr; 959 if (GenGetProperty && !objcGetPropertyDefined) { 960 objcGetPropertyDefined = true; 961 // FIXME. Is this attribute correct in all cases? 962 Getr = "\nextern \"C\" __declspec(dllimport) " 963 "id objc_getProperty(id, SEL, long, bool);\n"; 964 } 965 RewriteObjCMethodDecl(OID->getContainingInterface(), 966 PD->getGetterMethodDecl(), Getr); 967 Getr += "{ "; 968 // Synthesize an explicit cast to gain access to the ivar. 969 // See objc-act.c:objc_synthesize_new_getter() for details. 970 if (GenGetProperty) { 971 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1) 972 Getr += "typedef "; 973 const FunctionType *FPRetType = nullptr; 974 RewriteTypeIntoString(PD->getGetterMethodDecl()->getReturnType(), Getr, 975 FPRetType); 976 Getr += " _TYPE"; 977 if (FPRetType) { 978 Getr += ")"; // close the precedence "scope" for "*". 979 980 // Now, emit the argument types (if any). 981 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){ 982 Getr += "("; 983 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 984 if (i) Getr += ", "; 985 std::string ParamStr = 986 FT->getParamType(i).getAsString(Context->getPrintingPolicy()); 987 Getr += ParamStr; 988 } 989 if (FT->isVariadic()) { 990 if (FT->getNumParams()) 991 Getr += ", "; 992 Getr += "..."; 993 } 994 Getr += ")"; 995 } else 996 Getr += "()"; 997 } 998 Getr += ";\n"; 999 Getr += "return (_TYPE)"; 1000 Getr += "objc_getProperty(self, _cmd, "; 1001 RewriteIvarOffsetComputation(OID, Getr); 1002 Getr += ", 1)"; 1003 } 1004 else 1005 Getr += "return " + getIvarAccessString(OID); 1006 Getr += "; }"; 1007 InsertText(startGetterSetterLoc, Getr); 1008 } 1009 1010 if (PD->isReadOnly() || 1011 !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/)) 1012 return; 1013 1014 // Generate the 'setter' function. 1015 std::string Setr; 1016 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain | 1017 ObjCPropertyDecl::OBJC_PR_copy); 1018 if (GenSetProperty && !objcSetPropertyDefined) { 1019 objcSetPropertyDefined = true; 1020 // FIXME. Is this attribute correct in all cases? 1021 Setr = "\nextern \"C\" __declspec(dllimport) " 1022 "void objc_setProperty (id, SEL, long, id, bool, bool);\n"; 1023 } 1024 1025 RewriteObjCMethodDecl(OID->getContainingInterface(), 1026 PD->getSetterMethodDecl(), Setr); 1027 Setr += "{ "; 1028 // Synthesize an explicit cast to initialize the ivar. 1029 // See objc-act.c:objc_synthesize_new_setter() for details. 1030 if (GenSetProperty) { 1031 Setr += "objc_setProperty (self, _cmd, "; 1032 RewriteIvarOffsetComputation(OID, Setr); 1033 Setr += ", (id)"; 1034 Setr += PD->getName(); 1035 Setr += ", "; 1036 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) 1037 Setr += "0, "; 1038 else 1039 Setr += "1, "; 1040 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy) 1041 Setr += "1)"; 1042 else 1043 Setr += "0)"; 1044 } 1045 else { 1046 Setr += getIvarAccessString(OID) + " = "; 1047 Setr += PD->getName(); 1048 } 1049 Setr += "; }\n"; 1050 InsertText(startGetterSetterLoc, Setr); 1051 } 1052 1053 static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl, 1054 std::string &typedefString) { 1055 typedefString += "\n#ifndef _REWRITER_typedef_"; 1056 typedefString += ForwardDecl->getNameAsString(); 1057 typedefString += "\n"; 1058 typedefString += "#define _REWRITER_typedef_"; 1059 typedefString += ForwardDecl->getNameAsString(); 1060 typedefString += "\n"; 1061 typedefString += "typedef struct objc_object "; 1062 typedefString += ForwardDecl->getNameAsString(); 1063 // typedef struct { } _objc_exc_Classname; 1064 typedefString += ";\ntypedef struct {} _objc_exc_"; 1065 typedefString += ForwardDecl->getNameAsString(); 1066 typedefString += ";\n#endif\n"; 1067 } 1068 1069 void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl, 1070 const std::string &typedefString) { 1071 SourceLocation startLoc = ClassDecl->getLocStart(); 1072 const char *startBuf = SM->getCharacterData(startLoc); 1073 const char *semiPtr = strchr(startBuf, ';'); 1074 // Replace the @class with typedefs corresponding to the classes. 1075 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString); 1076 } 1077 1078 void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) { 1079 std::string typedefString; 1080 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) { 1081 if (ObjCInterfaceDecl *ForwardDecl = dyn_cast<ObjCInterfaceDecl>(*I)) { 1082 if (I == D.begin()) { 1083 // Translate to typedef's that forward reference structs with the same name 1084 // as the class. As a convenience, we include the original declaration 1085 // as a comment. 1086 typedefString += "// @class "; 1087 typedefString += ForwardDecl->getNameAsString(); 1088 typedefString += ";"; 1089 } 1090 RewriteOneForwardClassDecl(ForwardDecl, typedefString); 1091 } 1092 else 1093 HandleTopLevelSingleDecl(*I); 1094 } 1095 DeclGroupRef::iterator I = D.begin(); 1096 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString); 1097 } 1098 1099 void RewriteModernObjC::RewriteForwardClassDecl( 1100 const SmallVectorImpl<Decl *> &D) { 1101 std::string typedefString; 1102 for (unsigned i = 0; i < D.size(); i++) { 1103 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]); 1104 if (i == 0) { 1105 typedefString += "// @class "; 1106 typedefString += ForwardDecl->getNameAsString(); 1107 typedefString += ";"; 1108 } 1109 RewriteOneForwardClassDecl(ForwardDecl, typedefString); 1110 } 1111 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString); 1112 } 1113 1114 void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) { 1115 // When method is a synthesized one, such as a getter/setter there is 1116 // nothing to rewrite. 1117 if (Method->isImplicit()) 1118 return; 1119 SourceLocation LocStart = Method->getLocStart(); 1120 SourceLocation LocEnd = Method->getLocEnd(); 1121 1122 if (SM->getExpansionLineNumber(LocEnd) > 1123 SM->getExpansionLineNumber(LocStart)) { 1124 InsertText(LocStart, "#if 0\n"); 1125 ReplaceText(LocEnd, 1, ";\n#endif\n"); 1126 } else { 1127 InsertText(LocStart, "// "); 1128 } 1129 } 1130 1131 void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) { 1132 SourceLocation Loc = prop->getAtLoc(); 1133 1134 ReplaceText(Loc, 0, "// "); 1135 // FIXME: handle properties that are declared across multiple lines. 1136 } 1137 1138 void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) { 1139 SourceLocation LocStart = CatDecl->getLocStart(); 1140 1141 // FIXME: handle category headers that are declared across multiple lines. 1142 if (CatDecl->getIvarRBraceLoc().isValid()) { 1143 ReplaceText(LocStart, 1, "/** "); 1144 ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ "); 1145 } 1146 else { 1147 ReplaceText(LocStart, 0, "// "); 1148 } 1149 1150 for (auto *I : CatDecl->properties()) 1151 RewriteProperty(I); 1152 1153 for (auto *I : CatDecl->instance_methods()) 1154 RewriteMethodDeclaration(I); 1155 for (auto *I : CatDecl->class_methods()) 1156 RewriteMethodDeclaration(I); 1157 1158 // Lastly, comment out the @end. 1159 ReplaceText(CatDecl->getAtEndRange().getBegin(), 1160 strlen("@end"), "/* @end */\n"); 1161 } 1162 1163 void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) { 1164 SourceLocation LocStart = PDecl->getLocStart(); 1165 assert(PDecl->isThisDeclarationADefinition()); 1166 1167 // FIXME: handle protocol headers that are declared across multiple lines. 1168 ReplaceText(LocStart, 0, "// "); 1169 1170 for (auto *I : PDecl->instance_methods()) 1171 RewriteMethodDeclaration(I); 1172 for (auto *I : PDecl->class_methods()) 1173 RewriteMethodDeclaration(I); 1174 for (auto *I : PDecl->properties()) 1175 RewriteProperty(I); 1176 1177 // Lastly, comment out the @end. 1178 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin(); 1179 ReplaceText(LocEnd, strlen("@end"), "/* @end */\n"); 1180 1181 // Must comment out @optional/@required 1182 const char *startBuf = SM->getCharacterData(LocStart); 1183 const char *endBuf = SM->getCharacterData(LocEnd); 1184 for (const char *p = startBuf; p < endBuf; p++) { 1185 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) { 1186 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf); 1187 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */"); 1188 1189 } 1190 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) { 1191 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf); 1192 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */"); 1193 1194 } 1195 } 1196 } 1197 1198 void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) { 1199 SourceLocation LocStart = (*D.begin())->getLocStart(); 1200 if (LocStart.isInvalid()) 1201 llvm_unreachable("Invalid SourceLocation"); 1202 // FIXME: handle forward protocol that are declared across multiple lines. 1203 ReplaceText(LocStart, 0, "// "); 1204 } 1205 1206 void 1207 RewriteModernObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) { 1208 SourceLocation LocStart = DG[0]->getLocStart(); 1209 if (LocStart.isInvalid()) 1210 llvm_unreachable("Invalid SourceLocation"); 1211 // FIXME: handle forward protocol that are declared across multiple lines. 1212 ReplaceText(LocStart, 0, "// "); 1213 } 1214 1215 void 1216 RewriteModernObjC::RewriteLinkageSpec(LinkageSpecDecl *LSD) { 1217 SourceLocation LocStart = LSD->getExternLoc(); 1218 if (LocStart.isInvalid()) 1219 llvm_unreachable("Invalid extern SourceLocation"); 1220 1221 ReplaceText(LocStart, 0, "// "); 1222 if (!LSD->hasBraces()) 1223 return; 1224 // FIXME. We don't rewrite well if '{' is not on same line as 'extern'. 1225 SourceLocation LocRBrace = LSD->getRBraceLoc(); 1226 if (LocRBrace.isInvalid()) 1227 llvm_unreachable("Invalid rbrace SourceLocation"); 1228 ReplaceText(LocRBrace, 0, "// "); 1229 } 1230 1231 void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr, 1232 const FunctionType *&FPRetType) { 1233 if (T->isObjCQualifiedIdType()) 1234 ResultStr += "id"; 1235 else if (T->isFunctionPointerType() || 1236 T->isBlockPointerType()) { 1237 // needs special handling, since pointer-to-functions have special 1238 // syntax (where a decaration models use). 1239 QualType retType = T; 1240 QualType PointeeTy; 1241 if (const PointerType* PT = retType->getAs<PointerType>()) 1242 PointeeTy = PT->getPointeeType(); 1243 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>()) 1244 PointeeTy = BPT->getPointeeType(); 1245 if ((FPRetType = PointeeTy->getAs<FunctionType>())) { 1246 ResultStr += 1247 FPRetType->getReturnType().getAsString(Context->getPrintingPolicy()); 1248 ResultStr += "(*"; 1249 } 1250 } else 1251 ResultStr += T.getAsString(Context->getPrintingPolicy()); 1252 } 1253 1254 void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl, 1255 ObjCMethodDecl *OMD, 1256 std::string &ResultStr) { 1257 //fprintf(stderr,"In RewriteObjCMethodDecl\n"); 1258 const FunctionType *FPRetType = nullptr; 1259 ResultStr += "\nstatic "; 1260 RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType); 1261 ResultStr += " "; 1262 1263 // Unique method name 1264 std::string NameStr; 1265 1266 if (OMD->isInstanceMethod()) 1267 NameStr += "_I_"; 1268 else 1269 NameStr += "_C_"; 1270 1271 NameStr += IDecl->getNameAsString(); 1272 NameStr += "_"; 1273 1274 if (ObjCCategoryImplDecl *CID = 1275 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) { 1276 NameStr += CID->getNameAsString(); 1277 NameStr += "_"; 1278 } 1279 // Append selector names, replacing ':' with '_' 1280 { 1281 std::string selString = OMD->getSelector().getAsString(); 1282 int len = selString.size(); 1283 for (int i = 0; i < len; i++) 1284 if (selString[i] == ':') 1285 selString[i] = '_'; 1286 NameStr += selString; 1287 } 1288 // Remember this name for metadata emission 1289 MethodInternalNames[OMD] = NameStr; 1290 ResultStr += NameStr; 1291 1292 // Rewrite arguments 1293 ResultStr += "("; 1294 1295 // invisible arguments 1296 if (OMD->isInstanceMethod()) { 1297 QualType selfTy = Context->getObjCInterfaceType(IDecl); 1298 selfTy = Context->getPointerType(selfTy); 1299 if (!LangOpts.MicrosoftExt) { 1300 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl))) 1301 ResultStr += "struct "; 1302 } 1303 // When rewriting for Microsoft, explicitly omit the structure name. 1304 ResultStr += IDecl->getNameAsString(); 1305 ResultStr += " *"; 1306 } 1307 else 1308 ResultStr += Context->getObjCClassType().getAsString( 1309 Context->getPrintingPolicy()); 1310 1311 ResultStr += " self, "; 1312 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy()); 1313 ResultStr += " _cmd"; 1314 1315 // Method arguments. 1316 for (const auto *PDecl : OMD->params()) { 1317 ResultStr += ", "; 1318 if (PDecl->getType()->isObjCQualifiedIdType()) { 1319 ResultStr += "id "; 1320 ResultStr += PDecl->getNameAsString(); 1321 } else { 1322 std::string Name = PDecl->getNameAsString(); 1323 QualType QT = PDecl->getType(); 1324 // Make sure we convert "t (^)(...)" to "t (*)(...)". 1325 (void)convertBlockPointerToFunctionPointer(QT); 1326 QT.getAsStringInternal(Name, Context->getPrintingPolicy()); 1327 ResultStr += Name; 1328 } 1329 } 1330 if (OMD->isVariadic()) 1331 ResultStr += ", ..."; 1332 ResultStr += ") "; 1333 1334 if (FPRetType) { 1335 ResultStr += ")"; // close the precedence "scope" for "*". 1336 1337 // Now, emit the argument types (if any). 1338 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) { 1339 ResultStr += "("; 1340 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 1341 if (i) ResultStr += ", "; 1342 std::string ParamStr = 1343 FT->getParamType(i).getAsString(Context->getPrintingPolicy()); 1344 ResultStr += ParamStr; 1345 } 1346 if (FT->isVariadic()) { 1347 if (FT->getNumParams()) 1348 ResultStr += ", "; 1349 ResultStr += "..."; 1350 } 1351 ResultStr += ")"; 1352 } else { 1353 ResultStr += "()"; 1354 } 1355 } 1356 } 1357 void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) { 1358 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID); 1359 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID); 1360 1361 if (IMD) { 1362 if (IMD->getIvarRBraceLoc().isValid()) { 1363 ReplaceText(IMD->getLocStart(), 1, "/** "); 1364 ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ "); 1365 } 1366 else { 1367 InsertText(IMD->getLocStart(), "// "); 1368 } 1369 } 1370 else 1371 InsertText(CID->getLocStart(), "// "); 1372 1373 for (auto *OMD : IMD ? IMD->instance_methods() : CID->instance_methods()) { 1374 std::string ResultStr; 1375 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr); 1376 SourceLocation LocStart = OMD->getLocStart(); 1377 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart(); 1378 1379 const char *startBuf = SM->getCharacterData(LocStart); 1380 const char *endBuf = SM->getCharacterData(LocEnd); 1381 ReplaceText(LocStart, endBuf-startBuf, ResultStr); 1382 } 1383 1384 for (auto *OMD : IMD ? IMD->class_methods() : CID->class_methods()) { 1385 std::string ResultStr; 1386 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr); 1387 SourceLocation LocStart = OMD->getLocStart(); 1388 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart(); 1389 1390 const char *startBuf = SM->getCharacterData(LocStart); 1391 const char *endBuf = SM->getCharacterData(LocEnd); 1392 ReplaceText(LocStart, endBuf-startBuf, ResultStr); 1393 } 1394 for (auto *I : IMD ? IMD->property_impls() : CID->property_impls()) 1395 RewritePropertyImplDecl(I, IMD, CID); 1396 1397 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// "); 1398 } 1399 1400 void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) { 1401 // Do not synthesize more than once. 1402 if (ObjCSynthesizedStructs.count(ClassDecl)) 1403 return; 1404 // Make sure super class's are written before current class is written. 1405 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass(); 1406 while (SuperClass) { 1407 RewriteInterfaceDecl(SuperClass); 1408 SuperClass = SuperClass->getSuperClass(); 1409 } 1410 std::string ResultStr; 1411 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) { 1412 // we haven't seen a forward decl - generate a typedef. 1413 RewriteOneForwardClassDecl(ClassDecl, ResultStr); 1414 RewriteIvarOffsetSymbols(ClassDecl, ResultStr); 1415 1416 RewriteObjCInternalStruct(ClassDecl, ResultStr); 1417 // Mark this typedef as having been written into its c++ equivalent. 1418 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl()); 1419 1420 for (auto *I : ClassDecl->properties()) 1421 RewriteProperty(I); 1422 for (auto *I : ClassDecl->instance_methods()) 1423 RewriteMethodDeclaration(I); 1424 for (auto *I : ClassDecl->class_methods()) 1425 RewriteMethodDeclaration(I); 1426 1427 // Lastly, comment out the @end. 1428 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"), 1429 "/* @end */\n"); 1430 } 1431 } 1432 1433 Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) { 1434 SourceRange OldRange = PseudoOp->getSourceRange(); 1435 1436 // We just magically know some things about the structure of this 1437 // expression. 1438 ObjCMessageExpr *OldMsg = 1439 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr( 1440 PseudoOp->getNumSemanticExprs() - 1)); 1441 1442 // Because the rewriter doesn't allow us to rewrite rewritten code, 1443 // we need to suppress rewriting the sub-statements. 1444 Expr *Base; 1445 SmallVector<Expr*, 2> Args; 1446 { 1447 DisableReplaceStmtScope S(*this); 1448 1449 // Rebuild the base expression if we have one. 1450 Base = nullptr; 1451 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) { 1452 Base = OldMsg->getInstanceReceiver(); 1453 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr(); 1454 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base)); 1455 } 1456 1457 unsigned numArgs = OldMsg->getNumArgs(); 1458 for (unsigned i = 0; i < numArgs; i++) { 1459 Expr *Arg = OldMsg->getArg(i); 1460 if (isa<OpaqueValueExpr>(Arg)) 1461 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr(); 1462 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg)); 1463 Args.push_back(Arg); 1464 } 1465 } 1466 1467 // TODO: avoid this copy. 1468 SmallVector<SourceLocation, 1> SelLocs; 1469 OldMsg->getSelectorLocs(SelLocs); 1470 1471 ObjCMessageExpr *NewMsg = nullptr; 1472 switch (OldMsg->getReceiverKind()) { 1473 case ObjCMessageExpr::Class: 1474 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(), 1475 OldMsg->getValueKind(), 1476 OldMsg->getLeftLoc(), 1477 OldMsg->getClassReceiverTypeInfo(), 1478 OldMsg->getSelector(), 1479 SelLocs, 1480 OldMsg->getMethodDecl(), 1481 Args, 1482 OldMsg->getRightLoc(), 1483 OldMsg->isImplicit()); 1484 break; 1485 1486 case ObjCMessageExpr::Instance: 1487 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(), 1488 OldMsg->getValueKind(), 1489 OldMsg->getLeftLoc(), 1490 Base, 1491 OldMsg->getSelector(), 1492 SelLocs, 1493 OldMsg->getMethodDecl(), 1494 Args, 1495 OldMsg->getRightLoc(), 1496 OldMsg->isImplicit()); 1497 break; 1498 1499 case ObjCMessageExpr::SuperClass: 1500 case ObjCMessageExpr::SuperInstance: 1501 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(), 1502 OldMsg->getValueKind(), 1503 OldMsg->getLeftLoc(), 1504 OldMsg->getSuperLoc(), 1505 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance, 1506 OldMsg->getSuperType(), 1507 OldMsg->getSelector(), 1508 SelLocs, 1509 OldMsg->getMethodDecl(), 1510 Args, 1511 OldMsg->getRightLoc(), 1512 OldMsg->isImplicit()); 1513 break; 1514 } 1515 1516 Stmt *Replacement = SynthMessageExpr(NewMsg); 1517 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange); 1518 return Replacement; 1519 } 1520 1521 Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) { 1522 SourceRange OldRange = PseudoOp->getSourceRange(); 1523 1524 // We just magically know some things about the structure of this 1525 // expression. 1526 ObjCMessageExpr *OldMsg = 1527 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit()); 1528 1529 // Because the rewriter doesn't allow us to rewrite rewritten code, 1530 // we need to suppress rewriting the sub-statements. 1531 Expr *Base = nullptr; 1532 SmallVector<Expr*, 1> Args; 1533 { 1534 DisableReplaceStmtScope S(*this); 1535 // Rebuild the base expression if we have one. 1536 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) { 1537 Base = OldMsg->getInstanceReceiver(); 1538 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr(); 1539 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base)); 1540 } 1541 unsigned numArgs = OldMsg->getNumArgs(); 1542 for (unsigned i = 0; i < numArgs; i++) { 1543 Expr *Arg = OldMsg->getArg(i); 1544 if (isa<OpaqueValueExpr>(Arg)) 1545 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr(); 1546 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg)); 1547 Args.push_back(Arg); 1548 } 1549 } 1550 1551 // Intentionally empty. 1552 SmallVector<SourceLocation, 1> SelLocs; 1553 1554 ObjCMessageExpr *NewMsg = nullptr; 1555 switch (OldMsg->getReceiverKind()) { 1556 case ObjCMessageExpr::Class: 1557 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(), 1558 OldMsg->getValueKind(), 1559 OldMsg->getLeftLoc(), 1560 OldMsg->getClassReceiverTypeInfo(), 1561 OldMsg->getSelector(), 1562 SelLocs, 1563 OldMsg->getMethodDecl(), 1564 Args, 1565 OldMsg->getRightLoc(), 1566 OldMsg->isImplicit()); 1567 break; 1568 1569 case ObjCMessageExpr::Instance: 1570 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(), 1571 OldMsg->getValueKind(), 1572 OldMsg->getLeftLoc(), 1573 Base, 1574 OldMsg->getSelector(), 1575 SelLocs, 1576 OldMsg->getMethodDecl(), 1577 Args, 1578 OldMsg->getRightLoc(), 1579 OldMsg->isImplicit()); 1580 break; 1581 1582 case ObjCMessageExpr::SuperClass: 1583 case ObjCMessageExpr::SuperInstance: 1584 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(), 1585 OldMsg->getValueKind(), 1586 OldMsg->getLeftLoc(), 1587 OldMsg->getSuperLoc(), 1588 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance, 1589 OldMsg->getSuperType(), 1590 OldMsg->getSelector(), 1591 SelLocs, 1592 OldMsg->getMethodDecl(), 1593 Args, 1594 OldMsg->getRightLoc(), 1595 OldMsg->isImplicit()); 1596 break; 1597 } 1598 1599 Stmt *Replacement = SynthMessageExpr(NewMsg); 1600 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange); 1601 return Replacement; 1602 } 1603 1604 /// SynthCountByEnumWithState - To print: 1605 /// ((NSUInteger (*) 1606 /// (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger)) 1607 /// (void *)objc_msgSend)((id)l_collection, 1608 /// sel_registerName( 1609 /// "countByEnumeratingWithState:objects:count:"), 1610 /// &enumState, 1611 /// (id *)__rw_items, (NSUInteger)16) 1612 /// 1613 void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) { 1614 buf += "((_WIN_NSUInteger (*) (id, SEL, struct __objcFastEnumerationState *, " 1615 "id *, _WIN_NSUInteger))(void *)objc_msgSend)"; 1616 buf += "\n\t\t"; 1617 buf += "((id)l_collection,\n\t\t"; 1618 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),"; 1619 buf += "\n\t\t"; 1620 buf += "&enumState, " 1621 "(id *)__rw_items, (_WIN_NSUInteger)16)"; 1622 } 1623 1624 /// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach 1625 /// statement to exit to its outer synthesized loop. 1626 /// 1627 Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) { 1628 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back())) 1629 return S; 1630 // replace break with goto __break_label 1631 std::string buf; 1632 1633 SourceLocation startLoc = S->getLocStart(); 1634 buf = "goto __break_label_"; 1635 buf += utostr(ObjCBcLabelNo.back()); 1636 ReplaceText(startLoc, strlen("break"), buf); 1637 1638 return nullptr; 1639 } 1640 1641 void RewriteModernObjC::ConvertSourceLocationToLineDirective( 1642 SourceLocation Loc, 1643 std::string &LineString) { 1644 if (Loc.isFileID() && GenerateLineInfo) { 1645 LineString += "\n#line "; 1646 PresumedLoc PLoc = SM->getPresumedLoc(Loc); 1647 LineString += utostr(PLoc.getLine()); 1648 LineString += " \""; 1649 LineString += Lexer::Stringify(PLoc.getFilename()); 1650 LineString += "\"\n"; 1651 } 1652 } 1653 1654 /// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach 1655 /// statement to continue with its inner synthesized loop. 1656 /// 1657 Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) { 1658 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back())) 1659 return S; 1660 // replace continue with goto __continue_label 1661 std::string buf; 1662 1663 SourceLocation startLoc = S->getLocStart(); 1664 buf = "goto __continue_label_"; 1665 buf += utostr(ObjCBcLabelNo.back()); 1666 ReplaceText(startLoc, strlen("continue"), buf); 1667 1668 return nullptr; 1669 } 1670 1671 /// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement. 1672 /// It rewrites: 1673 /// for ( type elem in collection) { stmts; } 1674 1675 /// Into: 1676 /// { 1677 /// type elem; 1678 /// struct __objcFastEnumerationState enumState = { 0 }; 1679 /// id __rw_items[16]; 1680 /// id l_collection = (id)collection; 1681 /// NSUInteger limit = [l_collection countByEnumeratingWithState:&enumState 1682 /// objects:__rw_items count:16]; 1683 /// if (limit) { 1684 /// unsigned long startMutations = *enumState.mutationsPtr; 1685 /// do { 1686 /// unsigned long counter = 0; 1687 /// do { 1688 /// if (startMutations != *enumState.mutationsPtr) 1689 /// objc_enumerationMutation(l_collection); 1690 /// elem = (type)enumState.itemsPtr[counter++]; 1691 /// stmts; 1692 /// __continue_label: ; 1693 /// } while (counter < limit); 1694 /// } while ((limit = [l_collection countByEnumeratingWithState:&enumState 1695 /// objects:__rw_items count:16])); 1696 /// elem = nil; 1697 /// __break_label: ; 1698 /// } 1699 /// else 1700 /// elem = nil; 1701 /// } 1702 /// 1703 Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S, 1704 SourceLocation OrigEnd) { 1705 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty"); 1706 assert(isa<ObjCForCollectionStmt>(Stmts.back()) && 1707 "ObjCForCollectionStmt Statement stack mismatch"); 1708 assert(!ObjCBcLabelNo.empty() && 1709 "ObjCForCollectionStmt - Label No stack empty"); 1710 1711 SourceLocation startLoc = S->getLocStart(); 1712 const char *startBuf = SM->getCharacterData(startLoc); 1713 StringRef elementName; 1714 std::string elementTypeAsString; 1715 std::string buf; 1716 // line directive first. 1717 SourceLocation ForEachLoc = S->getForLoc(); 1718 ConvertSourceLocationToLineDirective(ForEachLoc, buf); 1719 buf += "{\n\t"; 1720 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) { 1721 // type elem; 1722 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl()); 1723 QualType ElementType = cast<ValueDecl>(D)->getType(); 1724 if (ElementType->isObjCQualifiedIdType() || 1725 ElementType->isObjCQualifiedInterfaceType()) 1726 // Simply use 'id' for all qualified types. 1727 elementTypeAsString = "id"; 1728 else 1729 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy()); 1730 buf += elementTypeAsString; 1731 buf += " "; 1732 elementName = D->getName(); 1733 buf += elementName; 1734 buf += ";\n\t"; 1735 } 1736 else { 1737 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement()); 1738 elementName = DR->getDecl()->getName(); 1739 ValueDecl *VD = cast<ValueDecl>(DR->getDecl()); 1740 if (VD->getType()->isObjCQualifiedIdType() || 1741 VD->getType()->isObjCQualifiedInterfaceType()) 1742 // Simply use 'id' for all qualified types. 1743 elementTypeAsString = "id"; 1744 else 1745 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy()); 1746 } 1747 1748 // struct __objcFastEnumerationState enumState = { 0 }; 1749 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t"; 1750 // id __rw_items[16]; 1751 buf += "id __rw_items[16];\n\t"; 1752 // id l_collection = (id) 1753 buf += "id l_collection = (id)"; 1754 // Find start location of 'collection' the hard way! 1755 const char *startCollectionBuf = startBuf; 1756 startCollectionBuf += 3; // skip 'for' 1757 startCollectionBuf = strchr(startCollectionBuf, '('); 1758 startCollectionBuf++; // skip '(' 1759 // find 'in' and skip it. 1760 while (*startCollectionBuf != ' ' || 1761 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' || 1762 (*(startCollectionBuf+3) != ' ' && 1763 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '(')) 1764 startCollectionBuf++; 1765 startCollectionBuf += 3; 1766 1767 // Replace: "for (type element in" with string constructed thus far. 1768 ReplaceText(startLoc, startCollectionBuf - startBuf, buf); 1769 // Replace ')' in for '(' type elem in collection ')' with ';' 1770 SourceLocation rightParenLoc = S->getRParenLoc(); 1771 const char *rparenBuf = SM->getCharacterData(rightParenLoc); 1772 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf); 1773 buf = ";\n\t"; 1774 1775 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState 1776 // objects:__rw_items count:16]; 1777 // which is synthesized into: 1778 // NSUInteger limit = 1779 // ((NSUInteger (*) 1780 // (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger)) 1781 // (void *)objc_msgSend)((id)l_collection, 1782 // sel_registerName( 1783 // "countByEnumeratingWithState:objects:count:"), 1784 // (struct __objcFastEnumerationState *)&state, 1785 // (id *)__rw_items, (NSUInteger)16); 1786 buf += "_WIN_NSUInteger limit =\n\t\t"; 1787 SynthCountByEnumWithState(buf); 1788 buf += ";\n\t"; 1789 /// if (limit) { 1790 /// unsigned long startMutations = *enumState.mutationsPtr; 1791 /// do { 1792 /// unsigned long counter = 0; 1793 /// do { 1794 /// if (startMutations != *enumState.mutationsPtr) 1795 /// objc_enumerationMutation(l_collection); 1796 /// elem = (type)enumState.itemsPtr[counter++]; 1797 buf += "if (limit) {\n\t"; 1798 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t"; 1799 buf += "do {\n\t\t"; 1800 buf += "unsigned long counter = 0;\n\t\t"; 1801 buf += "do {\n\t\t\t"; 1802 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t"; 1803 buf += "objc_enumerationMutation(l_collection);\n\t\t\t"; 1804 buf += elementName; 1805 buf += " = ("; 1806 buf += elementTypeAsString; 1807 buf += ")enumState.itemsPtr[counter++];"; 1808 // Replace ')' in for '(' type elem in collection ')' with all of these. 1809 ReplaceText(lparenLoc, 1, buf); 1810 1811 /// __continue_label: ; 1812 /// } while (counter < limit); 1813 /// } while ((limit = [l_collection countByEnumeratingWithState:&enumState 1814 /// objects:__rw_items count:16])); 1815 /// elem = nil; 1816 /// __break_label: ; 1817 /// } 1818 /// else 1819 /// elem = nil; 1820 /// } 1821 /// 1822 buf = ";\n\t"; 1823 buf += "__continue_label_"; 1824 buf += utostr(ObjCBcLabelNo.back()); 1825 buf += ": ;"; 1826 buf += "\n\t\t"; 1827 buf += "} while (counter < limit);\n\t"; 1828 buf += "} while ((limit = "; 1829 SynthCountByEnumWithState(buf); 1830 buf += "));\n\t"; 1831 buf += elementName; 1832 buf += " = (("; 1833 buf += elementTypeAsString; 1834 buf += ")0);\n\t"; 1835 buf += "__break_label_"; 1836 buf += utostr(ObjCBcLabelNo.back()); 1837 buf += ": ;\n\t"; 1838 buf += "}\n\t"; 1839 buf += "else\n\t\t"; 1840 buf += elementName; 1841 buf += " = (("; 1842 buf += elementTypeAsString; 1843 buf += ")0);\n\t"; 1844 buf += "}\n"; 1845 1846 // Insert all these *after* the statement body. 1847 // FIXME: If this should support Obj-C++, support CXXTryStmt 1848 if (isa<CompoundStmt>(S->getBody())) { 1849 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1); 1850 InsertText(endBodyLoc, buf); 1851 } else { 1852 /* Need to treat single statements specially. For example: 1853 * 1854 * for (A *a in b) if (stuff()) break; 1855 * for (A *a in b) xxxyy; 1856 * 1857 * The following code simply scans ahead to the semi to find the actual end. 1858 */ 1859 const char *stmtBuf = SM->getCharacterData(OrigEnd); 1860 const char *semiBuf = strchr(stmtBuf, ';'); 1861 assert(semiBuf && "Can't find ';'"); 1862 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1); 1863 InsertText(endBodyLoc, buf); 1864 } 1865 Stmts.pop_back(); 1866 ObjCBcLabelNo.pop_back(); 1867 return nullptr; 1868 } 1869 1870 static void Write_RethrowObject(std::string &buf) { 1871 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n"; 1872 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n"; 1873 buf += "\tid rethrow;\n"; 1874 buf += "\t} _fin_force_rethow(_rethrow);"; 1875 } 1876 1877 /// RewriteObjCSynchronizedStmt - 1878 /// This routine rewrites @synchronized(expr) stmt; 1879 /// into: 1880 /// objc_sync_enter(expr); 1881 /// @try stmt @finally { objc_sync_exit(expr); } 1882 /// 1883 Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) { 1884 // Get the start location and compute the semi location. 1885 SourceLocation startLoc = S->getLocStart(); 1886 const char *startBuf = SM->getCharacterData(startLoc); 1887 1888 assert((*startBuf == '@') && "bogus @synchronized location"); 1889 1890 std::string buf; 1891 SourceLocation SynchLoc = S->getAtSynchronizedLoc(); 1892 ConvertSourceLocationToLineDirective(SynchLoc, buf); 1893 buf += "{ id _rethrow = 0; id _sync_obj = (id)"; 1894 1895 const char *lparenBuf = startBuf; 1896 while (*lparenBuf != '(') lparenBuf++; 1897 ReplaceText(startLoc, lparenBuf-startBuf+1, buf); 1898 1899 buf = "; objc_sync_enter(_sync_obj);\n"; 1900 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}"; 1901 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}"; 1902 buf += "\n\tid sync_exit;"; 1903 buf += "\n\t} _sync_exit(_sync_obj);\n"; 1904 1905 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since 1906 // the sync expression is typically a message expression that's already 1907 // been rewritten! (which implies the SourceLocation's are invalid). 1908 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart(); 1909 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc); 1910 while (*RParenExprLocBuf != ')') RParenExprLocBuf--; 1911 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf); 1912 1913 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart(); 1914 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc); 1915 assert (*LBraceLocBuf == '{'); 1916 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf); 1917 1918 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd(); 1919 assert((*SM->getCharacterData(startRBraceLoc) == '}') && 1920 "bogus @synchronized block"); 1921 1922 buf = "} catch (id e) {_rethrow = e;}\n"; 1923 Write_RethrowObject(buf); 1924 buf += "}\n"; 1925 buf += "}\n"; 1926 1927 ReplaceText(startRBraceLoc, 1, buf); 1928 1929 return nullptr; 1930 } 1931 1932 void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S) 1933 { 1934 // Perform a bottom up traversal of all children. 1935 for (Stmt::child_range CI = S->children(); CI; ++CI) 1936 if (*CI) 1937 WarnAboutReturnGotoStmts(*CI); 1938 1939 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) { 1940 Diags.Report(Context->getFullLoc(S->getLocStart()), 1941 TryFinallyContainsReturnDiag); 1942 } 1943 return; 1944 } 1945 1946 Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) { 1947 SourceLocation startLoc = S->getAtLoc(); 1948 ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */"); 1949 ReplaceText(S->getSubStmt()->getLocStart(), 1, 1950 "{ __AtAutoreleasePool __autoreleasepool; "); 1951 1952 return nullptr; 1953 } 1954 1955 Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) { 1956 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt(); 1957 bool noCatch = S->getNumCatchStmts() == 0; 1958 std::string buf; 1959 SourceLocation TryLocation = S->getAtTryLoc(); 1960 ConvertSourceLocationToLineDirective(TryLocation, buf); 1961 1962 if (finalStmt) { 1963 if (noCatch) 1964 buf += "{ id volatile _rethrow = 0;\n"; 1965 else { 1966 buf += "{ id volatile _rethrow = 0;\ntry {\n"; 1967 } 1968 } 1969 // Get the start location and compute the semi location. 1970 SourceLocation startLoc = S->getLocStart(); 1971 const char *startBuf = SM->getCharacterData(startLoc); 1972 1973 assert((*startBuf == '@') && "bogus @try location"); 1974 if (finalStmt) 1975 ReplaceText(startLoc, 1, buf); 1976 else 1977 // @try -> try 1978 ReplaceText(startLoc, 1, ""); 1979 1980 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) { 1981 ObjCAtCatchStmt *Catch = S->getCatchStmt(I); 1982 VarDecl *catchDecl = Catch->getCatchParamDecl(); 1983 1984 startLoc = Catch->getLocStart(); 1985 bool AtRemoved = false; 1986 if (catchDecl) { 1987 QualType t = catchDecl->getType(); 1988 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) { 1989 // Should be a pointer to a class. 1990 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface(); 1991 if (IDecl) { 1992 std::string Result; 1993 ConvertSourceLocationToLineDirective(Catch->getLocStart(), Result); 1994 1995 startBuf = SM->getCharacterData(startLoc); 1996 assert((*startBuf == '@') && "bogus @catch location"); 1997 SourceLocation rParenLoc = Catch->getRParenLoc(); 1998 const char *rParenBuf = SM->getCharacterData(rParenLoc); 1999 2000 // _objc_exc_Foo *_e as argument to catch. 2001 Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString(); 2002 Result += " *_"; Result += catchDecl->getNameAsString(); 2003 Result += ")"; 2004 ReplaceText(startLoc, rParenBuf-startBuf+1, Result); 2005 // Foo *e = (Foo *)_e; 2006 Result.clear(); 2007 Result = "{ "; 2008 Result += IDecl->getNameAsString(); 2009 Result += " *"; Result += catchDecl->getNameAsString(); 2010 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)"; 2011 Result += "_"; Result += catchDecl->getNameAsString(); 2012 2013 Result += "; "; 2014 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart(); 2015 ReplaceText(lBraceLoc, 1, Result); 2016 AtRemoved = true; 2017 } 2018 } 2019 } 2020 if (!AtRemoved) 2021 // @catch -> catch 2022 ReplaceText(startLoc, 1, ""); 2023 2024 } 2025 if (finalStmt) { 2026 buf.clear(); 2027 SourceLocation FinallyLoc = finalStmt->getLocStart(); 2028 2029 if (noCatch) { 2030 ConvertSourceLocationToLineDirective(FinallyLoc, buf); 2031 buf += "catch (id e) {_rethrow = e;}\n"; 2032 } 2033 else { 2034 buf += "}\n"; 2035 ConvertSourceLocationToLineDirective(FinallyLoc, buf); 2036 buf += "catch (id e) {_rethrow = e;}\n"; 2037 } 2038 2039 SourceLocation startFinalLoc = finalStmt->getLocStart(); 2040 ReplaceText(startFinalLoc, 8, buf); 2041 Stmt *body = finalStmt->getFinallyBody(); 2042 SourceLocation startFinalBodyLoc = body->getLocStart(); 2043 buf.clear(); 2044 Write_RethrowObject(buf); 2045 ReplaceText(startFinalBodyLoc, 1, buf); 2046 2047 SourceLocation endFinalBodyLoc = body->getLocEnd(); 2048 ReplaceText(endFinalBodyLoc, 1, "}\n}"); 2049 // Now check for any return/continue/go statements within the @try. 2050 WarnAboutReturnGotoStmts(S->getTryBody()); 2051 } 2052 2053 return nullptr; 2054 } 2055 2056 // This can't be done with ReplaceStmt(S, ThrowExpr), since 2057 // the throw expression is typically a message expression that's already 2058 // been rewritten! (which implies the SourceLocation's are invalid). 2059 Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) { 2060 // Get the start location and compute the semi location. 2061 SourceLocation startLoc = S->getLocStart(); 2062 const char *startBuf = SM->getCharacterData(startLoc); 2063 2064 assert((*startBuf == '@') && "bogus @throw location"); 2065 2066 std::string buf; 2067 /* void objc_exception_throw(id) __attribute__((noreturn)); */ 2068 if (S->getThrowExpr()) 2069 buf = "objc_exception_throw("; 2070 else 2071 buf = "throw"; 2072 2073 // handle "@ throw" correctly. 2074 const char *wBuf = strchr(startBuf, 'w'); 2075 assert((*wBuf == 'w') && "@throw: can't find 'w'"); 2076 ReplaceText(startLoc, wBuf-startBuf+1, buf); 2077 2078 SourceLocation endLoc = S->getLocEnd(); 2079 const char *endBuf = SM->getCharacterData(endLoc); 2080 const char *semiBuf = strchr(endBuf, ';'); 2081 assert((*semiBuf == ';') && "@throw: can't find ';'"); 2082 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf); 2083 if (S->getThrowExpr()) 2084 ReplaceText(semiLoc, 1, ");"); 2085 return nullptr; 2086 } 2087 2088 Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) { 2089 // Create a new string expression. 2090 std::string StrEncoding; 2091 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding); 2092 Expr *Replacement = getStringLiteral(StrEncoding); 2093 ReplaceStmt(Exp, Replacement); 2094 2095 // Replace this subexpr in the parent. 2096 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info. 2097 return Replacement; 2098 } 2099 2100 Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) { 2101 if (!SelGetUidFunctionDecl) 2102 SynthSelGetUidFunctionDecl(); 2103 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl"); 2104 // Create a call to sel_registerName("selName"). 2105 SmallVector<Expr*, 8> SelExprs; 2106 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString())); 2107 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl, 2108 &SelExprs[0], SelExprs.size()); 2109 ReplaceStmt(Exp, SelExp); 2110 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info. 2111 return SelExp; 2112 } 2113 2114 CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl( 2115 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc, 2116 SourceLocation EndLoc) { 2117 // Get the type, we will need to reference it in a couple spots. 2118 QualType msgSendType = FD->getType(); 2119 2120 // Create a reference to the objc_msgSend() declaration. 2121 DeclRefExpr *DRE = 2122 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation()); 2123 2124 // Now, we cast the reference to a pointer to the objc_msgSend type. 2125 QualType pToFunc = Context->getPointerType(msgSendType); 2126 ImplicitCastExpr *ICE = 2127 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay, 2128 DRE, nullptr, VK_RValue); 2129 2130 const FunctionType *FT = msgSendType->getAs<FunctionType>(); 2131 2132 CallExpr *Exp = 2133 new (Context) CallExpr(*Context, ICE, llvm::makeArrayRef(args, nargs), 2134 FT->getCallResultType(*Context), 2135 VK_RValue, EndLoc); 2136 return Exp; 2137 } 2138 2139 static bool scanForProtocolRefs(const char *startBuf, const char *endBuf, 2140 const char *&startRef, const char *&endRef) { 2141 while (startBuf < endBuf) { 2142 if (*startBuf == '<') 2143 startRef = startBuf; // mark the start. 2144 if (*startBuf == '>') { 2145 if (startRef && *startRef == '<') { 2146 endRef = startBuf; // mark the end. 2147 return true; 2148 } 2149 return false; 2150 } 2151 startBuf++; 2152 } 2153 return false; 2154 } 2155 2156 static void scanToNextArgument(const char *&argRef) { 2157 int angle = 0; 2158 while (*argRef != ')' && (*argRef != ',' || angle > 0)) { 2159 if (*argRef == '<') 2160 angle++; 2161 else if (*argRef == '>') 2162 angle--; 2163 argRef++; 2164 } 2165 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax"); 2166 } 2167 2168 bool RewriteModernObjC::needToScanForQualifiers(QualType T) { 2169 if (T->isObjCQualifiedIdType()) 2170 return true; 2171 if (const PointerType *PT = T->getAs<PointerType>()) { 2172 if (PT->getPointeeType()->isObjCQualifiedIdType()) 2173 return true; 2174 } 2175 if (T->isObjCObjectPointerType()) { 2176 T = T->getPointeeType(); 2177 return T->isObjCQualifiedInterfaceType(); 2178 } 2179 if (T->isArrayType()) { 2180 QualType ElemTy = Context->getBaseElementType(T); 2181 return needToScanForQualifiers(ElemTy); 2182 } 2183 return false; 2184 } 2185 2186 void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) { 2187 QualType Type = E->getType(); 2188 if (needToScanForQualifiers(Type)) { 2189 SourceLocation Loc, EndLoc; 2190 2191 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) { 2192 Loc = ECE->getLParenLoc(); 2193 EndLoc = ECE->getRParenLoc(); 2194 } else { 2195 Loc = E->getLocStart(); 2196 EndLoc = E->getLocEnd(); 2197 } 2198 // This will defend against trying to rewrite synthesized expressions. 2199 if (Loc.isInvalid() || EndLoc.isInvalid()) 2200 return; 2201 2202 const char *startBuf = SM->getCharacterData(Loc); 2203 const char *endBuf = SM->getCharacterData(EndLoc); 2204 const char *startRef = nullptr, *endRef = nullptr; 2205 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) { 2206 // Get the locations of the startRef, endRef. 2207 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf); 2208 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1); 2209 // Comment out the protocol references. 2210 InsertText(LessLoc, "/*"); 2211 InsertText(GreaterLoc, "*/"); 2212 } 2213 } 2214 } 2215 2216 void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) { 2217 SourceLocation Loc; 2218 QualType Type; 2219 const FunctionProtoType *proto = nullptr; 2220 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) { 2221 Loc = VD->getLocation(); 2222 Type = VD->getType(); 2223 } 2224 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) { 2225 Loc = FD->getLocation(); 2226 // Check for ObjC 'id' and class types that have been adorned with protocol 2227 // information (id<p>, C<p>*). The protocol references need to be rewritten! 2228 const FunctionType *funcType = FD->getType()->getAs<FunctionType>(); 2229 assert(funcType && "missing function type"); 2230 proto = dyn_cast<FunctionProtoType>(funcType); 2231 if (!proto) 2232 return; 2233 Type = proto->getReturnType(); 2234 } 2235 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) { 2236 Loc = FD->getLocation(); 2237 Type = FD->getType(); 2238 } 2239 else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Dcl)) { 2240 Loc = TD->getLocation(); 2241 Type = TD->getUnderlyingType(); 2242 } 2243 else 2244 return; 2245 2246 if (needToScanForQualifiers(Type)) { 2247 // Since types are unique, we need to scan the buffer. 2248 2249 const char *endBuf = SM->getCharacterData(Loc); 2250 const char *startBuf = endBuf; 2251 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart) 2252 startBuf--; // scan backward (from the decl location) for return type. 2253 const char *startRef = nullptr, *endRef = nullptr; 2254 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) { 2255 // Get the locations of the startRef, endRef. 2256 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf); 2257 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1); 2258 // Comment out the protocol references. 2259 InsertText(LessLoc, "/*"); 2260 InsertText(GreaterLoc, "*/"); 2261 } 2262 } 2263 if (!proto) 2264 return; // most likely, was a variable 2265 // Now check arguments. 2266 const char *startBuf = SM->getCharacterData(Loc); 2267 const char *startFuncBuf = startBuf; 2268 for (unsigned i = 0; i < proto->getNumParams(); i++) { 2269 if (needToScanForQualifiers(proto->getParamType(i))) { 2270 // Since types are unique, we need to scan the buffer. 2271 2272 const char *endBuf = startBuf; 2273 // scan forward (from the decl location) for argument types. 2274 scanToNextArgument(endBuf); 2275 const char *startRef = nullptr, *endRef = nullptr; 2276 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) { 2277 // Get the locations of the startRef, endRef. 2278 SourceLocation LessLoc = 2279 Loc.getLocWithOffset(startRef-startFuncBuf); 2280 SourceLocation GreaterLoc = 2281 Loc.getLocWithOffset(endRef-startFuncBuf+1); 2282 // Comment out the protocol references. 2283 InsertText(LessLoc, "/*"); 2284 InsertText(GreaterLoc, "*/"); 2285 } 2286 startBuf = ++endBuf; 2287 } 2288 else { 2289 // If the function name is derived from a macro expansion, then the 2290 // argument buffer will not follow the name. Need to speak with Chris. 2291 while (*startBuf && *startBuf != ')' && *startBuf != ',') 2292 startBuf++; // scan forward (from the decl location) for argument types. 2293 startBuf++; 2294 } 2295 } 2296 } 2297 2298 void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) { 2299 QualType QT = ND->getType(); 2300 const Type* TypePtr = QT->getAs<Type>(); 2301 if (!isa<TypeOfExprType>(TypePtr)) 2302 return; 2303 while (isa<TypeOfExprType>(TypePtr)) { 2304 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr); 2305 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType(); 2306 TypePtr = QT->getAs<Type>(); 2307 } 2308 // FIXME. This will not work for multiple declarators; as in: 2309 // __typeof__(a) b,c,d; 2310 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy())); 2311 SourceLocation DeclLoc = ND->getTypeSpecStartLoc(); 2312 const char *startBuf = SM->getCharacterData(DeclLoc); 2313 if (ND->getInit()) { 2314 std::string Name(ND->getNameAsString()); 2315 TypeAsString += " " + Name + " = "; 2316 Expr *E = ND->getInit(); 2317 SourceLocation startLoc; 2318 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) 2319 startLoc = ECE->getLParenLoc(); 2320 else 2321 startLoc = E->getLocStart(); 2322 startLoc = SM->getExpansionLoc(startLoc); 2323 const char *endBuf = SM->getCharacterData(startLoc); 2324 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString); 2325 } 2326 else { 2327 SourceLocation X = ND->getLocEnd(); 2328 X = SM->getExpansionLoc(X); 2329 const char *endBuf = SM->getCharacterData(X); 2330 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString); 2331 } 2332 } 2333 2334 // SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str); 2335 void RewriteModernObjC::SynthSelGetUidFunctionDecl() { 2336 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName"); 2337 SmallVector<QualType, 16> ArgTys; 2338 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst())); 2339 QualType getFuncType = 2340 getSimpleFunctionType(Context->getObjCSelType(), ArgTys); 2341 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl, 2342 SourceLocation(), 2343 SourceLocation(), 2344 SelGetUidIdent, getFuncType, 2345 nullptr, SC_Extern); 2346 } 2347 2348 void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) { 2349 // declared in <objc/objc.h> 2350 if (FD->getIdentifier() && 2351 FD->getName() == "sel_registerName") { 2352 SelGetUidFunctionDecl = FD; 2353 return; 2354 } 2355 RewriteObjCQualifiedInterfaceTypes(FD); 2356 } 2357 2358 void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) { 2359 std::string TypeString(Type.getAsString(Context->getPrintingPolicy())); 2360 const char *argPtr = TypeString.c_str(); 2361 if (!strchr(argPtr, '^')) { 2362 Str += TypeString; 2363 return; 2364 } 2365 while (*argPtr) { 2366 Str += (*argPtr == '^' ? '*' : *argPtr); 2367 argPtr++; 2368 } 2369 } 2370 2371 // FIXME. Consolidate this routine with RewriteBlockPointerType. 2372 void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str, 2373 ValueDecl *VD) { 2374 QualType Type = VD->getType(); 2375 std::string TypeString(Type.getAsString(Context->getPrintingPolicy())); 2376 const char *argPtr = TypeString.c_str(); 2377 int paren = 0; 2378 while (*argPtr) { 2379 switch (*argPtr) { 2380 case '(': 2381 Str += *argPtr; 2382 paren++; 2383 break; 2384 case ')': 2385 Str += *argPtr; 2386 paren--; 2387 break; 2388 case '^': 2389 Str += '*'; 2390 if (paren == 1) 2391 Str += VD->getNameAsString(); 2392 break; 2393 default: 2394 Str += *argPtr; 2395 break; 2396 } 2397 argPtr++; 2398 } 2399 } 2400 2401 void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) { 2402 SourceLocation FunLocStart = FD->getTypeSpecStartLoc(); 2403 const FunctionType *funcType = FD->getType()->getAs<FunctionType>(); 2404 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType); 2405 if (!proto) 2406 return; 2407 QualType Type = proto->getReturnType(); 2408 std::string FdStr = Type.getAsString(Context->getPrintingPolicy()); 2409 FdStr += " "; 2410 FdStr += FD->getName(); 2411 FdStr += "("; 2412 unsigned numArgs = proto->getNumParams(); 2413 for (unsigned i = 0; i < numArgs; i++) { 2414 QualType ArgType = proto->getParamType(i); 2415 RewriteBlockPointerType(FdStr, ArgType); 2416 if (i+1 < numArgs) 2417 FdStr += ", "; 2418 } 2419 if (FD->isVariadic()) { 2420 FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n"; 2421 } 2422 else 2423 FdStr += ");\n"; 2424 InsertText(FunLocStart, FdStr); 2425 } 2426 2427 // SynthSuperConstructorFunctionDecl - id __rw_objc_super(id obj, id super); 2428 void RewriteModernObjC::SynthSuperConstructorFunctionDecl() { 2429 if (SuperConstructorFunctionDecl) 2430 return; 2431 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super"); 2432 SmallVector<QualType, 16> ArgTys; 2433 QualType argT = Context->getObjCIdType(); 2434 assert(!argT.isNull() && "Can't find 'id' type"); 2435 ArgTys.push_back(argT); 2436 ArgTys.push_back(argT); 2437 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(), 2438 ArgTys); 2439 SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl, 2440 SourceLocation(), 2441 SourceLocation(), 2442 msgSendIdent, msgSendType, 2443 nullptr, SC_Extern); 2444 } 2445 2446 // SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...); 2447 void RewriteModernObjC::SynthMsgSendFunctionDecl() { 2448 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend"); 2449 SmallVector<QualType, 16> ArgTys; 2450 QualType argT = Context->getObjCIdType(); 2451 assert(!argT.isNull() && "Can't find 'id' type"); 2452 ArgTys.push_back(argT); 2453 argT = Context->getObjCSelType(); 2454 assert(!argT.isNull() && "Can't find 'SEL' type"); 2455 ArgTys.push_back(argT); 2456 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(), 2457 ArgTys, /*isVariadic=*/true); 2458 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl, 2459 SourceLocation(), 2460 SourceLocation(), 2461 msgSendIdent, msgSendType, nullptr, 2462 SC_Extern); 2463 } 2464 2465 // SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void); 2466 void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() { 2467 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper"); 2468 SmallVector<QualType, 2> ArgTys; 2469 ArgTys.push_back(Context->VoidTy); 2470 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(), 2471 ArgTys, /*isVariadic=*/true); 2472 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl, 2473 SourceLocation(), 2474 SourceLocation(), 2475 msgSendIdent, msgSendType, 2476 nullptr, SC_Extern); 2477 } 2478 2479 // SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...); 2480 void RewriteModernObjC::SynthMsgSendStretFunctionDecl() { 2481 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret"); 2482 SmallVector<QualType, 16> ArgTys; 2483 QualType argT = Context->getObjCIdType(); 2484 assert(!argT.isNull() && "Can't find 'id' type"); 2485 ArgTys.push_back(argT); 2486 argT = Context->getObjCSelType(); 2487 assert(!argT.isNull() && "Can't find 'SEL' type"); 2488 ArgTys.push_back(argT); 2489 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(), 2490 ArgTys, /*isVariadic=*/true); 2491 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl, 2492 SourceLocation(), 2493 SourceLocation(), 2494 msgSendIdent, msgSendType, 2495 nullptr, SC_Extern); 2496 } 2497 2498 // SynthMsgSendSuperStretFunctionDecl - 2499 // id objc_msgSendSuper_stret(void); 2500 void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() { 2501 IdentifierInfo *msgSendIdent = 2502 &Context->Idents.get("objc_msgSendSuper_stret"); 2503 SmallVector<QualType, 2> ArgTys; 2504 ArgTys.push_back(Context->VoidTy); 2505 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(), 2506 ArgTys, /*isVariadic=*/true); 2507 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl, 2508 SourceLocation(), 2509 SourceLocation(), 2510 msgSendIdent, 2511 msgSendType, nullptr, 2512 SC_Extern); 2513 } 2514 2515 // SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...); 2516 void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() { 2517 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret"); 2518 SmallVector<QualType, 16> ArgTys; 2519 QualType argT = Context->getObjCIdType(); 2520 assert(!argT.isNull() && "Can't find 'id' type"); 2521 ArgTys.push_back(argT); 2522 argT = Context->getObjCSelType(); 2523 assert(!argT.isNull() && "Can't find 'SEL' type"); 2524 ArgTys.push_back(argT); 2525 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy, 2526 ArgTys, /*isVariadic=*/true); 2527 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl, 2528 SourceLocation(), 2529 SourceLocation(), 2530 msgSendIdent, msgSendType, 2531 nullptr, SC_Extern); 2532 } 2533 2534 // SynthGetClassFunctionDecl - Class objc_getClass(const char *name); 2535 void RewriteModernObjC::SynthGetClassFunctionDecl() { 2536 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass"); 2537 SmallVector<QualType, 16> ArgTys; 2538 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst())); 2539 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(), 2540 ArgTys); 2541 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl, 2542 SourceLocation(), 2543 SourceLocation(), 2544 getClassIdent, getClassType, 2545 nullptr, SC_Extern); 2546 } 2547 2548 // SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls); 2549 void RewriteModernObjC::SynthGetSuperClassFunctionDecl() { 2550 IdentifierInfo *getSuperClassIdent = 2551 &Context->Idents.get("class_getSuperclass"); 2552 SmallVector<QualType, 16> ArgTys; 2553 ArgTys.push_back(Context->getObjCClassType()); 2554 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(), 2555 ArgTys); 2556 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl, 2557 SourceLocation(), 2558 SourceLocation(), 2559 getSuperClassIdent, 2560 getClassType, nullptr, 2561 SC_Extern); 2562 } 2563 2564 // SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name); 2565 void RewriteModernObjC::SynthGetMetaClassFunctionDecl() { 2566 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass"); 2567 SmallVector<QualType, 16> ArgTys; 2568 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst())); 2569 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(), 2570 ArgTys); 2571 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl, 2572 SourceLocation(), 2573 SourceLocation(), 2574 getClassIdent, getClassType, 2575 nullptr, SC_Extern); 2576 } 2577 2578 Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) { 2579 assert (Exp != nullptr && "Expected non-null ObjCStringLiteral"); 2580 QualType strType = getConstantStringStructType(); 2581 2582 std::string S = "__NSConstantStringImpl_"; 2583 2584 std::string tmpName = InFileName; 2585 unsigned i; 2586 for (i=0; i < tmpName.length(); i++) { 2587 char c = tmpName.at(i); 2588 // replace any non-alphanumeric characters with '_'. 2589 if (!isAlphanumeric(c)) 2590 tmpName[i] = '_'; 2591 } 2592 S += tmpName; 2593 S += "_"; 2594 S += utostr(NumObjCStringLiterals++); 2595 2596 Preamble += "static __NSConstantStringImpl " + S; 2597 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,"; 2598 Preamble += "0x000007c8,"; // utf8_str 2599 // The pretty printer for StringLiteral handles escape characters properly. 2600 std::string prettyBufS; 2601 llvm::raw_string_ostream prettyBuf(prettyBufS); 2602 Exp->getString()->printPretty(prettyBuf, nullptr, PrintingPolicy(LangOpts)); 2603 Preamble += prettyBuf.str(); 2604 Preamble += ","; 2605 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n"; 2606 2607 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(), 2608 SourceLocation(), &Context->Idents.get(S), 2609 strType, nullptr, SC_Static); 2610 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue, 2611 SourceLocation()); 2612 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf, 2613 Context->getPointerType(DRE->getType()), 2614 VK_RValue, OK_Ordinary, 2615 SourceLocation()); 2616 // cast to NSConstantString * 2617 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(), 2618 CK_CPointerToObjCPointerCast, Unop); 2619 ReplaceStmt(Exp, cast); 2620 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info. 2621 return cast; 2622 } 2623 2624 Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) { 2625 unsigned IntSize = 2626 static_cast<unsigned>(Context->getTypeSize(Context->IntTy)); 2627 2628 Expr *FlagExp = IntegerLiteral::Create(*Context, 2629 llvm::APInt(IntSize, Exp->getValue()), 2630 Context->IntTy, Exp->getLocation()); 2631 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy, 2632 CK_BitCast, FlagExp); 2633 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(), 2634 cast); 2635 ReplaceStmt(Exp, PE); 2636 return PE; 2637 } 2638 2639 Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) { 2640 // synthesize declaration of helper functions needed in this routine. 2641 if (!SelGetUidFunctionDecl) 2642 SynthSelGetUidFunctionDecl(); 2643 // use objc_msgSend() for all. 2644 if (!MsgSendFunctionDecl) 2645 SynthMsgSendFunctionDecl(); 2646 if (!GetClassFunctionDecl) 2647 SynthGetClassFunctionDecl(); 2648 2649 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl; 2650 SourceLocation StartLoc = Exp->getLocStart(); 2651 SourceLocation EndLoc = Exp->getLocEnd(); 2652 2653 // Synthesize a call to objc_msgSend(). 2654 SmallVector<Expr*, 4> MsgExprs; 2655 SmallVector<Expr*, 4> ClsExprs; 2656 2657 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument. 2658 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod(); 2659 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface(); 2660 2661 IdentifierInfo *clsName = BoxingClass->getIdentifier(); 2662 ClsExprs.push_back(getStringLiteral(clsName->getName())); 2663 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, 2664 &ClsExprs[0], 2665 ClsExprs.size(), 2666 StartLoc, EndLoc); 2667 MsgExprs.push_back(Cls); 2668 2669 // Create a call to sel_registerName("<BoxingMethod>:"), etc. 2670 // it will be the 2nd argument. 2671 SmallVector<Expr*, 4> SelExprs; 2672 SelExprs.push_back( 2673 getStringLiteral(BoxingMethod->getSelector().getAsString())); 2674 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl, 2675 &SelExprs[0], SelExprs.size(), 2676 StartLoc, EndLoc); 2677 MsgExprs.push_back(SelExp); 2678 2679 // User provided sub-expression is the 3rd, and last, argument. 2680 Expr *subExpr = Exp->getSubExpr(); 2681 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) { 2682 QualType type = ICE->getType(); 2683 const Expr *SubExpr = ICE->IgnoreParenImpCasts(); 2684 CastKind CK = CK_BitCast; 2685 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType()) 2686 CK = CK_IntegralToBoolean; 2687 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr); 2688 } 2689 MsgExprs.push_back(subExpr); 2690 2691 SmallVector<QualType, 4> ArgTypes; 2692 ArgTypes.push_back(Context->getObjCIdType()); 2693 ArgTypes.push_back(Context->getObjCSelType()); 2694 for (const auto PI : BoxingMethod->parameters()) 2695 ArgTypes.push_back(PI->getType()); 2696 2697 QualType returnType = Exp->getType(); 2698 // Get the type, we will need to reference it in a couple spots. 2699 QualType msgSendType = MsgSendFlavor->getType(); 2700 2701 // Create a reference to the objc_msgSend() declaration. 2702 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType, 2703 VK_LValue, SourceLocation()); 2704 2705 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, 2706 Context->getPointerType(Context->VoidTy), 2707 CK_BitCast, DRE); 2708 2709 // Now do the "normal" pointer to function cast. 2710 QualType castType = 2711 getSimpleFunctionType(returnType, ArgTypes, BoxingMethod->isVariadic()); 2712 castType = Context->getPointerType(castType); 2713 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast, 2714 cast); 2715 2716 // Don't forget the parens to enforce the proper binding. 2717 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast); 2718 2719 const FunctionType *FT = msgSendType->getAs<FunctionType>(); 2720 CallExpr *CE = new (Context) 2721 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc); 2722 ReplaceStmt(Exp, CE); 2723 return CE; 2724 } 2725 2726 Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) { 2727 // synthesize declaration of helper functions needed in this routine. 2728 if (!SelGetUidFunctionDecl) 2729 SynthSelGetUidFunctionDecl(); 2730 // use objc_msgSend() for all. 2731 if (!MsgSendFunctionDecl) 2732 SynthMsgSendFunctionDecl(); 2733 if (!GetClassFunctionDecl) 2734 SynthGetClassFunctionDecl(); 2735 2736 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl; 2737 SourceLocation StartLoc = Exp->getLocStart(); 2738 SourceLocation EndLoc = Exp->getLocEnd(); 2739 2740 // Build the expression: __NSContainer_literal(int, ...).arr 2741 QualType IntQT = Context->IntTy; 2742 QualType NSArrayFType = 2743 getSimpleFunctionType(Context->VoidTy, IntQT, true); 2744 std::string NSArrayFName("__NSContainer_literal"); 2745 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName); 2746 DeclRefExpr *NSArrayDRE = 2747 new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue, 2748 SourceLocation()); 2749 2750 SmallVector<Expr*, 16> InitExprs; 2751 unsigned NumElements = Exp->getNumElements(); 2752 unsigned UnsignedIntSize = 2753 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy)); 2754 Expr *count = IntegerLiteral::Create(*Context, 2755 llvm::APInt(UnsignedIntSize, NumElements), 2756 Context->UnsignedIntTy, SourceLocation()); 2757 InitExprs.push_back(count); 2758 for (unsigned i = 0; i < NumElements; i++) 2759 InitExprs.push_back(Exp->getElement(i)); 2760 Expr *NSArrayCallExpr = 2761 new (Context) CallExpr(*Context, NSArrayDRE, InitExprs, 2762 NSArrayFType, VK_LValue, SourceLocation()); 2763 2764 FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(), 2765 SourceLocation(), 2766 &Context->Idents.get("arr"), 2767 Context->getPointerType(Context->VoidPtrTy), 2768 nullptr, /*BitWidth=*/nullptr, 2769 /*Mutable=*/true, ICIS_NoInit); 2770 MemberExpr *ArrayLiteralME = 2771 new (Context) MemberExpr(NSArrayCallExpr, false, ARRFD, 2772 SourceLocation(), 2773 ARRFD->getType(), VK_LValue, 2774 OK_Ordinary); 2775 QualType ConstIdT = Context->getObjCIdType().withConst(); 2776 CStyleCastExpr * ArrayLiteralObjects = 2777 NoTypeInfoCStyleCastExpr(Context, 2778 Context->getPointerType(ConstIdT), 2779 CK_BitCast, 2780 ArrayLiteralME); 2781 2782 // Synthesize a call to objc_msgSend(). 2783 SmallVector<Expr*, 32> MsgExprs; 2784 SmallVector<Expr*, 4> ClsExprs; 2785 QualType expType = Exp->getType(); 2786 2787 // Create a call to objc_getClass("NSArray"). It will be th 1st argument. 2788 ObjCInterfaceDecl *Class = 2789 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface(); 2790 2791 IdentifierInfo *clsName = Class->getIdentifier(); 2792 ClsExprs.push_back(getStringLiteral(clsName->getName())); 2793 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, 2794 &ClsExprs[0], 2795 ClsExprs.size(), 2796 StartLoc, EndLoc); 2797 MsgExprs.push_back(Cls); 2798 2799 // Create a call to sel_registerName("arrayWithObjects:count:"). 2800 // it will be the 2nd argument. 2801 SmallVector<Expr*, 4> SelExprs; 2802 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod(); 2803 SelExprs.push_back( 2804 getStringLiteral(ArrayMethod->getSelector().getAsString())); 2805 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl, 2806 &SelExprs[0], SelExprs.size(), 2807 StartLoc, EndLoc); 2808 MsgExprs.push_back(SelExp); 2809 2810 // (const id [])objects 2811 MsgExprs.push_back(ArrayLiteralObjects); 2812 2813 // (NSUInteger)cnt 2814 Expr *cnt = IntegerLiteral::Create(*Context, 2815 llvm::APInt(UnsignedIntSize, NumElements), 2816 Context->UnsignedIntTy, SourceLocation()); 2817 MsgExprs.push_back(cnt); 2818 2819 2820 SmallVector<QualType, 4> ArgTypes; 2821 ArgTypes.push_back(Context->getObjCIdType()); 2822 ArgTypes.push_back(Context->getObjCSelType()); 2823 for (const auto *PI : ArrayMethod->params()) 2824 ArgTypes.push_back(PI->getType()); 2825 2826 QualType returnType = Exp->getType(); 2827 // Get the type, we will need to reference it in a couple spots. 2828 QualType msgSendType = MsgSendFlavor->getType(); 2829 2830 // Create a reference to the objc_msgSend() declaration. 2831 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType, 2832 VK_LValue, SourceLocation()); 2833 2834 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, 2835 Context->getPointerType(Context->VoidTy), 2836 CK_BitCast, DRE); 2837 2838 // Now do the "normal" pointer to function cast. 2839 QualType castType = 2840 getSimpleFunctionType(returnType, ArgTypes, ArrayMethod->isVariadic()); 2841 castType = Context->getPointerType(castType); 2842 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast, 2843 cast); 2844 2845 // Don't forget the parens to enforce the proper binding. 2846 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast); 2847 2848 const FunctionType *FT = msgSendType->getAs<FunctionType>(); 2849 CallExpr *CE = new (Context) 2850 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc); 2851 ReplaceStmt(Exp, CE); 2852 return CE; 2853 } 2854 2855 Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) { 2856 // synthesize declaration of helper functions needed in this routine. 2857 if (!SelGetUidFunctionDecl) 2858 SynthSelGetUidFunctionDecl(); 2859 // use objc_msgSend() for all. 2860 if (!MsgSendFunctionDecl) 2861 SynthMsgSendFunctionDecl(); 2862 if (!GetClassFunctionDecl) 2863 SynthGetClassFunctionDecl(); 2864 2865 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl; 2866 SourceLocation StartLoc = Exp->getLocStart(); 2867 SourceLocation EndLoc = Exp->getLocEnd(); 2868 2869 // Build the expression: __NSContainer_literal(int, ...).arr 2870 QualType IntQT = Context->IntTy; 2871 QualType NSDictFType = 2872 getSimpleFunctionType(Context->VoidTy, IntQT, true); 2873 std::string NSDictFName("__NSContainer_literal"); 2874 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName); 2875 DeclRefExpr *NSDictDRE = 2876 new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue, 2877 SourceLocation()); 2878 2879 SmallVector<Expr*, 16> KeyExprs; 2880 SmallVector<Expr*, 16> ValueExprs; 2881 2882 unsigned NumElements = Exp->getNumElements(); 2883 unsigned UnsignedIntSize = 2884 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy)); 2885 Expr *count = IntegerLiteral::Create(*Context, 2886 llvm::APInt(UnsignedIntSize, NumElements), 2887 Context->UnsignedIntTy, SourceLocation()); 2888 KeyExprs.push_back(count); 2889 ValueExprs.push_back(count); 2890 for (unsigned i = 0; i < NumElements; i++) { 2891 ObjCDictionaryElement Element = Exp->getKeyValueElement(i); 2892 KeyExprs.push_back(Element.Key); 2893 ValueExprs.push_back(Element.Value); 2894 } 2895 2896 // (const id [])objects 2897 Expr *NSValueCallExpr = 2898 new (Context) CallExpr(*Context, NSDictDRE, ValueExprs, 2899 NSDictFType, VK_LValue, SourceLocation()); 2900 2901 FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(), 2902 SourceLocation(), 2903 &Context->Idents.get("arr"), 2904 Context->getPointerType(Context->VoidPtrTy), 2905 nullptr, /*BitWidth=*/nullptr, 2906 /*Mutable=*/true, ICIS_NoInit); 2907 MemberExpr *DictLiteralValueME = 2908 new (Context) MemberExpr(NSValueCallExpr, false, ARRFD, 2909 SourceLocation(), 2910 ARRFD->getType(), VK_LValue, 2911 OK_Ordinary); 2912 QualType ConstIdT = Context->getObjCIdType().withConst(); 2913 CStyleCastExpr * DictValueObjects = 2914 NoTypeInfoCStyleCastExpr(Context, 2915 Context->getPointerType(ConstIdT), 2916 CK_BitCast, 2917 DictLiteralValueME); 2918 // (const id <NSCopying> [])keys 2919 Expr *NSKeyCallExpr = 2920 new (Context) CallExpr(*Context, NSDictDRE, KeyExprs, 2921 NSDictFType, VK_LValue, SourceLocation()); 2922 2923 MemberExpr *DictLiteralKeyME = 2924 new (Context) MemberExpr(NSKeyCallExpr, false, ARRFD, 2925 SourceLocation(), 2926 ARRFD->getType(), VK_LValue, 2927 OK_Ordinary); 2928 2929 CStyleCastExpr * DictKeyObjects = 2930 NoTypeInfoCStyleCastExpr(Context, 2931 Context->getPointerType(ConstIdT), 2932 CK_BitCast, 2933 DictLiteralKeyME); 2934 2935 2936 2937 // Synthesize a call to objc_msgSend(). 2938 SmallVector<Expr*, 32> MsgExprs; 2939 SmallVector<Expr*, 4> ClsExprs; 2940 QualType expType = Exp->getType(); 2941 2942 // Create a call to objc_getClass("NSArray"). It will be th 1st argument. 2943 ObjCInterfaceDecl *Class = 2944 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface(); 2945 2946 IdentifierInfo *clsName = Class->getIdentifier(); 2947 ClsExprs.push_back(getStringLiteral(clsName->getName())); 2948 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, 2949 &ClsExprs[0], 2950 ClsExprs.size(), 2951 StartLoc, EndLoc); 2952 MsgExprs.push_back(Cls); 2953 2954 // Create a call to sel_registerName("arrayWithObjects:count:"). 2955 // it will be the 2nd argument. 2956 SmallVector<Expr*, 4> SelExprs; 2957 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod(); 2958 SelExprs.push_back(getStringLiteral(DictMethod->getSelector().getAsString())); 2959 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl, 2960 &SelExprs[0], SelExprs.size(), 2961 StartLoc, EndLoc); 2962 MsgExprs.push_back(SelExp); 2963 2964 // (const id [])objects 2965 MsgExprs.push_back(DictValueObjects); 2966 2967 // (const id <NSCopying> [])keys 2968 MsgExprs.push_back(DictKeyObjects); 2969 2970 // (NSUInteger)cnt 2971 Expr *cnt = IntegerLiteral::Create(*Context, 2972 llvm::APInt(UnsignedIntSize, NumElements), 2973 Context->UnsignedIntTy, SourceLocation()); 2974 MsgExprs.push_back(cnt); 2975 2976 2977 SmallVector<QualType, 8> ArgTypes; 2978 ArgTypes.push_back(Context->getObjCIdType()); 2979 ArgTypes.push_back(Context->getObjCSelType()); 2980 for (const auto *PI : DictMethod->params()) { 2981 QualType T = PI->getType(); 2982 if (const PointerType* PT = T->getAs<PointerType>()) { 2983 QualType PointeeTy = PT->getPointeeType(); 2984 convertToUnqualifiedObjCType(PointeeTy); 2985 T = Context->getPointerType(PointeeTy); 2986 } 2987 ArgTypes.push_back(T); 2988 } 2989 2990 QualType returnType = Exp->getType(); 2991 // Get the type, we will need to reference it in a couple spots. 2992 QualType msgSendType = MsgSendFlavor->getType(); 2993 2994 // Create a reference to the objc_msgSend() declaration. 2995 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType, 2996 VK_LValue, SourceLocation()); 2997 2998 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, 2999 Context->getPointerType(Context->VoidTy), 3000 CK_BitCast, DRE); 3001 3002 // Now do the "normal" pointer to function cast. 3003 QualType castType = 3004 getSimpleFunctionType(returnType, ArgTypes, DictMethod->isVariadic()); 3005 castType = Context->getPointerType(castType); 3006 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast, 3007 cast); 3008 3009 // Don't forget the parens to enforce the proper binding. 3010 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast); 3011 3012 const FunctionType *FT = msgSendType->getAs<FunctionType>(); 3013 CallExpr *CE = new (Context) 3014 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc); 3015 ReplaceStmt(Exp, CE); 3016 return CE; 3017 } 3018 3019 // struct __rw_objc_super { 3020 // struct objc_object *object; struct objc_object *superClass; 3021 // }; 3022 QualType RewriteModernObjC::getSuperStructType() { 3023 if (!SuperStructDecl) { 3024 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl, 3025 SourceLocation(), SourceLocation(), 3026 &Context->Idents.get("__rw_objc_super")); 3027 QualType FieldTypes[2]; 3028 3029 // struct objc_object *object; 3030 FieldTypes[0] = Context->getObjCIdType(); 3031 // struct objc_object *superClass; 3032 FieldTypes[1] = Context->getObjCIdType(); 3033 3034 // Create fields 3035 for (unsigned i = 0; i < 2; ++i) { 3036 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl, 3037 SourceLocation(), 3038 SourceLocation(), nullptr, 3039 FieldTypes[i], nullptr, 3040 /*BitWidth=*/nullptr, 3041 /*Mutable=*/false, 3042 ICIS_NoInit)); 3043 } 3044 3045 SuperStructDecl->completeDefinition(); 3046 } 3047 return Context->getTagDeclType(SuperStructDecl); 3048 } 3049 3050 QualType RewriteModernObjC::getConstantStringStructType() { 3051 if (!ConstantStringDecl) { 3052 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl, 3053 SourceLocation(), SourceLocation(), 3054 &Context->Idents.get("__NSConstantStringImpl")); 3055 QualType FieldTypes[4]; 3056 3057 // struct objc_object *receiver; 3058 FieldTypes[0] = Context->getObjCIdType(); 3059 // int flags; 3060 FieldTypes[1] = Context->IntTy; 3061 // char *str; 3062 FieldTypes[2] = Context->getPointerType(Context->CharTy); 3063 // long length; 3064 FieldTypes[3] = Context->LongTy; 3065 3066 // Create fields 3067 for (unsigned i = 0; i < 4; ++i) { 3068 ConstantStringDecl->addDecl(FieldDecl::Create(*Context, 3069 ConstantStringDecl, 3070 SourceLocation(), 3071 SourceLocation(), nullptr, 3072 FieldTypes[i], nullptr, 3073 /*BitWidth=*/nullptr, 3074 /*Mutable=*/true, 3075 ICIS_NoInit)); 3076 } 3077 3078 ConstantStringDecl->completeDefinition(); 3079 } 3080 return Context->getTagDeclType(ConstantStringDecl); 3081 } 3082 3083 /// getFunctionSourceLocation - returns start location of a function 3084 /// definition. Complication arises when function has declared as 3085 /// extern "C" or extern "C" {...} 3086 static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R, 3087 FunctionDecl *FD) { 3088 if (FD->isExternC() && !FD->isMain()) { 3089 const DeclContext *DC = FD->getDeclContext(); 3090 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC)) 3091 // if it is extern "C" {...}, return function decl's own location. 3092 if (!LSD->getRBraceLoc().isValid()) 3093 return LSD->getExternLoc(); 3094 } 3095 if (FD->getStorageClass() != SC_None) 3096 R.RewriteBlockLiteralFunctionDecl(FD); 3097 return FD->getTypeSpecStartLoc(); 3098 } 3099 3100 void RewriteModernObjC::RewriteLineDirective(const Decl *D) { 3101 3102 SourceLocation Location = D->getLocation(); 3103 3104 if (Location.isFileID() && GenerateLineInfo) { 3105 std::string LineString("\n#line "); 3106 PresumedLoc PLoc = SM->getPresumedLoc(Location); 3107 LineString += utostr(PLoc.getLine()); 3108 LineString += " \""; 3109 LineString += Lexer::Stringify(PLoc.getFilename()); 3110 if (isa<ObjCMethodDecl>(D)) 3111 LineString += "\""; 3112 else LineString += "\"\n"; 3113 3114 Location = D->getLocStart(); 3115 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 3116 if (FD->isExternC() && !FD->isMain()) { 3117 const DeclContext *DC = FD->getDeclContext(); 3118 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC)) 3119 // if it is extern "C" {...}, return function decl's own location. 3120 if (!LSD->getRBraceLoc().isValid()) 3121 Location = LSD->getExternLoc(); 3122 } 3123 } 3124 InsertText(Location, LineString); 3125 } 3126 } 3127 3128 /// SynthMsgSendStretCallExpr - This routine translates message expression 3129 /// into a call to objc_msgSend_stret() entry point. Tricky part is that 3130 /// nil check on receiver must be performed before calling objc_msgSend_stret. 3131 /// MsgSendStretFlavor - function declaration objc_msgSend_stret(...) 3132 /// msgSendType - function type of objc_msgSend_stret(...) 3133 /// returnType - Result type of the method being synthesized. 3134 /// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type. 3135 /// MsgExprs - list of argument expressions being passed to objc_msgSend_stret, 3136 /// starting with receiver. 3137 /// Method - Method being rewritten. 3138 Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor, 3139 QualType returnType, 3140 SmallVectorImpl<QualType> &ArgTypes, 3141 SmallVectorImpl<Expr*> &MsgExprs, 3142 ObjCMethodDecl *Method) { 3143 // Now do the "normal" pointer to function cast. 3144 QualType castType = getSimpleFunctionType(returnType, ArgTypes, 3145 Method ? Method->isVariadic() 3146 : false); 3147 castType = Context->getPointerType(castType); 3148 3149 // build type for containing the objc_msgSend_stret object. 3150 static unsigned stretCount=0; 3151 std::string name = "__Stret"; name += utostr(stretCount); 3152 std::string str = 3153 "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n"; 3154 str += "namespace {\n"; 3155 str += "struct "; str += name; 3156 str += " {\n\t"; 3157 str += name; 3158 str += "(id receiver, SEL sel"; 3159 for (unsigned i = 2; i < ArgTypes.size(); i++) { 3160 std::string ArgName = "arg"; ArgName += utostr(i); 3161 ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy()); 3162 str += ", "; str += ArgName; 3163 } 3164 // could be vararg. 3165 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) { 3166 std::string ArgName = "arg"; ArgName += utostr(i); 3167 MsgExprs[i]->getType().getAsStringInternal(ArgName, 3168 Context->getPrintingPolicy()); 3169 str += ", "; str += ArgName; 3170 } 3171 3172 str += ") {\n"; 3173 str += "\t unsigned size = sizeof("; 3174 str += returnType.getAsString(Context->getPrintingPolicy()); str += ");\n"; 3175 3176 str += "\t if (size == 1 || size == 2 || size == 4 || size == 8)\n"; 3177 3178 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy()); 3179 str += ")(void *)objc_msgSend)(receiver, sel"; 3180 for (unsigned i = 2; i < ArgTypes.size(); i++) { 3181 str += ", arg"; str += utostr(i); 3182 } 3183 // could be vararg. 3184 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) { 3185 str += ", arg"; str += utostr(i); 3186 } 3187 str+= ");\n"; 3188 3189 str += "\t else if (receiver == 0)\n"; 3190 str += "\t memset((void*)&s, 0, sizeof(s));\n"; 3191 str += "\t else\n"; 3192 3193 3194 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy()); 3195 str += ")(void *)objc_msgSend_stret)(receiver, sel"; 3196 for (unsigned i = 2; i < ArgTypes.size(); i++) { 3197 str += ", arg"; str += utostr(i); 3198 } 3199 // could be vararg. 3200 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) { 3201 str += ", arg"; str += utostr(i); 3202 } 3203 str += ");\n"; 3204 3205 3206 str += "\t}\n"; 3207 str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy()); 3208 str += " s;\n"; 3209 str += "};\n};\n\n"; 3210 SourceLocation FunLocStart; 3211 if (CurFunctionDef) 3212 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef); 3213 else { 3214 assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null"); 3215 FunLocStart = CurMethodDef->getLocStart(); 3216 } 3217 3218 InsertText(FunLocStart, str); 3219 ++stretCount; 3220 3221 // AST for __Stretn(receiver, args).s; 3222 IdentifierInfo *ID = &Context->Idents.get(name); 3223 FunctionDecl *FD = FunctionDecl::Create(*Context, TUDecl, SourceLocation(), 3224 SourceLocation(), ID, castType, 3225 nullptr, SC_Extern, false, false); 3226 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, castType, VK_RValue, 3227 SourceLocation()); 3228 CallExpr *STCE = new (Context) CallExpr(*Context, DRE, MsgExprs, 3229 castType, VK_LValue, SourceLocation()); 3230 3231 FieldDecl *FieldD = FieldDecl::Create(*Context, nullptr, SourceLocation(), 3232 SourceLocation(), 3233 &Context->Idents.get("s"), 3234 returnType, nullptr, 3235 /*BitWidth=*/nullptr, 3236 /*Mutable=*/true, ICIS_NoInit); 3237 MemberExpr *ME = new (Context) MemberExpr(STCE, false, FieldD, SourceLocation(), 3238 FieldD->getType(), VK_LValue, 3239 OK_Ordinary); 3240 3241 return ME; 3242 } 3243 3244 Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp, 3245 SourceLocation StartLoc, 3246 SourceLocation EndLoc) { 3247 if (!SelGetUidFunctionDecl) 3248 SynthSelGetUidFunctionDecl(); 3249 if (!MsgSendFunctionDecl) 3250 SynthMsgSendFunctionDecl(); 3251 if (!MsgSendSuperFunctionDecl) 3252 SynthMsgSendSuperFunctionDecl(); 3253 if (!MsgSendStretFunctionDecl) 3254 SynthMsgSendStretFunctionDecl(); 3255 if (!MsgSendSuperStretFunctionDecl) 3256 SynthMsgSendSuperStretFunctionDecl(); 3257 if (!MsgSendFpretFunctionDecl) 3258 SynthMsgSendFpretFunctionDecl(); 3259 if (!GetClassFunctionDecl) 3260 SynthGetClassFunctionDecl(); 3261 if (!GetSuperClassFunctionDecl) 3262 SynthGetSuperClassFunctionDecl(); 3263 if (!GetMetaClassFunctionDecl) 3264 SynthGetMetaClassFunctionDecl(); 3265 3266 // default to objc_msgSend(). 3267 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl; 3268 // May need to use objc_msgSend_stret() as well. 3269 FunctionDecl *MsgSendStretFlavor = nullptr; 3270 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) { 3271 QualType resultType = mDecl->getReturnType(); 3272 if (resultType->isRecordType()) 3273 MsgSendStretFlavor = MsgSendStretFunctionDecl; 3274 else if (resultType->isRealFloatingType()) 3275 MsgSendFlavor = MsgSendFpretFunctionDecl; 3276 } 3277 3278 // Synthesize a call to objc_msgSend(). 3279 SmallVector<Expr*, 8> MsgExprs; 3280 switch (Exp->getReceiverKind()) { 3281 case ObjCMessageExpr::SuperClass: { 3282 MsgSendFlavor = MsgSendSuperFunctionDecl; 3283 if (MsgSendStretFlavor) 3284 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl; 3285 assert(MsgSendFlavor && "MsgSendFlavor is NULL!"); 3286 3287 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface(); 3288 3289 SmallVector<Expr*, 4> InitExprs; 3290 3291 // set the receiver to self, the first argument to all methods. 3292 InitExprs.push_back( 3293 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(), 3294 CK_BitCast, 3295 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(), 3296 false, 3297 Context->getObjCIdType(), 3298 VK_RValue, 3299 SourceLocation())) 3300 ); // set the 'receiver'. 3301 3302 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass")) 3303 SmallVector<Expr*, 8> ClsExprs; 3304 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName())); 3305 // (Class)objc_getClass("CurrentClass") 3306 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl, 3307 &ClsExprs[0], 3308 ClsExprs.size(), 3309 StartLoc, 3310 EndLoc); 3311 ClsExprs.clear(); 3312 ClsExprs.push_back(Cls); 3313 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, 3314 &ClsExprs[0], ClsExprs.size(), 3315 StartLoc, EndLoc); 3316 3317 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass")) 3318 // To turn off a warning, type-cast to 'id' 3319 InitExprs.push_back( // set 'super class', using class_getSuperclass(). 3320 NoTypeInfoCStyleCastExpr(Context, 3321 Context->getObjCIdType(), 3322 CK_BitCast, Cls)); 3323 // struct __rw_objc_super 3324 QualType superType = getSuperStructType(); 3325 Expr *SuperRep; 3326 3327 if (LangOpts.MicrosoftExt) { 3328 SynthSuperConstructorFunctionDecl(); 3329 // Simulate a constructor call... 3330 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl, 3331 false, superType, VK_LValue, 3332 SourceLocation()); 3333 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs, 3334 superType, VK_LValue, 3335 SourceLocation()); 3336 // The code for super is a little tricky to prevent collision with 3337 // the structure definition in the header. The rewriter has it's own 3338 // internal definition (__rw_objc_super) that is uses. This is why 3339 // we need the cast below. For example: 3340 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER")) 3341 // 3342 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf, 3343 Context->getPointerType(SuperRep->getType()), 3344 VK_RValue, OK_Ordinary, 3345 SourceLocation()); 3346 SuperRep = NoTypeInfoCStyleCastExpr(Context, 3347 Context->getPointerType(superType), 3348 CK_BitCast, SuperRep); 3349 } else { 3350 // (struct __rw_objc_super) { <exprs from above> } 3351 InitListExpr *ILE = 3352 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs, 3353 SourceLocation()); 3354 TypeSourceInfo *superTInfo 3355 = Context->getTrivialTypeSourceInfo(superType); 3356 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo, 3357 superType, VK_LValue, 3358 ILE, false); 3359 // struct __rw_objc_super * 3360 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf, 3361 Context->getPointerType(SuperRep->getType()), 3362 VK_RValue, OK_Ordinary, 3363 SourceLocation()); 3364 } 3365 MsgExprs.push_back(SuperRep); 3366 break; 3367 } 3368 3369 case ObjCMessageExpr::Class: { 3370 SmallVector<Expr*, 8> ClsExprs; 3371 ObjCInterfaceDecl *Class 3372 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface(); 3373 IdentifierInfo *clsName = Class->getIdentifier(); 3374 ClsExprs.push_back(getStringLiteral(clsName->getName())); 3375 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, 3376 &ClsExprs[0], 3377 ClsExprs.size(), 3378 StartLoc, EndLoc); 3379 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context, 3380 Context->getObjCIdType(), 3381 CK_BitCast, Cls); 3382 MsgExprs.push_back(ArgExpr); 3383 break; 3384 } 3385 3386 case ObjCMessageExpr::SuperInstance:{ 3387 MsgSendFlavor = MsgSendSuperFunctionDecl; 3388 if (MsgSendStretFlavor) 3389 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl; 3390 assert(MsgSendFlavor && "MsgSendFlavor is NULL!"); 3391 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface(); 3392 SmallVector<Expr*, 4> InitExprs; 3393 3394 InitExprs.push_back( 3395 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(), 3396 CK_BitCast, 3397 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(), 3398 false, 3399 Context->getObjCIdType(), 3400 VK_RValue, SourceLocation())) 3401 ); // set the 'receiver'. 3402 3403 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass")) 3404 SmallVector<Expr*, 8> ClsExprs; 3405 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName())); 3406 // (Class)objc_getClass("CurrentClass") 3407 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, 3408 &ClsExprs[0], 3409 ClsExprs.size(), 3410 StartLoc, EndLoc); 3411 ClsExprs.clear(); 3412 ClsExprs.push_back(Cls); 3413 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, 3414 &ClsExprs[0], ClsExprs.size(), 3415 StartLoc, EndLoc); 3416 3417 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass")) 3418 // To turn off a warning, type-cast to 'id' 3419 InitExprs.push_back( 3420 // set 'super class', using class_getSuperclass(). 3421 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(), 3422 CK_BitCast, Cls)); 3423 // struct __rw_objc_super 3424 QualType superType = getSuperStructType(); 3425 Expr *SuperRep; 3426 3427 if (LangOpts.MicrosoftExt) { 3428 SynthSuperConstructorFunctionDecl(); 3429 // Simulate a constructor call... 3430 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl, 3431 false, superType, VK_LValue, 3432 SourceLocation()); 3433 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs, 3434 superType, VK_LValue, SourceLocation()); 3435 // The code for super is a little tricky to prevent collision with 3436 // the structure definition in the header. The rewriter has it's own 3437 // internal definition (__rw_objc_super) that is uses. This is why 3438 // we need the cast below. For example: 3439 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER")) 3440 // 3441 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf, 3442 Context->getPointerType(SuperRep->getType()), 3443 VK_RValue, OK_Ordinary, 3444 SourceLocation()); 3445 SuperRep = NoTypeInfoCStyleCastExpr(Context, 3446 Context->getPointerType(superType), 3447 CK_BitCast, SuperRep); 3448 } else { 3449 // (struct __rw_objc_super) { <exprs from above> } 3450 InitListExpr *ILE = 3451 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs, 3452 SourceLocation()); 3453 TypeSourceInfo *superTInfo 3454 = Context->getTrivialTypeSourceInfo(superType); 3455 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo, 3456 superType, VK_RValue, ILE, 3457 false); 3458 } 3459 MsgExprs.push_back(SuperRep); 3460 break; 3461 } 3462 3463 case ObjCMessageExpr::Instance: { 3464 // Remove all type-casts because it may contain objc-style types; e.g. 3465 // Foo<Proto> *. 3466 Expr *recExpr = Exp->getInstanceReceiver(); 3467 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr)) 3468 recExpr = CE->getSubExpr(); 3469 CastKind CK = recExpr->getType()->isObjCObjectPointerType() 3470 ? CK_BitCast : recExpr->getType()->isBlockPointerType() 3471 ? CK_BlockPointerToObjCPointerCast 3472 : CK_CPointerToObjCPointerCast; 3473 3474 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(), 3475 CK, recExpr); 3476 MsgExprs.push_back(recExpr); 3477 break; 3478 } 3479 } 3480 3481 // Create a call to sel_registerName("selName"), it will be the 2nd argument. 3482 SmallVector<Expr*, 8> SelExprs; 3483 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString())); 3484 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl, 3485 &SelExprs[0], SelExprs.size(), 3486 StartLoc, 3487 EndLoc); 3488 MsgExprs.push_back(SelExp); 3489 3490 // Now push any user supplied arguments. 3491 for (unsigned i = 0; i < Exp->getNumArgs(); i++) { 3492 Expr *userExpr = Exp->getArg(i); 3493 // Make all implicit casts explicit...ICE comes in handy:-) 3494 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) { 3495 // Reuse the ICE type, it is exactly what the doctor ordered. 3496 QualType type = ICE->getType(); 3497 if (needToScanForQualifiers(type)) 3498 type = Context->getObjCIdType(); 3499 // Make sure we convert "type (^)(...)" to "type (*)(...)". 3500 (void)convertBlockPointerToFunctionPointer(type); 3501 const Expr *SubExpr = ICE->IgnoreParenImpCasts(); 3502 CastKind CK; 3503 if (SubExpr->getType()->isIntegralType(*Context) && 3504 type->isBooleanType()) { 3505 CK = CK_IntegralToBoolean; 3506 } else if (type->isObjCObjectPointerType()) { 3507 if (SubExpr->getType()->isBlockPointerType()) { 3508 CK = CK_BlockPointerToObjCPointerCast; 3509 } else if (SubExpr->getType()->isPointerType()) { 3510 CK = CK_CPointerToObjCPointerCast; 3511 } else { 3512 CK = CK_BitCast; 3513 } 3514 } else { 3515 CK = CK_BitCast; 3516 } 3517 3518 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr); 3519 } 3520 // Make id<P...> cast into an 'id' cast. 3521 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) { 3522 if (CE->getType()->isObjCQualifiedIdType()) { 3523 while ((CE = dyn_cast<CStyleCastExpr>(userExpr))) 3524 userExpr = CE->getSubExpr(); 3525 CastKind CK; 3526 if (userExpr->getType()->isIntegralType(*Context)) { 3527 CK = CK_IntegralToPointer; 3528 } else if (userExpr->getType()->isBlockPointerType()) { 3529 CK = CK_BlockPointerToObjCPointerCast; 3530 } else if (userExpr->getType()->isPointerType()) { 3531 CK = CK_CPointerToObjCPointerCast; 3532 } else { 3533 CK = CK_BitCast; 3534 } 3535 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(), 3536 CK, userExpr); 3537 } 3538 } 3539 MsgExprs.push_back(userExpr); 3540 // We've transferred the ownership to MsgExprs. For now, we *don't* null 3541 // out the argument in the original expression (since we aren't deleting 3542 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info. 3543 //Exp->setArg(i, 0); 3544 } 3545 // Generate the funky cast. 3546 CastExpr *cast; 3547 SmallVector<QualType, 8> ArgTypes; 3548 QualType returnType; 3549 3550 // Push 'id' and 'SEL', the 2 implicit arguments. 3551 if (MsgSendFlavor == MsgSendSuperFunctionDecl) 3552 ArgTypes.push_back(Context->getPointerType(getSuperStructType())); 3553 else 3554 ArgTypes.push_back(Context->getObjCIdType()); 3555 ArgTypes.push_back(Context->getObjCSelType()); 3556 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) { 3557 // Push any user argument types. 3558 for (const auto *PI : OMD->params()) { 3559 QualType t = PI->getType()->isObjCQualifiedIdType() 3560 ? Context->getObjCIdType() 3561 : PI->getType(); 3562 // Make sure we convert "t (^)(...)" to "t (*)(...)". 3563 (void)convertBlockPointerToFunctionPointer(t); 3564 ArgTypes.push_back(t); 3565 } 3566 returnType = Exp->getType(); 3567 convertToUnqualifiedObjCType(returnType); 3568 (void)convertBlockPointerToFunctionPointer(returnType); 3569 } else { 3570 returnType = Context->getObjCIdType(); 3571 } 3572 // Get the type, we will need to reference it in a couple spots. 3573 QualType msgSendType = MsgSendFlavor->getType(); 3574 3575 // Create a reference to the objc_msgSend() declaration. 3576 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType, 3577 VK_LValue, SourceLocation()); 3578 3579 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid). 3580 // If we don't do this cast, we get the following bizarre warning/note: 3581 // xx.m:13: warning: function called through a non-compatible type 3582 // xx.m:13: note: if this code is reached, the program will abort 3583 cast = NoTypeInfoCStyleCastExpr(Context, 3584 Context->getPointerType(Context->VoidTy), 3585 CK_BitCast, DRE); 3586 3587 // Now do the "normal" pointer to function cast. 3588 // If we don't have a method decl, force a variadic cast. 3589 const ObjCMethodDecl *MD = Exp->getMethodDecl(); 3590 QualType castType = 3591 getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true); 3592 castType = Context->getPointerType(castType); 3593 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast, 3594 cast); 3595 3596 // Don't forget the parens to enforce the proper binding. 3597 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast); 3598 3599 const FunctionType *FT = msgSendType->getAs<FunctionType>(); 3600 CallExpr *CE = new (Context) 3601 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc); 3602 Stmt *ReplacingStmt = CE; 3603 if (MsgSendStretFlavor) { 3604 // We have the method which returns a struct/union. Must also generate 3605 // call to objc_msgSend_stret and hang both varieties on a conditional 3606 // expression which dictate which one to envoke depending on size of 3607 // method's return type. 3608 3609 Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor, 3610 returnType, 3611 ArgTypes, MsgExprs, 3612 Exp->getMethodDecl()); 3613 ReplacingStmt = STCE; 3614 } 3615 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info. 3616 return ReplacingStmt; 3617 } 3618 3619 Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) { 3620 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(), 3621 Exp->getLocEnd()); 3622 3623 // Now do the actual rewrite. 3624 ReplaceStmt(Exp, ReplacingStmt); 3625 3626 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info. 3627 return ReplacingStmt; 3628 } 3629 3630 // typedef struct objc_object Protocol; 3631 QualType RewriteModernObjC::getProtocolType() { 3632 if (!ProtocolTypeDecl) { 3633 TypeSourceInfo *TInfo 3634 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType()); 3635 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl, 3636 SourceLocation(), SourceLocation(), 3637 &Context->Idents.get("Protocol"), 3638 TInfo); 3639 } 3640 return Context->getTypeDeclType(ProtocolTypeDecl); 3641 } 3642 3643 /// RewriteObjCProtocolExpr - Rewrite a protocol expression into 3644 /// a synthesized/forward data reference (to the protocol's metadata). 3645 /// The forward references (and metadata) are generated in 3646 /// RewriteModernObjC::HandleTranslationUnit(). 3647 Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) { 3648 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" + 3649 Exp->getProtocol()->getNameAsString(); 3650 IdentifierInfo *ID = &Context->Idents.get(Name); 3651 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(), 3652 SourceLocation(), ID, getProtocolType(), 3653 nullptr, SC_Extern); 3654 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(), 3655 VK_LValue, SourceLocation()); 3656 CastExpr *castExpr = 3657 NoTypeInfoCStyleCastExpr( 3658 Context, Context->getPointerType(DRE->getType()), CK_BitCast, DRE); 3659 ReplaceStmt(Exp, castExpr); 3660 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl()); 3661 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info. 3662 return castExpr; 3663 3664 } 3665 3666 bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf, 3667 const char *endBuf) { 3668 while (startBuf < endBuf) { 3669 if (*startBuf == '#') { 3670 // Skip whitespace. 3671 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf) 3672 ; 3673 if (!strncmp(startBuf, "if", strlen("if")) || 3674 !strncmp(startBuf, "ifdef", strlen("ifdef")) || 3675 !strncmp(startBuf, "ifndef", strlen("ifndef")) || 3676 !strncmp(startBuf, "define", strlen("define")) || 3677 !strncmp(startBuf, "undef", strlen("undef")) || 3678 !strncmp(startBuf, "else", strlen("else")) || 3679 !strncmp(startBuf, "elif", strlen("elif")) || 3680 !strncmp(startBuf, "endif", strlen("endif")) || 3681 !strncmp(startBuf, "pragma", strlen("pragma")) || 3682 !strncmp(startBuf, "include", strlen("include")) || 3683 !strncmp(startBuf, "import", strlen("import")) || 3684 !strncmp(startBuf, "include_next", strlen("include_next"))) 3685 return true; 3686 } 3687 startBuf++; 3688 } 3689 return false; 3690 } 3691 3692 /// IsTagDefinedInsideClass - This routine checks that a named tagged type 3693 /// is defined inside an objective-c class. If so, it returns true. 3694 bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, 3695 TagDecl *Tag, 3696 bool &IsNamedDefinition) { 3697 if (!IDecl) 3698 return false; 3699 SourceLocation TagLocation; 3700 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) { 3701 RD = RD->getDefinition(); 3702 if (!RD || !RD->getDeclName().getAsIdentifierInfo()) 3703 return false; 3704 IsNamedDefinition = true; 3705 TagLocation = RD->getLocation(); 3706 return Context->getSourceManager().isBeforeInTranslationUnit( 3707 IDecl->getLocation(), TagLocation); 3708 } 3709 if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) { 3710 if (!ED || !ED->getDeclName().getAsIdentifierInfo()) 3711 return false; 3712 IsNamedDefinition = true; 3713 TagLocation = ED->getLocation(); 3714 return Context->getSourceManager().isBeforeInTranslationUnit( 3715 IDecl->getLocation(), TagLocation); 3716 3717 } 3718 return false; 3719 } 3720 3721 /// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer. 3722 /// It handles elaborated types, as well as enum types in the process. 3723 bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type, 3724 std::string &Result) { 3725 if (isa<TypedefType>(Type)) { 3726 Result += "\t"; 3727 return false; 3728 } 3729 3730 if (Type->isArrayType()) { 3731 QualType ElemTy = Context->getBaseElementType(Type); 3732 return RewriteObjCFieldDeclType(ElemTy, Result); 3733 } 3734 else if (Type->isRecordType()) { 3735 RecordDecl *RD = Type->getAs<RecordType>()->getDecl(); 3736 if (RD->isCompleteDefinition()) { 3737 if (RD->isStruct()) 3738 Result += "\n\tstruct "; 3739 else if (RD->isUnion()) 3740 Result += "\n\tunion "; 3741 else 3742 assert(false && "class not allowed as an ivar type"); 3743 3744 Result += RD->getName(); 3745 if (GlobalDefinedTags.count(RD)) { 3746 // struct/union is defined globally, use it. 3747 Result += " "; 3748 return true; 3749 } 3750 Result += " {\n"; 3751 for (auto *FD : RD->fields()) 3752 RewriteObjCFieldDecl(FD, Result); 3753 Result += "\t} "; 3754 return true; 3755 } 3756 } 3757 else if (Type->isEnumeralType()) { 3758 EnumDecl *ED = Type->getAs<EnumType>()->getDecl(); 3759 if (ED->isCompleteDefinition()) { 3760 Result += "\n\tenum "; 3761 Result += ED->getName(); 3762 if (GlobalDefinedTags.count(ED)) { 3763 // Enum is globall defined, use it. 3764 Result += " "; 3765 return true; 3766 } 3767 3768 Result += " {\n"; 3769 for (const auto *EC : ED->enumerators()) { 3770 Result += "\t"; Result += EC->getName(); Result += " = "; 3771 llvm::APSInt Val = EC->getInitVal(); 3772 Result += Val.toString(10); 3773 Result += ",\n"; 3774 } 3775 Result += "\t} "; 3776 return true; 3777 } 3778 } 3779 3780 Result += "\t"; 3781 convertObjCTypeToCStyleType(Type); 3782 return false; 3783 } 3784 3785 3786 /// RewriteObjCFieldDecl - This routine rewrites a field into the buffer. 3787 /// It handles elaborated types, as well as enum types in the process. 3788 void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl, 3789 std::string &Result) { 3790 QualType Type = fieldDecl->getType(); 3791 std::string Name = fieldDecl->getNameAsString(); 3792 3793 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result); 3794 if (!EleboratedType) 3795 Type.getAsStringInternal(Name, Context->getPrintingPolicy()); 3796 Result += Name; 3797 if (fieldDecl->isBitField()) { 3798 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context)); 3799 } 3800 else if (EleboratedType && Type->isArrayType()) { 3801 const ArrayType *AT = Context->getAsArrayType(Type); 3802 do { 3803 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) { 3804 Result += "["; 3805 llvm::APInt Dim = CAT->getSize(); 3806 Result += utostr(Dim.getZExtValue()); 3807 Result += "]"; 3808 } 3809 AT = Context->getAsArrayType(AT->getElementType()); 3810 } while (AT); 3811 } 3812 3813 Result += ";\n"; 3814 } 3815 3816 /// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined 3817 /// named aggregate types into the input buffer. 3818 void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl, 3819 std::string &Result) { 3820 QualType Type = fieldDecl->getType(); 3821 if (isa<TypedefType>(Type)) 3822 return; 3823 if (Type->isArrayType()) 3824 Type = Context->getBaseElementType(Type); 3825 ObjCContainerDecl *IDecl = 3826 dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext()); 3827 3828 TagDecl *TD = nullptr; 3829 if (Type->isRecordType()) { 3830 TD = Type->getAs<RecordType>()->getDecl(); 3831 } 3832 else if (Type->isEnumeralType()) { 3833 TD = Type->getAs<EnumType>()->getDecl(); 3834 } 3835 3836 if (TD) { 3837 if (GlobalDefinedTags.count(TD)) 3838 return; 3839 3840 bool IsNamedDefinition = false; 3841 if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) { 3842 RewriteObjCFieldDeclType(Type, Result); 3843 Result += ";"; 3844 } 3845 if (IsNamedDefinition) 3846 GlobalDefinedTags.insert(TD); 3847 } 3848 3849 } 3850 3851 unsigned RewriteModernObjC::ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV) { 3852 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface(); 3853 if (ObjCInterefaceHasBitfieldGroups.count(CDecl)) { 3854 return IvarGroupNumber[IV]; 3855 } 3856 unsigned GroupNo = 0; 3857 SmallVector<const ObjCIvarDecl *, 8> IVars; 3858 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin(); 3859 IVD; IVD = IVD->getNextIvar()) 3860 IVars.push_back(IVD); 3861 3862 for (unsigned i = 0, e = IVars.size(); i < e; i++) 3863 if (IVars[i]->isBitField()) { 3864 IvarGroupNumber[IVars[i++]] = ++GroupNo; 3865 while (i < e && IVars[i]->isBitField()) 3866 IvarGroupNumber[IVars[i++]] = GroupNo; 3867 if (i < e) 3868 --i; 3869 } 3870 3871 ObjCInterefaceHasBitfieldGroups.insert(CDecl); 3872 return IvarGroupNumber[IV]; 3873 } 3874 3875 QualType RewriteModernObjC::SynthesizeBitfieldGroupStructType( 3876 ObjCIvarDecl *IV, 3877 SmallVectorImpl<ObjCIvarDecl *> &IVars) { 3878 std::string StructTagName; 3879 ObjCIvarBitfieldGroupType(IV, StructTagName); 3880 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, 3881 Context->getTranslationUnitDecl(), 3882 SourceLocation(), SourceLocation(), 3883 &Context->Idents.get(StructTagName)); 3884 for (unsigned i=0, e = IVars.size(); i < e; i++) { 3885 ObjCIvarDecl *Ivar = IVars[i]; 3886 RD->addDecl(FieldDecl::Create(*Context, RD, SourceLocation(), SourceLocation(), 3887 &Context->Idents.get(Ivar->getName()), 3888 Ivar->getType(), 3889 nullptr, /*Expr *BW */Ivar->getBitWidth(), 3890 false, ICIS_NoInit)); 3891 } 3892 RD->completeDefinition(); 3893 return Context->getTagDeclType(RD); 3894 } 3895 3896 QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV) { 3897 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface(); 3898 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV); 3899 std::pair<const ObjCInterfaceDecl*, unsigned> tuple = std::make_pair(CDecl, GroupNo); 3900 if (GroupRecordType.count(tuple)) 3901 return GroupRecordType[tuple]; 3902 3903 SmallVector<ObjCIvarDecl *, 8> IVars; 3904 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin(); 3905 IVD; IVD = IVD->getNextIvar()) { 3906 if (IVD->isBitField()) 3907 IVars.push_back(const_cast<ObjCIvarDecl *>(IVD)); 3908 else { 3909 if (!IVars.empty()) { 3910 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]); 3911 // Generate the struct type for this group of bitfield ivars. 3912 GroupRecordType[std::make_pair(CDecl, GroupNo)] = 3913 SynthesizeBitfieldGroupStructType(IVars[0], IVars); 3914 IVars.clear(); 3915 } 3916 } 3917 } 3918 if (!IVars.empty()) { 3919 // Do the last one. 3920 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]); 3921 GroupRecordType[std::make_pair(CDecl, GroupNo)] = 3922 SynthesizeBitfieldGroupStructType(IVars[0], IVars); 3923 } 3924 QualType RetQT = GroupRecordType[tuple]; 3925 assert(!RetQT.isNull() && "GetGroupRecordTypeForObjCIvarBitfield struct type is NULL"); 3926 3927 return RetQT; 3928 } 3929 3930 /// ObjCIvarBitfieldGroupDecl - Names field decl. for ivar bitfield group. 3931 /// Name would be: classname__GRBF_n where n is the group number for this ivar. 3932 void RewriteModernObjC::ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV, 3933 std::string &Result) { 3934 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface(); 3935 Result += CDecl->getName(); 3936 Result += "__GRBF_"; 3937 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV); 3938 Result += utostr(GroupNo); 3939 return; 3940 } 3941 3942 /// ObjCIvarBitfieldGroupType - Names struct type for ivar bitfield group. 3943 /// Name of the struct would be: classname__T_n where n is the group number for 3944 /// this ivar. 3945 void RewriteModernObjC::ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV, 3946 std::string &Result) { 3947 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface(); 3948 Result += CDecl->getName(); 3949 Result += "__T_"; 3950 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV); 3951 Result += utostr(GroupNo); 3952 return; 3953 } 3954 3955 /// ObjCIvarBitfieldGroupOffset - Names symbol for ivar bitfield group field offset. 3956 /// Name would be: OBJC_IVAR_$_classname__GRBF_n where n is the group number for 3957 /// this ivar. 3958 void RewriteModernObjC::ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV, 3959 std::string &Result) { 3960 Result += "OBJC_IVAR_$_"; 3961 ObjCIvarBitfieldGroupDecl(IV, Result); 3962 } 3963 3964 #define SKIP_BITFIELDS(IX, ENDIX, VEC) { \ 3965 while ((IX < ENDIX) && VEC[IX]->isBitField()) \ 3966 ++IX; \ 3967 if (IX < ENDIX) \ 3968 --IX; \ 3969 } 3970 3971 /// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to 3972 /// an objective-c class with ivars. 3973 void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl, 3974 std::string &Result) { 3975 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct"); 3976 assert(CDecl->getName() != "" && 3977 "Name missing in SynthesizeObjCInternalStruct"); 3978 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass(); 3979 SmallVector<ObjCIvarDecl *, 8> IVars; 3980 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin(); 3981 IVD; IVD = IVD->getNextIvar()) 3982 IVars.push_back(IVD); 3983 3984 SourceLocation LocStart = CDecl->getLocStart(); 3985 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc(); 3986 3987 const char *startBuf = SM->getCharacterData(LocStart); 3988 const char *endBuf = SM->getCharacterData(LocEnd); 3989 3990 // If no ivars and no root or if its root, directly or indirectly, 3991 // have no ivars (thus not synthesized) then no need to synthesize this class. 3992 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) && 3993 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) { 3994 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts); 3995 ReplaceText(LocStart, endBuf-startBuf, Result); 3996 return; 3997 } 3998 3999 // Insert named struct/union definitions inside class to 4000 // outer scope. This follows semantics of locally defined 4001 // struct/unions in objective-c classes. 4002 for (unsigned i = 0, e = IVars.size(); i < e; i++) 4003 RewriteLocallyDefinedNamedAggregates(IVars[i], Result); 4004 4005 // Insert named structs which are syntheized to group ivar bitfields 4006 // to outer scope as well. 4007 for (unsigned i = 0, e = IVars.size(); i < e; i++) 4008 if (IVars[i]->isBitField()) { 4009 ObjCIvarDecl *IV = IVars[i]; 4010 QualType QT = GetGroupRecordTypeForObjCIvarBitfield(IV); 4011 RewriteObjCFieldDeclType(QT, Result); 4012 Result += ";"; 4013 // skip over ivar bitfields in this group. 4014 SKIP_BITFIELDS(i , e, IVars); 4015 } 4016 4017 Result += "\nstruct "; 4018 Result += CDecl->getNameAsString(); 4019 Result += "_IMPL {\n"; 4020 4021 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) { 4022 Result += "\tstruct "; Result += RCDecl->getNameAsString(); 4023 Result += "_IMPL "; Result += RCDecl->getNameAsString(); 4024 Result += "_IVARS;\n"; 4025 } 4026 4027 for (unsigned i = 0, e = IVars.size(); i < e; i++) { 4028 if (IVars[i]->isBitField()) { 4029 ObjCIvarDecl *IV = IVars[i]; 4030 Result += "\tstruct "; 4031 ObjCIvarBitfieldGroupType(IV, Result); Result += " "; 4032 ObjCIvarBitfieldGroupDecl(IV, Result); Result += ";\n"; 4033 // skip over ivar bitfields in this group. 4034 SKIP_BITFIELDS(i , e, IVars); 4035 } 4036 else 4037 RewriteObjCFieldDecl(IVars[i], Result); 4038 } 4039 4040 Result += "};\n"; 4041 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts); 4042 ReplaceText(LocStart, endBuf-startBuf, Result); 4043 // Mark this struct as having been generated. 4044 if (!ObjCSynthesizedStructs.insert(CDecl)) 4045 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct"); 4046 } 4047 4048 /// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which 4049 /// have been referenced in an ivar access expression. 4050 void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl, 4051 std::string &Result) { 4052 // write out ivar offset symbols which have been referenced in an ivar 4053 // access expression. 4054 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl]; 4055 if (Ivars.empty()) 4056 return; 4057 4058 llvm::DenseSet<std::pair<const ObjCInterfaceDecl*, unsigned> > GroupSymbolOutput; 4059 for (ObjCIvarDecl *IvarDecl : Ivars) { 4060 const ObjCInterfaceDecl *IDecl = IvarDecl->getContainingInterface(); 4061 unsigned GroupNo = 0; 4062 if (IvarDecl->isBitField()) { 4063 GroupNo = ObjCIvarBitfieldGroupNo(IvarDecl); 4064 if (GroupSymbolOutput.count(std::make_pair(IDecl, GroupNo))) 4065 continue; 4066 } 4067 Result += "\n"; 4068 if (LangOpts.MicrosoftExt) 4069 Result += "__declspec(allocate(\".objc_ivar$B\")) "; 4070 Result += "extern \"C\" "; 4071 if (LangOpts.MicrosoftExt && 4072 IvarDecl->getAccessControl() != ObjCIvarDecl::Private && 4073 IvarDecl->getAccessControl() != ObjCIvarDecl::Package) 4074 Result += "__declspec(dllimport) "; 4075 4076 Result += "unsigned long "; 4077 if (IvarDecl->isBitField()) { 4078 ObjCIvarBitfieldGroupOffset(IvarDecl, Result); 4079 GroupSymbolOutput.insert(std::make_pair(IDecl, GroupNo)); 4080 } 4081 else 4082 WriteInternalIvarName(CDecl, IvarDecl, Result); 4083 Result += ";"; 4084 } 4085 } 4086 4087 //===----------------------------------------------------------------------===// 4088 // Meta Data Emission 4089 //===----------------------------------------------------------------------===// 4090 4091 4092 /// RewriteImplementations - This routine rewrites all method implementations 4093 /// and emits meta-data. 4094 4095 void RewriteModernObjC::RewriteImplementations() { 4096 int ClsDefCount = ClassImplementation.size(); 4097 int CatDefCount = CategoryImplementation.size(); 4098 4099 // Rewrite implemented methods 4100 for (int i = 0; i < ClsDefCount; i++) { 4101 ObjCImplementationDecl *OIMP = ClassImplementation[i]; 4102 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface(); 4103 if (CDecl->isImplicitInterfaceDecl()) 4104 assert(false && 4105 "Legacy implicit interface rewriting not supported in moder abi"); 4106 RewriteImplementationDecl(OIMP); 4107 } 4108 4109 for (int i = 0; i < CatDefCount; i++) { 4110 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i]; 4111 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface(); 4112 if (CDecl->isImplicitInterfaceDecl()) 4113 assert(false && 4114 "Legacy implicit interface rewriting not supported in moder abi"); 4115 RewriteImplementationDecl(CIMP); 4116 } 4117 } 4118 4119 void RewriteModernObjC::RewriteByRefString(std::string &ResultStr, 4120 const std::string &Name, 4121 ValueDecl *VD, bool def) { 4122 assert(BlockByRefDeclNo.count(VD) && 4123 "RewriteByRefString: ByRef decl missing"); 4124 if (def) 4125 ResultStr += "struct "; 4126 ResultStr += "__Block_byref_" + Name + 4127 "_" + utostr(BlockByRefDeclNo[VD]) ; 4128 } 4129 4130 static bool HasLocalVariableExternalStorage(ValueDecl *VD) { 4131 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) 4132 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage()); 4133 return false; 4134 } 4135 4136 std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i, 4137 StringRef funcName, 4138 std::string Tag) { 4139 const FunctionType *AFT = CE->getFunctionType(); 4140 QualType RT = AFT->getReturnType(); 4141 std::string StructRef = "struct " + Tag; 4142 SourceLocation BlockLoc = CE->getExprLoc(); 4143 std::string S; 4144 ConvertSourceLocationToLineDirective(BlockLoc, S); 4145 4146 S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" + 4147 funcName.str() + "_block_func_" + utostr(i); 4148 4149 BlockDecl *BD = CE->getBlockDecl(); 4150 4151 if (isa<FunctionNoProtoType>(AFT)) { 4152 // No user-supplied arguments. Still need to pass in a pointer to the 4153 // block (to reference imported block decl refs). 4154 S += "(" + StructRef + " *__cself)"; 4155 } else if (BD->param_empty()) { 4156 S += "(" + StructRef + " *__cself)"; 4157 } else { 4158 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT); 4159 assert(FT && "SynthesizeBlockFunc: No function proto"); 4160 S += '('; 4161 // first add the implicit argument. 4162 S += StructRef + " *__cself, "; 4163 std::string ParamStr; 4164 for (BlockDecl::param_iterator AI = BD->param_begin(), 4165 E = BD->param_end(); AI != E; ++AI) { 4166 if (AI != BD->param_begin()) S += ", "; 4167 ParamStr = (*AI)->getNameAsString(); 4168 QualType QT = (*AI)->getType(); 4169 (void)convertBlockPointerToFunctionPointer(QT); 4170 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy()); 4171 S += ParamStr; 4172 } 4173 if (FT->isVariadic()) { 4174 if (!BD->param_empty()) S += ", "; 4175 S += "..."; 4176 } 4177 S += ')'; 4178 } 4179 S += " {\n"; 4180 4181 // Create local declarations to avoid rewriting all closure decl ref exprs. 4182 // First, emit a declaration for all "by ref" decls. 4183 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(), 4184 E = BlockByRefDecls.end(); I != E; ++I) { 4185 S += " "; 4186 std::string Name = (*I)->getNameAsString(); 4187 std::string TypeString; 4188 RewriteByRefString(TypeString, Name, (*I)); 4189 TypeString += " *"; 4190 Name = TypeString + Name; 4191 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n"; 4192 } 4193 // Next, emit a declaration for all "by copy" declarations. 4194 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(), 4195 E = BlockByCopyDecls.end(); I != E; ++I) { 4196 S += " "; 4197 // Handle nested closure invocation. For example: 4198 // 4199 // void (^myImportedClosure)(void); 4200 // myImportedClosure = ^(void) { setGlobalInt(x + y); }; 4201 // 4202 // void (^anotherClosure)(void); 4203 // anotherClosure = ^(void) { 4204 // myImportedClosure(); // import and invoke the closure 4205 // }; 4206 // 4207 if (isTopLevelBlockPointerType((*I)->getType())) { 4208 RewriteBlockPointerTypeVariable(S, (*I)); 4209 S += " = ("; 4210 RewriteBlockPointerType(S, (*I)->getType()); 4211 S += ")"; 4212 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n"; 4213 } 4214 else { 4215 std::string Name = (*I)->getNameAsString(); 4216 QualType QT = (*I)->getType(); 4217 if (HasLocalVariableExternalStorage(*I)) 4218 QT = Context->getPointerType(QT); 4219 QT.getAsStringInternal(Name, Context->getPrintingPolicy()); 4220 S += Name + " = __cself->" + 4221 (*I)->getNameAsString() + "; // bound by copy\n"; 4222 } 4223 } 4224 std::string RewrittenStr = RewrittenBlockExprs[CE]; 4225 const char *cstr = RewrittenStr.c_str(); 4226 while (*cstr++ != '{') ; 4227 S += cstr; 4228 S += "\n"; 4229 return S; 4230 } 4231 4232 std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i, 4233 StringRef funcName, 4234 std::string Tag) { 4235 std::string StructRef = "struct " + Tag; 4236 std::string S = "static void __"; 4237 4238 S += funcName; 4239 S += "_block_copy_" + utostr(i); 4240 S += "(" + StructRef; 4241 S += "*dst, " + StructRef; 4242 S += "*src) {"; 4243 for (ValueDecl *VD : ImportedBlockDecls) { 4244 S += "_Block_object_assign((void*)&dst->"; 4245 S += VD->getNameAsString(); 4246 S += ", (void*)src->"; 4247 S += VD->getNameAsString(); 4248 if (BlockByRefDeclsPtrSet.count(VD)) 4249 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);"; 4250 else if (VD->getType()->isBlockPointerType()) 4251 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);"; 4252 else 4253 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);"; 4254 } 4255 S += "}\n"; 4256 4257 S += "\nstatic void __"; 4258 S += funcName; 4259 S += "_block_dispose_" + utostr(i); 4260 S += "(" + StructRef; 4261 S += "*src) {"; 4262 for (ValueDecl *VD : ImportedBlockDecls) { 4263 S += "_Block_object_dispose((void*)src->"; 4264 S += VD->getNameAsString(); 4265 if (BlockByRefDeclsPtrSet.count(VD)) 4266 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);"; 4267 else if (VD->getType()->isBlockPointerType()) 4268 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);"; 4269 else 4270 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);"; 4271 } 4272 S += "}\n"; 4273 return S; 4274 } 4275 4276 std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag, 4277 std::string Desc) { 4278 std::string S = "\nstruct " + Tag; 4279 std::string Constructor = " " + Tag; 4280 4281 S += " {\n struct __block_impl impl;\n"; 4282 S += " struct " + Desc; 4283 S += "* Desc;\n"; 4284 4285 Constructor += "(void *fp, "; // Invoke function pointer. 4286 Constructor += "struct " + Desc; // Descriptor pointer. 4287 Constructor += " *desc"; 4288 4289 if (BlockDeclRefs.size()) { 4290 // Output all "by copy" declarations. 4291 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(), 4292 E = BlockByCopyDecls.end(); I != E; ++I) { 4293 S += " "; 4294 std::string FieldName = (*I)->getNameAsString(); 4295 std::string ArgName = "_" + FieldName; 4296 // Handle nested closure invocation. For example: 4297 // 4298 // void (^myImportedBlock)(void); 4299 // myImportedBlock = ^(void) { setGlobalInt(x + y); }; 4300 // 4301 // void (^anotherBlock)(void); 4302 // anotherBlock = ^(void) { 4303 // myImportedBlock(); // import and invoke the closure 4304 // }; 4305 // 4306 if (isTopLevelBlockPointerType((*I)->getType())) { 4307 S += "struct __block_impl *"; 4308 Constructor += ", void *" + ArgName; 4309 } else { 4310 QualType QT = (*I)->getType(); 4311 if (HasLocalVariableExternalStorage(*I)) 4312 QT = Context->getPointerType(QT); 4313 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy()); 4314 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy()); 4315 Constructor += ", " + ArgName; 4316 } 4317 S += FieldName + ";\n"; 4318 } 4319 // Output all "by ref" declarations. 4320 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(), 4321 E = BlockByRefDecls.end(); I != E; ++I) { 4322 S += " "; 4323 std::string FieldName = (*I)->getNameAsString(); 4324 std::string ArgName = "_" + FieldName; 4325 { 4326 std::string TypeString; 4327 RewriteByRefString(TypeString, FieldName, (*I)); 4328 TypeString += " *"; 4329 FieldName = TypeString + FieldName; 4330 ArgName = TypeString + ArgName; 4331 Constructor += ", " + ArgName; 4332 } 4333 S += FieldName + "; // by ref\n"; 4334 } 4335 // Finish writing the constructor. 4336 Constructor += ", int flags=0)"; 4337 // Initialize all "by copy" arguments. 4338 bool firsTime = true; 4339 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(), 4340 E = BlockByCopyDecls.end(); I != E; ++I) { 4341 std::string Name = (*I)->getNameAsString(); 4342 if (firsTime) { 4343 Constructor += " : "; 4344 firsTime = false; 4345 } 4346 else 4347 Constructor += ", "; 4348 if (isTopLevelBlockPointerType((*I)->getType())) 4349 Constructor += Name + "((struct __block_impl *)_" + Name + ")"; 4350 else 4351 Constructor += Name + "(_" + Name + ")"; 4352 } 4353 // Initialize all "by ref" arguments. 4354 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(), 4355 E = BlockByRefDecls.end(); I != E; ++I) { 4356 std::string Name = (*I)->getNameAsString(); 4357 if (firsTime) { 4358 Constructor += " : "; 4359 firsTime = false; 4360 } 4361 else 4362 Constructor += ", "; 4363 Constructor += Name + "(_" + Name + "->__forwarding)"; 4364 } 4365 4366 Constructor += " {\n"; 4367 if (GlobalVarDecl) 4368 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n"; 4369 else 4370 Constructor += " impl.isa = &_NSConcreteStackBlock;\n"; 4371 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n"; 4372 4373 Constructor += " Desc = desc;\n"; 4374 } else { 4375 // Finish writing the constructor. 4376 Constructor += ", int flags=0) {\n"; 4377 if (GlobalVarDecl) 4378 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n"; 4379 else 4380 Constructor += " impl.isa = &_NSConcreteStackBlock;\n"; 4381 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n"; 4382 Constructor += " Desc = desc;\n"; 4383 } 4384 Constructor += " "; 4385 Constructor += "}\n"; 4386 S += Constructor; 4387 S += "};\n"; 4388 return S; 4389 } 4390 4391 std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag, 4392 std::string ImplTag, int i, 4393 StringRef FunName, 4394 unsigned hasCopy) { 4395 std::string S = "\nstatic struct " + DescTag; 4396 4397 S += " {\n size_t reserved;\n"; 4398 S += " size_t Block_size;\n"; 4399 if (hasCopy) { 4400 S += " void (*copy)(struct "; 4401 S += ImplTag; S += "*, struct "; 4402 S += ImplTag; S += "*);\n"; 4403 4404 S += " void (*dispose)(struct "; 4405 S += ImplTag; S += "*);\n"; 4406 } 4407 S += "} "; 4408 4409 S += DescTag + "_DATA = { 0, sizeof(struct "; 4410 S += ImplTag + ")"; 4411 if (hasCopy) { 4412 S += ", __" + FunName.str() + "_block_copy_" + utostr(i); 4413 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i); 4414 } 4415 S += "};\n"; 4416 return S; 4417 } 4418 4419 void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart, 4420 StringRef FunName) { 4421 bool RewriteSC = (GlobalVarDecl && 4422 !Blocks.empty() && 4423 GlobalVarDecl->getStorageClass() == SC_Static && 4424 GlobalVarDecl->getType().getCVRQualifiers()); 4425 if (RewriteSC) { 4426 std::string SC(" void __"); 4427 SC += GlobalVarDecl->getNameAsString(); 4428 SC += "() {}"; 4429 InsertText(FunLocStart, SC); 4430 } 4431 4432 // Insert closures that were part of the function. 4433 for (unsigned i = 0, count=0; i < Blocks.size(); i++) { 4434 CollectBlockDeclRefInfo(Blocks[i]); 4435 // Need to copy-in the inner copied-in variables not actually used in this 4436 // block. 4437 for (int j = 0; j < InnerDeclRefsCount[i]; j++) { 4438 DeclRefExpr *Exp = InnerDeclRefs[count++]; 4439 ValueDecl *VD = Exp->getDecl(); 4440 BlockDeclRefs.push_back(Exp); 4441 if (!VD->hasAttr<BlocksAttr>()) { 4442 if (!BlockByCopyDeclsPtrSet.count(VD)) { 4443 BlockByCopyDeclsPtrSet.insert(VD); 4444 BlockByCopyDecls.push_back(VD); 4445 } 4446 continue; 4447 } 4448 4449 if (!BlockByRefDeclsPtrSet.count(VD)) { 4450 BlockByRefDeclsPtrSet.insert(VD); 4451 BlockByRefDecls.push_back(VD); 4452 } 4453 4454 // imported objects in the inner blocks not used in the outer 4455 // blocks must be copied/disposed in the outer block as well. 4456 if (VD->getType()->isObjCObjectPointerType() || 4457 VD->getType()->isBlockPointerType()) 4458 ImportedBlockDecls.insert(VD); 4459 } 4460 4461 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i); 4462 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i); 4463 4464 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag); 4465 4466 InsertText(FunLocStart, CI); 4467 4468 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag); 4469 4470 InsertText(FunLocStart, CF); 4471 4472 if (ImportedBlockDecls.size()) { 4473 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag); 4474 InsertText(FunLocStart, HF); 4475 } 4476 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName, 4477 ImportedBlockDecls.size() > 0); 4478 InsertText(FunLocStart, BD); 4479 4480 BlockDeclRefs.clear(); 4481 BlockByRefDecls.clear(); 4482 BlockByRefDeclsPtrSet.clear(); 4483 BlockByCopyDecls.clear(); 4484 BlockByCopyDeclsPtrSet.clear(); 4485 ImportedBlockDecls.clear(); 4486 } 4487 if (RewriteSC) { 4488 // Must insert any 'const/volatile/static here. Since it has been 4489 // removed as result of rewriting of block literals. 4490 std::string SC; 4491 if (GlobalVarDecl->getStorageClass() == SC_Static) 4492 SC = "static "; 4493 if (GlobalVarDecl->getType().isConstQualified()) 4494 SC += "const "; 4495 if (GlobalVarDecl->getType().isVolatileQualified()) 4496 SC += "volatile "; 4497 if (GlobalVarDecl->getType().isRestrictQualified()) 4498 SC += "restrict "; 4499 InsertText(FunLocStart, SC); 4500 } 4501 if (GlobalConstructionExp) { 4502 // extra fancy dance for global literal expression. 4503 4504 // Always the latest block expression on the block stack. 4505 std::string Tag = "__"; 4506 Tag += FunName; 4507 Tag += "_block_impl_"; 4508 Tag += utostr(Blocks.size()-1); 4509 std::string globalBuf = "static "; 4510 globalBuf += Tag; globalBuf += " "; 4511 std::string SStr; 4512 4513 llvm::raw_string_ostream constructorExprBuf(SStr); 4514 GlobalConstructionExp->printPretty(constructorExprBuf, nullptr, 4515 PrintingPolicy(LangOpts)); 4516 globalBuf += constructorExprBuf.str(); 4517 globalBuf += ";\n"; 4518 InsertText(FunLocStart, globalBuf); 4519 GlobalConstructionExp = nullptr; 4520 } 4521 4522 Blocks.clear(); 4523 InnerDeclRefsCount.clear(); 4524 InnerDeclRefs.clear(); 4525 RewrittenBlockExprs.clear(); 4526 } 4527 4528 void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) { 4529 SourceLocation FunLocStart = 4530 (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD) 4531 : FD->getTypeSpecStartLoc(); 4532 StringRef FuncName = FD->getName(); 4533 4534 SynthesizeBlockLiterals(FunLocStart, FuncName); 4535 } 4536 4537 static void BuildUniqueMethodName(std::string &Name, 4538 ObjCMethodDecl *MD) { 4539 ObjCInterfaceDecl *IFace = MD->getClassInterface(); 4540 Name = IFace->getName(); 4541 Name += "__" + MD->getSelector().getAsString(); 4542 // Convert colons to underscores. 4543 std::string::size_type loc = 0; 4544 while ((loc = Name.find(":", loc)) != std::string::npos) 4545 Name.replace(loc, 1, "_"); 4546 } 4547 4548 void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) { 4549 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n"); 4550 //SourceLocation FunLocStart = MD->getLocStart(); 4551 SourceLocation FunLocStart = MD->getLocStart(); 4552 std::string FuncName; 4553 BuildUniqueMethodName(FuncName, MD); 4554 SynthesizeBlockLiterals(FunLocStart, FuncName); 4555 } 4556 4557 void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) { 4558 for (Stmt::child_range CI = S->children(); CI; ++CI) 4559 if (*CI) { 4560 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) 4561 GetBlockDeclRefExprs(CBE->getBody()); 4562 else 4563 GetBlockDeclRefExprs(*CI); 4564 } 4565 // Handle specific things. 4566 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) { 4567 if (DRE->refersToEnclosingLocal()) { 4568 // FIXME: Handle enums. 4569 if (!isa<FunctionDecl>(DRE->getDecl())) 4570 BlockDeclRefs.push_back(DRE); 4571 if (HasLocalVariableExternalStorage(DRE->getDecl())) 4572 BlockDeclRefs.push_back(DRE); 4573 } 4574 } 4575 4576 return; 4577 } 4578 4579 void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S, 4580 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs, 4581 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts) { 4582 for (Stmt::child_range CI = S->children(); CI; ++CI) 4583 if (*CI) { 4584 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) { 4585 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl())); 4586 GetInnerBlockDeclRefExprs(CBE->getBody(), 4587 InnerBlockDeclRefs, 4588 InnerContexts); 4589 } 4590 else 4591 GetInnerBlockDeclRefExprs(*CI, 4592 InnerBlockDeclRefs, 4593 InnerContexts); 4594 4595 } 4596 // Handle specific things. 4597 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) { 4598 if (DRE->refersToEnclosingLocal()) { 4599 if (!isa<FunctionDecl>(DRE->getDecl()) && 4600 !InnerContexts.count(DRE->getDecl()->getDeclContext())) 4601 InnerBlockDeclRefs.push_back(DRE); 4602 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) 4603 if (Var->isFunctionOrMethodVarDecl()) 4604 ImportedLocalExternalDecls.insert(Var); 4605 } 4606 } 4607 4608 return; 4609 } 4610 4611 /// convertObjCTypeToCStyleType - This routine converts such objc types 4612 /// as qualified objects, and blocks to their closest c/c++ types that 4613 /// it can. It returns true if input type was modified. 4614 bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) { 4615 QualType oldT = T; 4616 convertBlockPointerToFunctionPointer(T); 4617 if (T->isFunctionPointerType()) { 4618 QualType PointeeTy; 4619 if (const PointerType* PT = T->getAs<PointerType>()) { 4620 PointeeTy = PT->getPointeeType(); 4621 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) { 4622 T = convertFunctionTypeOfBlocks(FT); 4623 T = Context->getPointerType(T); 4624 } 4625 } 4626 } 4627 4628 convertToUnqualifiedObjCType(T); 4629 return T != oldT; 4630 } 4631 4632 /// convertFunctionTypeOfBlocks - This routine converts a function type 4633 /// whose result type may be a block pointer or whose argument type(s) 4634 /// might be block pointers to an equivalent function type replacing 4635 /// all block pointers to function pointers. 4636 QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) { 4637 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT); 4638 // FTP will be null for closures that don't take arguments. 4639 // Generate a funky cast. 4640 SmallVector<QualType, 8> ArgTypes; 4641 QualType Res = FT->getReturnType(); 4642 bool modified = convertObjCTypeToCStyleType(Res); 4643 4644 if (FTP) { 4645 for (auto &I : FTP->param_types()) { 4646 QualType t = I; 4647 // Make sure we convert "t (^)(...)" to "t (*)(...)". 4648 if (convertObjCTypeToCStyleType(t)) 4649 modified = true; 4650 ArgTypes.push_back(t); 4651 } 4652 } 4653 QualType FuncType; 4654 if (modified) 4655 FuncType = getSimpleFunctionType(Res, ArgTypes); 4656 else FuncType = QualType(FT, 0); 4657 return FuncType; 4658 } 4659 4660 Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) { 4661 // Navigate to relevant type information. 4662 const BlockPointerType *CPT = nullptr; 4663 4664 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) { 4665 CPT = DRE->getType()->getAs<BlockPointerType>(); 4666 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) { 4667 CPT = MExpr->getType()->getAs<BlockPointerType>(); 4668 } 4669 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) { 4670 return SynthesizeBlockCall(Exp, PRE->getSubExpr()); 4671 } 4672 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp)) 4673 CPT = IEXPR->getType()->getAs<BlockPointerType>(); 4674 else if (const ConditionalOperator *CEXPR = 4675 dyn_cast<ConditionalOperator>(BlockExp)) { 4676 Expr *LHSExp = CEXPR->getLHS(); 4677 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp); 4678 Expr *RHSExp = CEXPR->getRHS(); 4679 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp); 4680 Expr *CONDExp = CEXPR->getCond(); 4681 ConditionalOperator *CondExpr = 4682 new (Context) ConditionalOperator(CONDExp, 4683 SourceLocation(), cast<Expr>(LHSStmt), 4684 SourceLocation(), cast<Expr>(RHSStmt), 4685 Exp->getType(), VK_RValue, OK_Ordinary); 4686 return CondExpr; 4687 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) { 4688 CPT = IRE->getType()->getAs<BlockPointerType>(); 4689 } else if (const PseudoObjectExpr *POE 4690 = dyn_cast<PseudoObjectExpr>(BlockExp)) { 4691 CPT = POE->getType()->castAs<BlockPointerType>(); 4692 } else { 4693 assert(1 && "RewriteBlockClass: Bad type"); 4694 } 4695 assert(CPT && "RewriteBlockClass: Bad type"); 4696 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>(); 4697 assert(FT && "RewriteBlockClass: Bad type"); 4698 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT); 4699 // FTP will be null for closures that don't take arguments. 4700 4701 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl, 4702 SourceLocation(), SourceLocation(), 4703 &Context->Idents.get("__block_impl")); 4704 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD)); 4705 4706 // Generate a funky cast. 4707 SmallVector<QualType, 8> ArgTypes; 4708 4709 // Push the block argument type. 4710 ArgTypes.push_back(PtrBlock); 4711 if (FTP) { 4712 for (auto &I : FTP->param_types()) { 4713 QualType t = I; 4714 // Make sure we convert "t (^)(...)" to "t (*)(...)". 4715 if (!convertBlockPointerToFunctionPointer(t)) 4716 convertToUnqualifiedObjCType(t); 4717 ArgTypes.push_back(t); 4718 } 4719 } 4720 // Now do the pointer to function cast. 4721 QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes); 4722 4723 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType); 4724 4725 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock, 4726 CK_BitCast, 4727 const_cast<Expr*>(BlockExp)); 4728 // Don't forget the parens to enforce the proper binding. 4729 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), 4730 BlkCast); 4731 //PE->dump(); 4732 4733 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), 4734 SourceLocation(), 4735 &Context->Idents.get("FuncPtr"), 4736 Context->VoidPtrTy, nullptr, 4737 /*BitWidth=*/nullptr, /*Mutable=*/true, 4738 ICIS_NoInit); 4739 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(), 4740 FD->getType(), VK_LValue, 4741 OK_Ordinary); 4742 4743 4744 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType, 4745 CK_BitCast, ME); 4746 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast); 4747 4748 SmallVector<Expr*, 8> BlkExprs; 4749 // Add the implicit argument. 4750 BlkExprs.push_back(BlkCast); 4751 // Add the user arguments. 4752 for (CallExpr::arg_iterator I = Exp->arg_begin(), 4753 E = Exp->arg_end(); I != E; ++I) { 4754 BlkExprs.push_back(*I); 4755 } 4756 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs, 4757 Exp->getType(), VK_RValue, 4758 SourceLocation()); 4759 return CE; 4760 } 4761 4762 // We need to return the rewritten expression to handle cases where the 4763 // DeclRefExpr is embedded in another expression being rewritten. 4764 // For example: 4765 // 4766 // int main() { 4767 // __block Foo *f; 4768 // __block int i; 4769 // 4770 // void (^myblock)() = ^() { 4771 // [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten). 4772 // i = 77; 4773 // }; 4774 //} 4775 Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) { 4776 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR 4777 // for each DeclRefExp where BYREFVAR is name of the variable. 4778 ValueDecl *VD = DeclRefExp->getDecl(); 4779 bool isArrow = DeclRefExp->refersToEnclosingLocal(); 4780 4781 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), 4782 SourceLocation(), 4783 &Context->Idents.get("__forwarding"), 4784 Context->VoidPtrTy, nullptr, 4785 /*BitWidth=*/nullptr, /*Mutable=*/true, 4786 ICIS_NoInit); 4787 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow, 4788 FD, SourceLocation(), 4789 FD->getType(), VK_LValue, 4790 OK_Ordinary); 4791 4792 StringRef Name = VD->getName(); 4793 FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(), 4794 &Context->Idents.get(Name), 4795 Context->VoidPtrTy, nullptr, 4796 /*BitWidth=*/nullptr, /*Mutable=*/true, 4797 ICIS_NoInit); 4798 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(), 4799 DeclRefExp->getType(), VK_LValue, OK_Ordinary); 4800 4801 4802 4803 // Need parens to enforce precedence. 4804 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(), 4805 DeclRefExp->getExprLoc(), 4806 ME); 4807 ReplaceStmt(DeclRefExp, PE); 4808 return PE; 4809 } 4810 4811 // Rewrites the imported local variable V with external storage 4812 // (static, extern, etc.) as *V 4813 // 4814 Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) { 4815 ValueDecl *VD = DRE->getDecl(); 4816 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) 4817 if (!ImportedLocalExternalDecls.count(Var)) 4818 return DRE; 4819 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(), 4820 VK_LValue, OK_Ordinary, 4821 DRE->getLocation()); 4822 // Need parens to enforce precedence. 4823 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), 4824 Exp); 4825 ReplaceStmt(DRE, PE); 4826 return PE; 4827 } 4828 4829 void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) { 4830 SourceLocation LocStart = CE->getLParenLoc(); 4831 SourceLocation LocEnd = CE->getRParenLoc(); 4832 4833 // Need to avoid trying to rewrite synthesized casts. 4834 if (LocStart.isInvalid()) 4835 return; 4836 // Need to avoid trying to rewrite casts contained in macros. 4837 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd)) 4838 return; 4839 4840 const char *startBuf = SM->getCharacterData(LocStart); 4841 const char *endBuf = SM->getCharacterData(LocEnd); 4842 QualType QT = CE->getType(); 4843 const Type* TypePtr = QT->getAs<Type>(); 4844 if (isa<TypeOfExprType>(TypePtr)) { 4845 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr); 4846 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType(); 4847 std::string TypeAsString = "("; 4848 RewriteBlockPointerType(TypeAsString, QT); 4849 TypeAsString += ")"; 4850 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString); 4851 return; 4852 } 4853 // advance the location to startArgList. 4854 const char *argPtr = startBuf; 4855 4856 while (*argPtr++ && (argPtr < endBuf)) { 4857 switch (*argPtr) { 4858 case '^': 4859 // Replace the '^' with '*'. 4860 LocStart = LocStart.getLocWithOffset(argPtr-startBuf); 4861 ReplaceText(LocStart, 1, "*"); 4862 break; 4863 } 4864 } 4865 return; 4866 } 4867 4868 void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) { 4869 CastKind CastKind = IC->getCastKind(); 4870 if (CastKind != CK_BlockPointerToObjCPointerCast && 4871 CastKind != CK_AnyPointerToBlockPointerCast) 4872 return; 4873 4874 QualType QT = IC->getType(); 4875 (void)convertBlockPointerToFunctionPointer(QT); 4876 std::string TypeString(QT.getAsString(Context->getPrintingPolicy())); 4877 std::string Str = "("; 4878 Str += TypeString; 4879 Str += ")"; 4880 InsertText(IC->getSubExpr()->getLocStart(), &Str[0], Str.size()); 4881 4882 return; 4883 } 4884 4885 void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) { 4886 SourceLocation DeclLoc = FD->getLocation(); 4887 unsigned parenCount = 0; 4888 4889 // We have 1 or more arguments that have closure pointers. 4890 const char *startBuf = SM->getCharacterData(DeclLoc); 4891 const char *startArgList = strchr(startBuf, '('); 4892 4893 assert((*startArgList == '(') && "Rewriter fuzzy parser confused"); 4894 4895 parenCount++; 4896 // advance the location to startArgList. 4897 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf); 4898 assert((DeclLoc.isValid()) && "Invalid DeclLoc"); 4899 4900 const char *argPtr = startArgList; 4901 4902 while (*argPtr++ && parenCount) { 4903 switch (*argPtr) { 4904 case '^': 4905 // Replace the '^' with '*'. 4906 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList); 4907 ReplaceText(DeclLoc, 1, "*"); 4908 break; 4909 case '(': 4910 parenCount++; 4911 break; 4912 case ')': 4913 parenCount--; 4914 break; 4915 } 4916 } 4917 return; 4918 } 4919 4920 bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) { 4921 const FunctionProtoType *FTP; 4922 const PointerType *PT = QT->getAs<PointerType>(); 4923 if (PT) { 4924 FTP = PT->getPointeeType()->getAs<FunctionProtoType>(); 4925 } else { 4926 const BlockPointerType *BPT = QT->getAs<BlockPointerType>(); 4927 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type"); 4928 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>(); 4929 } 4930 if (FTP) { 4931 for (const auto &I : FTP->param_types()) 4932 if (isTopLevelBlockPointerType(I)) 4933 return true; 4934 } 4935 return false; 4936 } 4937 4938 bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) { 4939 const FunctionProtoType *FTP; 4940 const PointerType *PT = QT->getAs<PointerType>(); 4941 if (PT) { 4942 FTP = PT->getPointeeType()->getAs<FunctionProtoType>(); 4943 } else { 4944 const BlockPointerType *BPT = QT->getAs<BlockPointerType>(); 4945 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type"); 4946 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>(); 4947 } 4948 if (FTP) { 4949 for (const auto &I : FTP->param_types()) { 4950 if (I->isObjCQualifiedIdType()) 4951 return true; 4952 if (I->isObjCObjectPointerType() && 4953 I->getPointeeType()->isObjCQualifiedInterfaceType()) 4954 return true; 4955 } 4956 4957 } 4958 return false; 4959 } 4960 4961 void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen, 4962 const char *&RParen) { 4963 const char *argPtr = strchr(Name, '('); 4964 assert((*argPtr == '(') && "Rewriter fuzzy parser confused"); 4965 4966 LParen = argPtr; // output the start. 4967 argPtr++; // skip past the left paren. 4968 unsigned parenCount = 1; 4969 4970 while (*argPtr && parenCount) { 4971 switch (*argPtr) { 4972 case '(': parenCount++; break; 4973 case ')': parenCount--; break; 4974 default: break; 4975 } 4976 if (parenCount) argPtr++; 4977 } 4978 assert((*argPtr == ')') && "Rewriter fuzzy parser confused"); 4979 RParen = argPtr; // output the end 4980 } 4981 4982 void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) { 4983 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 4984 RewriteBlockPointerFunctionArgs(FD); 4985 return; 4986 } 4987 // Handle Variables and Typedefs. 4988 SourceLocation DeclLoc = ND->getLocation(); 4989 QualType DeclT; 4990 if (VarDecl *VD = dyn_cast<VarDecl>(ND)) 4991 DeclT = VD->getType(); 4992 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND)) 4993 DeclT = TDD->getUnderlyingType(); 4994 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND)) 4995 DeclT = FD->getType(); 4996 else 4997 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled"); 4998 4999 const char *startBuf = SM->getCharacterData(DeclLoc); 5000 const char *endBuf = startBuf; 5001 // scan backward (from the decl location) for the end of the previous decl. 5002 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart) 5003 startBuf--; 5004 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf); 5005 std::string buf; 5006 unsigned OrigLength=0; 5007 // *startBuf != '^' if we are dealing with a pointer to function that 5008 // may take block argument types (which will be handled below). 5009 if (*startBuf == '^') { 5010 // Replace the '^' with '*', computing a negative offset. 5011 buf = '*'; 5012 startBuf++; 5013 OrigLength++; 5014 } 5015 while (*startBuf != ')') { 5016 buf += *startBuf; 5017 startBuf++; 5018 OrigLength++; 5019 } 5020 buf += ')'; 5021 OrigLength++; 5022 5023 if (PointerTypeTakesAnyBlockArguments(DeclT) || 5024 PointerTypeTakesAnyObjCQualifiedType(DeclT)) { 5025 // Replace the '^' with '*' for arguments. 5026 // Replace id<P> with id/*<>*/ 5027 DeclLoc = ND->getLocation(); 5028 startBuf = SM->getCharacterData(DeclLoc); 5029 const char *argListBegin, *argListEnd; 5030 GetExtentOfArgList(startBuf, argListBegin, argListEnd); 5031 while (argListBegin < argListEnd) { 5032 if (*argListBegin == '^') 5033 buf += '*'; 5034 else if (*argListBegin == '<') { 5035 buf += "/*"; 5036 buf += *argListBegin++; 5037 OrigLength++; 5038 while (*argListBegin != '>') { 5039 buf += *argListBegin++; 5040 OrigLength++; 5041 } 5042 buf += *argListBegin; 5043 buf += "*/"; 5044 } 5045 else 5046 buf += *argListBegin; 5047 argListBegin++; 5048 OrigLength++; 5049 } 5050 buf += ')'; 5051 OrigLength++; 5052 } 5053 ReplaceText(Start, OrigLength, buf); 5054 5055 return; 5056 } 5057 5058 5059 /// SynthesizeByrefCopyDestroyHelper - This routine synthesizes: 5060 /// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst, 5061 /// struct Block_byref_id_object *src) { 5062 /// _Block_object_assign (&_dest->object, _src->object, 5063 /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT 5064 /// [|BLOCK_FIELD_IS_WEAK]) // object 5065 /// _Block_object_assign(&_dest->object, _src->object, 5066 /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK 5067 /// [|BLOCK_FIELD_IS_WEAK]) // block 5068 /// } 5069 /// And: 5070 /// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) { 5071 /// _Block_object_dispose(_src->object, 5072 /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT 5073 /// [|BLOCK_FIELD_IS_WEAK]) // object 5074 /// _Block_object_dispose(_src->object, 5075 /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK 5076 /// [|BLOCK_FIELD_IS_WEAK]) // block 5077 /// } 5078 5079 std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD, 5080 int flag) { 5081 std::string S; 5082 if (CopyDestroyCache.count(flag)) 5083 return S; 5084 CopyDestroyCache.insert(flag); 5085 S = "static void __Block_byref_id_object_copy_"; 5086 S += utostr(flag); 5087 S += "(void *dst, void *src) {\n"; 5088 5089 // offset into the object pointer is computed as: 5090 // void * + void* + int + int + void* + void * 5091 unsigned IntSize = 5092 static_cast<unsigned>(Context->getTypeSize(Context->IntTy)); 5093 unsigned VoidPtrSize = 5094 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy)); 5095 5096 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth(); 5097 S += " _Block_object_assign((char*)dst + "; 5098 S += utostr(offset); 5099 S += ", *(void * *) ((char*)src + "; 5100 S += utostr(offset); 5101 S += "), "; 5102 S += utostr(flag); 5103 S += ");\n}\n"; 5104 5105 S += "static void __Block_byref_id_object_dispose_"; 5106 S += utostr(flag); 5107 S += "(void *src) {\n"; 5108 S += " _Block_object_dispose(*(void * *) ((char*)src + "; 5109 S += utostr(offset); 5110 S += "), "; 5111 S += utostr(flag); 5112 S += ");\n}\n"; 5113 return S; 5114 } 5115 5116 /// RewriteByRefVar - For each __block typex ND variable this routine transforms 5117 /// the declaration into: 5118 /// struct __Block_byref_ND { 5119 /// void *__isa; // NULL for everything except __weak pointers 5120 /// struct __Block_byref_ND *__forwarding; 5121 /// int32_t __flags; 5122 /// int32_t __size; 5123 /// void *__Block_byref_id_object_copy; // If variable is __block ObjC object 5124 /// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object 5125 /// typex ND; 5126 /// }; 5127 /// 5128 /// It then replaces declaration of ND variable with: 5129 /// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag, 5130 /// __size=sizeof(struct __Block_byref_ND), 5131 /// ND=initializer-if-any}; 5132 /// 5133 /// 5134 void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl, 5135 bool lastDecl) { 5136 int flag = 0; 5137 int isa = 0; 5138 SourceLocation DeclLoc = ND->getTypeSpecStartLoc(); 5139 if (DeclLoc.isInvalid()) 5140 // If type location is missing, it is because of missing type (a warning). 5141 // Use variable's location which is good for this case. 5142 DeclLoc = ND->getLocation(); 5143 const char *startBuf = SM->getCharacterData(DeclLoc); 5144 SourceLocation X = ND->getLocEnd(); 5145 X = SM->getExpansionLoc(X); 5146 const char *endBuf = SM->getCharacterData(X); 5147 std::string Name(ND->getNameAsString()); 5148 std::string ByrefType; 5149 RewriteByRefString(ByrefType, Name, ND, true); 5150 ByrefType += " {\n"; 5151 ByrefType += " void *__isa;\n"; 5152 RewriteByRefString(ByrefType, Name, ND); 5153 ByrefType += " *__forwarding;\n"; 5154 ByrefType += " int __flags;\n"; 5155 ByrefType += " int __size;\n"; 5156 // Add void *__Block_byref_id_object_copy; 5157 // void *__Block_byref_id_object_dispose; if needed. 5158 QualType Ty = ND->getType(); 5159 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND); 5160 if (HasCopyAndDispose) { 5161 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n"; 5162 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n"; 5163 } 5164 5165 QualType T = Ty; 5166 (void)convertBlockPointerToFunctionPointer(T); 5167 T.getAsStringInternal(Name, Context->getPrintingPolicy()); 5168 5169 ByrefType += " " + Name + ";\n"; 5170 ByrefType += "};\n"; 5171 // Insert this type in global scope. It is needed by helper function. 5172 SourceLocation FunLocStart; 5173 if (CurFunctionDef) 5174 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef); 5175 else { 5176 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null"); 5177 FunLocStart = CurMethodDef->getLocStart(); 5178 } 5179 InsertText(FunLocStart, ByrefType); 5180 5181 if (Ty.isObjCGCWeak()) { 5182 flag |= BLOCK_FIELD_IS_WEAK; 5183 isa = 1; 5184 } 5185 if (HasCopyAndDispose) { 5186 flag = BLOCK_BYREF_CALLER; 5187 QualType Ty = ND->getType(); 5188 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well. 5189 if (Ty->isBlockPointerType()) 5190 flag |= BLOCK_FIELD_IS_BLOCK; 5191 else 5192 flag |= BLOCK_FIELD_IS_OBJECT; 5193 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag); 5194 if (!HF.empty()) 5195 Preamble += HF; 5196 } 5197 5198 // struct __Block_byref_ND ND = 5199 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND), 5200 // initializer-if-any}; 5201 bool hasInit = (ND->getInit() != nullptr); 5202 // FIXME. rewriter does not support __block c++ objects which 5203 // require construction. 5204 if (hasInit) 5205 if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) { 5206 CXXConstructorDecl *CXXDecl = CExp->getConstructor(); 5207 if (CXXDecl && CXXDecl->isDefaultConstructor()) 5208 hasInit = false; 5209 } 5210 5211 unsigned flags = 0; 5212 if (HasCopyAndDispose) 5213 flags |= BLOCK_HAS_COPY_DISPOSE; 5214 Name = ND->getNameAsString(); 5215 ByrefType.clear(); 5216 RewriteByRefString(ByrefType, Name, ND); 5217 std::string ForwardingCastType("("); 5218 ForwardingCastType += ByrefType + " *)"; 5219 ByrefType += " " + Name + " = {(void*)"; 5220 ByrefType += utostr(isa); 5221 ByrefType += "," + ForwardingCastType + "&" + Name + ", "; 5222 ByrefType += utostr(flags); 5223 ByrefType += ", "; 5224 ByrefType += "sizeof("; 5225 RewriteByRefString(ByrefType, Name, ND); 5226 ByrefType += ")"; 5227 if (HasCopyAndDispose) { 5228 ByrefType += ", __Block_byref_id_object_copy_"; 5229 ByrefType += utostr(flag); 5230 ByrefType += ", __Block_byref_id_object_dispose_"; 5231 ByrefType += utostr(flag); 5232 } 5233 5234 if (!firstDecl) { 5235 // In multiple __block declarations, and for all but 1st declaration, 5236 // find location of the separating comma. This would be start location 5237 // where new text is to be inserted. 5238 DeclLoc = ND->getLocation(); 5239 const char *startDeclBuf = SM->getCharacterData(DeclLoc); 5240 const char *commaBuf = startDeclBuf; 5241 while (*commaBuf != ',') 5242 commaBuf--; 5243 assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','"); 5244 DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf); 5245 startBuf = commaBuf; 5246 } 5247 5248 if (!hasInit) { 5249 ByrefType += "};\n"; 5250 unsigned nameSize = Name.size(); 5251 // for block or function pointer declaration. Name is aleady 5252 // part of the declaration. 5253 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) 5254 nameSize = 1; 5255 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType); 5256 } 5257 else { 5258 ByrefType += ", "; 5259 SourceLocation startLoc; 5260 Expr *E = ND->getInit(); 5261 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) 5262 startLoc = ECE->getLParenLoc(); 5263 else 5264 startLoc = E->getLocStart(); 5265 startLoc = SM->getExpansionLoc(startLoc); 5266 endBuf = SM->getCharacterData(startLoc); 5267 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType); 5268 5269 const char separator = lastDecl ? ';' : ','; 5270 const char *startInitializerBuf = SM->getCharacterData(startLoc); 5271 const char *separatorBuf = strchr(startInitializerBuf, separator); 5272 assert((*separatorBuf == separator) && 5273 "RewriteByRefVar: can't find ';' or ','"); 5274 SourceLocation separatorLoc = 5275 startLoc.getLocWithOffset(separatorBuf-startInitializerBuf); 5276 5277 InsertText(separatorLoc, lastDecl ? "}" : "};\n"); 5278 } 5279 return; 5280 } 5281 5282 void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) { 5283 // Add initializers for any closure decl refs. 5284 GetBlockDeclRefExprs(Exp->getBody()); 5285 if (BlockDeclRefs.size()) { 5286 // Unique all "by copy" declarations. 5287 for (unsigned i = 0; i < BlockDeclRefs.size(); i++) 5288 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) { 5289 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) { 5290 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl()); 5291 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl()); 5292 } 5293 } 5294 // Unique all "by ref" declarations. 5295 for (unsigned i = 0; i < BlockDeclRefs.size(); i++) 5296 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) { 5297 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) { 5298 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl()); 5299 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl()); 5300 } 5301 } 5302 // Find any imported blocks...they will need special attention. 5303 for (unsigned i = 0; i < BlockDeclRefs.size(); i++) 5304 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() || 5305 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() || 5306 BlockDeclRefs[i]->getType()->isBlockPointerType()) 5307 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl()); 5308 } 5309 } 5310 5311 FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) { 5312 IdentifierInfo *ID = &Context->Idents.get(name); 5313 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy); 5314 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(), 5315 SourceLocation(), ID, FType, nullptr, SC_Extern, 5316 false, false); 5317 } 5318 5319 Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp, 5320 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) { 5321 5322 const BlockDecl *block = Exp->getBlockDecl(); 5323 5324 Blocks.push_back(Exp); 5325 5326 CollectBlockDeclRefInfo(Exp); 5327 5328 // Add inner imported variables now used in current block. 5329 int countOfInnerDecls = 0; 5330 if (!InnerBlockDeclRefs.empty()) { 5331 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) { 5332 DeclRefExpr *Exp = InnerBlockDeclRefs[i]; 5333 ValueDecl *VD = Exp->getDecl(); 5334 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) { 5335 // We need to save the copied-in variables in nested 5336 // blocks because it is needed at the end for some of the API generations. 5337 // See SynthesizeBlockLiterals routine. 5338 InnerDeclRefs.push_back(Exp); countOfInnerDecls++; 5339 BlockDeclRefs.push_back(Exp); 5340 BlockByCopyDeclsPtrSet.insert(VD); 5341 BlockByCopyDecls.push_back(VD); 5342 } 5343 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) { 5344 InnerDeclRefs.push_back(Exp); countOfInnerDecls++; 5345 BlockDeclRefs.push_back(Exp); 5346 BlockByRefDeclsPtrSet.insert(VD); 5347 BlockByRefDecls.push_back(VD); 5348 } 5349 } 5350 // Find any imported blocks...they will need special attention. 5351 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) 5352 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() || 5353 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() || 5354 InnerBlockDeclRefs[i]->getType()->isBlockPointerType()) 5355 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl()); 5356 } 5357 InnerDeclRefsCount.push_back(countOfInnerDecls); 5358 5359 std::string FuncName; 5360 5361 if (CurFunctionDef) 5362 FuncName = CurFunctionDef->getNameAsString(); 5363 else if (CurMethodDef) 5364 BuildUniqueMethodName(FuncName, CurMethodDef); 5365 else if (GlobalVarDecl) 5366 FuncName = std::string(GlobalVarDecl->getNameAsString()); 5367 5368 bool GlobalBlockExpr = 5369 block->getDeclContext()->getRedeclContext()->isFileContext(); 5370 5371 if (GlobalBlockExpr && !GlobalVarDecl) { 5372 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag); 5373 GlobalBlockExpr = false; 5374 } 5375 5376 std::string BlockNumber = utostr(Blocks.size()-1); 5377 5378 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber; 5379 5380 // Get a pointer to the function type so we can cast appropriately. 5381 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType()); 5382 QualType FType = Context->getPointerType(BFT); 5383 5384 FunctionDecl *FD; 5385 Expr *NewRep; 5386 5387 // Simulate a constructor call... 5388 std::string Tag; 5389 5390 if (GlobalBlockExpr) 5391 Tag = "__global_"; 5392 else 5393 Tag = "__"; 5394 Tag += FuncName + "_block_impl_" + BlockNumber; 5395 5396 FD = SynthBlockInitFunctionDecl(Tag); 5397 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue, 5398 SourceLocation()); 5399 5400 SmallVector<Expr*, 4> InitExprs; 5401 5402 // Initialize the block function. 5403 FD = SynthBlockInitFunctionDecl(Func); 5404 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(), 5405 VK_LValue, SourceLocation()); 5406 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy, 5407 CK_BitCast, Arg); 5408 InitExprs.push_back(castExpr); 5409 5410 // Initialize the block descriptor. 5411 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA"; 5412 5413 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, 5414 SourceLocation(), SourceLocation(), 5415 &Context->Idents.get(DescData.c_str()), 5416 Context->VoidPtrTy, nullptr, 5417 SC_Static); 5418 UnaryOperator *DescRefExpr = 5419 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false, 5420 Context->VoidPtrTy, 5421 VK_LValue, 5422 SourceLocation()), 5423 UO_AddrOf, 5424 Context->getPointerType(Context->VoidPtrTy), 5425 VK_RValue, OK_Ordinary, 5426 SourceLocation()); 5427 InitExprs.push_back(DescRefExpr); 5428 5429 // Add initializers for any closure decl refs. 5430 if (BlockDeclRefs.size()) { 5431 Expr *Exp; 5432 // Output all "by copy" declarations. 5433 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(), 5434 E = BlockByCopyDecls.end(); I != E; ++I) { 5435 if (isObjCType((*I)->getType())) { 5436 // FIXME: Conform to ABI ([[obj retain] autorelease]). 5437 FD = SynthBlockInitFunctionDecl((*I)->getName()); 5438 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), 5439 VK_LValue, SourceLocation()); 5440 if (HasLocalVariableExternalStorage(*I)) { 5441 QualType QT = (*I)->getType(); 5442 QT = Context->getPointerType(QT); 5443 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue, 5444 OK_Ordinary, SourceLocation()); 5445 } 5446 } else if (isTopLevelBlockPointerType((*I)->getType())) { 5447 FD = SynthBlockInitFunctionDecl((*I)->getName()); 5448 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(), 5449 VK_LValue, SourceLocation()); 5450 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy, 5451 CK_BitCast, Arg); 5452 } else { 5453 FD = SynthBlockInitFunctionDecl((*I)->getName()); 5454 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), 5455 VK_LValue, SourceLocation()); 5456 if (HasLocalVariableExternalStorage(*I)) { 5457 QualType QT = (*I)->getType(); 5458 QT = Context->getPointerType(QT); 5459 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue, 5460 OK_Ordinary, SourceLocation()); 5461 } 5462 5463 } 5464 InitExprs.push_back(Exp); 5465 } 5466 // Output all "by ref" declarations. 5467 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(), 5468 E = BlockByRefDecls.end(); I != E; ++I) { 5469 ValueDecl *ND = (*I); 5470 std::string Name(ND->getNameAsString()); 5471 std::string RecName; 5472 RewriteByRefString(RecName, Name, ND, true); 5473 IdentifierInfo *II = &Context->Idents.get(RecName.c_str() 5474 + sizeof("struct")); 5475 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl, 5476 SourceLocation(), SourceLocation(), 5477 II); 5478 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl"); 5479 QualType castT = Context->getPointerType(Context->getTagDeclType(RD)); 5480 5481 FD = SynthBlockInitFunctionDecl((*I)->getName()); 5482 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue, 5483 SourceLocation()); 5484 bool isNestedCapturedVar = false; 5485 if (block) 5486 for (const auto &CI : block->captures()) { 5487 const VarDecl *variable = CI.getVariable(); 5488 if (variable == ND && CI.isNested()) { 5489 assert (CI.isByRef() && 5490 "SynthBlockInitExpr - captured block variable is not byref"); 5491 isNestedCapturedVar = true; 5492 break; 5493 } 5494 } 5495 // captured nested byref variable has its address passed. Do not take 5496 // its address again. 5497 if (!isNestedCapturedVar) 5498 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, 5499 Context->getPointerType(Exp->getType()), 5500 VK_RValue, OK_Ordinary, SourceLocation()); 5501 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp); 5502 InitExprs.push_back(Exp); 5503 } 5504 } 5505 if (ImportedBlockDecls.size()) { 5506 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR 5507 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR); 5508 unsigned IntSize = 5509 static_cast<unsigned>(Context->getTypeSize(Context->IntTy)); 5510 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag), 5511 Context->IntTy, SourceLocation()); 5512 InitExprs.push_back(FlagExp); 5513 } 5514 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs, 5515 FType, VK_LValue, SourceLocation()); 5516 5517 if (GlobalBlockExpr) { 5518 assert (!GlobalConstructionExp && 5519 "SynthBlockInitExpr - GlobalConstructionExp must be null"); 5520 GlobalConstructionExp = NewRep; 5521 NewRep = DRE; 5522 } 5523 5524 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf, 5525 Context->getPointerType(NewRep->getType()), 5526 VK_RValue, OK_Ordinary, SourceLocation()); 5527 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast, 5528 NewRep); 5529 BlockDeclRefs.clear(); 5530 BlockByRefDecls.clear(); 5531 BlockByRefDeclsPtrSet.clear(); 5532 BlockByCopyDecls.clear(); 5533 BlockByCopyDeclsPtrSet.clear(); 5534 ImportedBlockDecls.clear(); 5535 return NewRep; 5536 } 5537 5538 bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) { 5539 if (const ObjCForCollectionStmt * CS = 5540 dyn_cast<ObjCForCollectionStmt>(Stmts.back())) 5541 return CS->getElement() == DS; 5542 return false; 5543 } 5544 5545 //===----------------------------------------------------------------------===// 5546 // Function Body / Expression rewriting 5547 //===----------------------------------------------------------------------===// 5548 5549 Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) { 5550 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || 5551 isa<DoStmt>(S) || isa<ForStmt>(S)) 5552 Stmts.push_back(S); 5553 else if (isa<ObjCForCollectionStmt>(S)) { 5554 Stmts.push_back(S); 5555 ObjCBcLabelNo.push_back(++BcLabelCount); 5556 } 5557 5558 // Pseudo-object operations and ivar references need special 5559 // treatment because we're going to recursively rewrite them. 5560 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) { 5561 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) { 5562 return RewritePropertyOrImplicitSetter(PseudoOp); 5563 } else { 5564 return RewritePropertyOrImplicitGetter(PseudoOp); 5565 } 5566 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) { 5567 return RewriteObjCIvarRefExpr(IvarRefExpr); 5568 } 5569 else if (isa<OpaqueValueExpr>(S)) 5570 S = cast<OpaqueValueExpr>(S)->getSourceExpr(); 5571 5572 SourceRange OrigStmtRange = S->getSourceRange(); 5573 5574 // Perform a bottom up rewrite of all children. 5575 for (Stmt::child_range CI = S->children(); CI; ++CI) 5576 if (*CI) { 5577 Stmt *childStmt = (*CI); 5578 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt); 5579 if (newStmt) { 5580 *CI = newStmt; 5581 } 5582 } 5583 5584 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) { 5585 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs; 5586 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts; 5587 InnerContexts.insert(BE->getBlockDecl()); 5588 ImportedLocalExternalDecls.clear(); 5589 GetInnerBlockDeclRefExprs(BE->getBody(), 5590 InnerBlockDeclRefs, InnerContexts); 5591 // Rewrite the block body in place. 5592 Stmt *SaveCurrentBody = CurrentBody; 5593 CurrentBody = BE->getBody(); 5594 PropParentMap = nullptr; 5595 // block literal on rhs of a property-dot-sytax assignment 5596 // must be replaced by its synthesize ast so getRewrittenText 5597 // works as expected. In this case, what actually ends up on RHS 5598 // is the blockTranscribed which is the helper function for the 5599 // block literal; as in: self.c = ^() {[ace ARR];}; 5600 bool saveDisableReplaceStmt = DisableReplaceStmt; 5601 DisableReplaceStmt = false; 5602 RewriteFunctionBodyOrGlobalInitializer(BE->getBody()); 5603 DisableReplaceStmt = saveDisableReplaceStmt; 5604 CurrentBody = SaveCurrentBody; 5605 PropParentMap = nullptr; 5606 ImportedLocalExternalDecls.clear(); 5607 // Now we snarf the rewritten text and stash it away for later use. 5608 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange()); 5609 RewrittenBlockExprs[BE] = Str; 5610 5611 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs); 5612 5613 //blockTranscribed->dump(); 5614 ReplaceStmt(S, blockTranscribed); 5615 return blockTranscribed; 5616 } 5617 // Handle specific things. 5618 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S)) 5619 return RewriteAtEncode(AtEncode); 5620 5621 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S)) 5622 return RewriteAtSelector(AtSelector); 5623 5624 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S)) 5625 return RewriteObjCStringLiteral(AtString); 5626 5627 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S)) 5628 return RewriteObjCBoolLiteralExpr(BoolLitExpr); 5629 5630 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S)) 5631 return RewriteObjCBoxedExpr(BoxedExpr); 5632 5633 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S)) 5634 return RewriteObjCArrayLiteralExpr(ArrayLitExpr); 5635 5636 if (ObjCDictionaryLiteral *DictionaryLitExpr = 5637 dyn_cast<ObjCDictionaryLiteral>(S)) 5638 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr); 5639 5640 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) { 5641 #if 0 5642 // Before we rewrite it, put the original message expression in a comment. 5643 SourceLocation startLoc = MessExpr->getLocStart(); 5644 SourceLocation endLoc = MessExpr->getLocEnd(); 5645 5646 const char *startBuf = SM->getCharacterData(startLoc); 5647 const char *endBuf = SM->getCharacterData(endLoc); 5648 5649 std::string messString; 5650 messString += "// "; 5651 messString.append(startBuf, endBuf-startBuf+1); 5652 messString += "\n"; 5653 5654 // FIXME: Missing definition of 5655 // InsertText(clang::SourceLocation, char const*, unsigned int). 5656 // InsertText(startLoc, messString.c_str(), messString.size()); 5657 // Tried this, but it didn't work either... 5658 // ReplaceText(startLoc, 0, messString.c_str(), messString.size()); 5659 #endif 5660 return RewriteMessageExpr(MessExpr); 5661 } 5662 5663 if (ObjCAutoreleasePoolStmt *StmtAutoRelease = 5664 dyn_cast<ObjCAutoreleasePoolStmt>(S)) { 5665 return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease); 5666 } 5667 5668 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S)) 5669 return RewriteObjCTryStmt(StmtTry); 5670 5671 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S)) 5672 return RewriteObjCSynchronizedStmt(StmtTry); 5673 5674 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S)) 5675 return RewriteObjCThrowStmt(StmtThrow); 5676 5677 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S)) 5678 return RewriteObjCProtocolExpr(ProtocolExp); 5679 5680 if (ObjCForCollectionStmt *StmtForCollection = 5681 dyn_cast<ObjCForCollectionStmt>(S)) 5682 return RewriteObjCForCollectionStmt(StmtForCollection, 5683 OrigStmtRange.getEnd()); 5684 if (BreakStmt *StmtBreakStmt = 5685 dyn_cast<BreakStmt>(S)) 5686 return RewriteBreakStmt(StmtBreakStmt); 5687 if (ContinueStmt *StmtContinueStmt = 5688 dyn_cast<ContinueStmt>(S)) 5689 return RewriteContinueStmt(StmtContinueStmt); 5690 5691 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls 5692 // and cast exprs. 5693 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) { 5694 // FIXME: What we're doing here is modifying the type-specifier that 5695 // precedes the first Decl. In the future the DeclGroup should have 5696 // a separate type-specifier that we can rewrite. 5697 // NOTE: We need to avoid rewriting the DeclStmt if it is within 5698 // the context of an ObjCForCollectionStmt. For example: 5699 // NSArray *someArray; 5700 // for (id <FooProtocol> index in someArray) ; 5701 // This is because RewriteObjCForCollectionStmt() does textual rewriting 5702 // and it depends on the original text locations/positions. 5703 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS)) 5704 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin()); 5705 5706 // Blocks rewrite rules. 5707 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end(); 5708 DI != DE; ++DI) { 5709 Decl *SD = *DI; 5710 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) { 5711 if (isTopLevelBlockPointerType(ND->getType())) 5712 RewriteBlockPointerDecl(ND); 5713 else if (ND->getType()->isFunctionPointerType()) 5714 CheckFunctionPointerDecl(ND->getType(), ND); 5715 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) { 5716 if (VD->hasAttr<BlocksAttr>()) { 5717 static unsigned uniqueByrefDeclCount = 0; 5718 assert(!BlockByRefDeclNo.count(ND) && 5719 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl"); 5720 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++; 5721 RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE)); 5722 } 5723 else 5724 RewriteTypeOfDecl(VD); 5725 } 5726 } 5727 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) { 5728 if (isTopLevelBlockPointerType(TD->getUnderlyingType())) 5729 RewriteBlockPointerDecl(TD); 5730 else if (TD->getUnderlyingType()->isFunctionPointerType()) 5731 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD); 5732 } 5733 } 5734 } 5735 5736 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) 5737 RewriteObjCQualifiedInterfaceTypes(CE); 5738 5739 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || 5740 isa<DoStmt>(S) || isa<ForStmt>(S)) { 5741 assert(!Stmts.empty() && "Statement stack is empty"); 5742 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) || 5743 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back())) 5744 && "Statement stack mismatch"); 5745 Stmts.pop_back(); 5746 } 5747 // Handle blocks rewriting. 5748 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) { 5749 ValueDecl *VD = DRE->getDecl(); 5750 if (VD->hasAttr<BlocksAttr>()) 5751 return RewriteBlockDeclRefExpr(DRE); 5752 if (HasLocalVariableExternalStorage(VD)) 5753 return RewriteLocalVariableExternalStorage(DRE); 5754 } 5755 5756 if (CallExpr *CE = dyn_cast<CallExpr>(S)) { 5757 if (CE->getCallee()->getType()->isBlockPointerType()) { 5758 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee()); 5759 ReplaceStmt(S, BlockCall); 5760 return BlockCall; 5761 } 5762 } 5763 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) { 5764 RewriteCastExpr(CE); 5765 } 5766 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) { 5767 RewriteImplicitCastObjCExpr(ICE); 5768 } 5769 #if 0 5770 5771 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) { 5772 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), 5773 ICE->getSubExpr(), 5774 SourceLocation()); 5775 // Get the new text. 5776 std::string SStr; 5777 llvm::raw_string_ostream Buf(SStr); 5778 Replacement->printPretty(Buf); 5779 const std::string &Str = Buf.str(); 5780 5781 printf("CAST = %s\n", &Str[0]); 5782 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size()); 5783 delete S; 5784 return Replacement; 5785 } 5786 #endif 5787 // Return this stmt unmodified. 5788 return S; 5789 } 5790 5791 void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) { 5792 for (auto *FD : RD->fields()) { 5793 if (isTopLevelBlockPointerType(FD->getType())) 5794 RewriteBlockPointerDecl(FD); 5795 if (FD->getType()->isObjCQualifiedIdType() || 5796 FD->getType()->isObjCQualifiedInterfaceType()) 5797 RewriteObjCQualifiedInterfaceTypes(FD); 5798 } 5799 } 5800 5801 /// HandleDeclInMainFile - This is called for each top-level decl defined in the 5802 /// main file of the input. 5803 void RewriteModernObjC::HandleDeclInMainFile(Decl *D) { 5804 switch (D->getKind()) { 5805 case Decl::Function: { 5806 FunctionDecl *FD = cast<FunctionDecl>(D); 5807 if (FD->isOverloadedOperator()) 5808 return; 5809 5810 // Since function prototypes don't have ParmDecl's, we check the function 5811 // prototype. This enables us to rewrite function declarations and 5812 // definitions using the same code. 5813 RewriteBlocksInFunctionProtoType(FD->getType(), FD); 5814 5815 if (!FD->isThisDeclarationADefinition()) 5816 break; 5817 5818 // FIXME: If this should support Obj-C++, support CXXTryStmt 5819 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) { 5820 CurFunctionDef = FD; 5821 CurrentBody = Body; 5822 Body = 5823 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body)); 5824 FD->setBody(Body); 5825 CurrentBody = nullptr; 5826 if (PropParentMap) { 5827 delete PropParentMap; 5828 PropParentMap = nullptr; 5829 } 5830 // This synthesizes and inserts the block "impl" struct, invoke function, 5831 // and any copy/dispose helper functions. 5832 InsertBlockLiteralsWithinFunction(FD); 5833 RewriteLineDirective(D); 5834 CurFunctionDef = nullptr; 5835 } 5836 break; 5837 } 5838 case Decl::ObjCMethod: { 5839 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D); 5840 if (CompoundStmt *Body = MD->getCompoundBody()) { 5841 CurMethodDef = MD; 5842 CurrentBody = Body; 5843 Body = 5844 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body)); 5845 MD->setBody(Body); 5846 CurrentBody = nullptr; 5847 if (PropParentMap) { 5848 delete PropParentMap; 5849 PropParentMap = nullptr; 5850 } 5851 InsertBlockLiteralsWithinMethod(MD); 5852 RewriteLineDirective(D); 5853 CurMethodDef = nullptr; 5854 } 5855 break; 5856 } 5857 case Decl::ObjCImplementation: { 5858 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D); 5859 ClassImplementation.push_back(CI); 5860 break; 5861 } 5862 case Decl::ObjCCategoryImpl: { 5863 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D); 5864 CategoryImplementation.push_back(CI); 5865 break; 5866 } 5867 case Decl::Var: { 5868 VarDecl *VD = cast<VarDecl>(D); 5869 RewriteObjCQualifiedInterfaceTypes(VD); 5870 if (isTopLevelBlockPointerType(VD->getType())) 5871 RewriteBlockPointerDecl(VD); 5872 else if (VD->getType()->isFunctionPointerType()) { 5873 CheckFunctionPointerDecl(VD->getType(), VD); 5874 if (VD->getInit()) { 5875 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) { 5876 RewriteCastExpr(CE); 5877 } 5878 } 5879 } else if (VD->getType()->isRecordType()) { 5880 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl(); 5881 if (RD->isCompleteDefinition()) 5882 RewriteRecordBody(RD); 5883 } 5884 if (VD->getInit()) { 5885 GlobalVarDecl = VD; 5886 CurrentBody = VD->getInit(); 5887 RewriteFunctionBodyOrGlobalInitializer(VD->getInit()); 5888 CurrentBody = nullptr; 5889 if (PropParentMap) { 5890 delete PropParentMap; 5891 PropParentMap = nullptr; 5892 } 5893 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName()); 5894 GlobalVarDecl = nullptr; 5895 5896 // This is needed for blocks. 5897 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) { 5898 RewriteCastExpr(CE); 5899 } 5900 } 5901 break; 5902 } 5903 case Decl::TypeAlias: 5904 case Decl::Typedef: { 5905 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) { 5906 if (isTopLevelBlockPointerType(TD->getUnderlyingType())) 5907 RewriteBlockPointerDecl(TD); 5908 else if (TD->getUnderlyingType()->isFunctionPointerType()) 5909 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD); 5910 else 5911 RewriteObjCQualifiedInterfaceTypes(TD); 5912 } 5913 break; 5914 } 5915 case Decl::CXXRecord: 5916 case Decl::Record: { 5917 RecordDecl *RD = cast<RecordDecl>(D); 5918 if (RD->isCompleteDefinition()) 5919 RewriteRecordBody(RD); 5920 break; 5921 } 5922 default: 5923 break; 5924 } 5925 // Nothing yet. 5926 } 5927 5928 /// Write_ProtocolExprReferencedMetadata - This routine writer out the 5929 /// protocol reference symbols in the for of: 5930 /// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA. 5931 static void Write_ProtocolExprReferencedMetadata(ASTContext *Context, 5932 ObjCProtocolDecl *PDecl, 5933 std::string &Result) { 5934 // Also output .objc_protorefs$B section and its meta-data. 5935 if (Context->getLangOpts().MicrosoftExt) 5936 Result += "static "; 5937 Result += "struct _protocol_t *"; 5938 Result += "_OBJC_PROTOCOL_REFERENCE_$_"; 5939 Result += PDecl->getNameAsString(); 5940 Result += " = &"; 5941 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString(); 5942 Result += ";\n"; 5943 } 5944 5945 void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) { 5946 if (Diags.hasErrorOccurred()) 5947 return; 5948 5949 RewriteInclude(); 5950 5951 for (unsigned i = 0, e = FunctionDefinitionsSeen.size(); i < e; i++) { 5952 // translation of function bodies were postponed until all class and 5953 // their extensions and implementations are seen. This is because, we 5954 // cannot build grouping structs for bitfields until they are all seen. 5955 FunctionDecl *FDecl = FunctionDefinitionsSeen[i]; 5956 HandleTopLevelSingleDecl(FDecl); 5957 } 5958 5959 // Here's a great place to add any extra declarations that may be needed. 5960 // Write out meta data for each @protocol(<expr>). 5961 for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls) { 5962 RewriteObjCProtocolMetaData(ProtDecl, Preamble); 5963 Write_ProtocolExprReferencedMetadata(Context, ProtDecl, Preamble); 5964 } 5965 5966 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false); 5967 5968 if (ClassImplementation.size() || CategoryImplementation.size()) 5969 RewriteImplementations(); 5970 5971 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) { 5972 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i]; 5973 // Write struct declaration for the class matching its ivar declarations. 5974 // Note that for modern abi, this is postponed until the end of TU 5975 // because class extensions and the implementation might declare their own 5976 // private ivars. 5977 RewriteInterfaceDecl(CDecl); 5978 } 5979 5980 // Get the buffer corresponding to MainFileID. If we haven't changed it, then 5981 // we are done. 5982 if (const RewriteBuffer *RewriteBuf = 5983 Rewrite.getRewriteBufferFor(MainFileID)) { 5984 //printf("Changed:\n"); 5985 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end()); 5986 } else { 5987 llvm::errs() << "No changes\n"; 5988 } 5989 5990 if (ClassImplementation.size() || CategoryImplementation.size() || 5991 ProtocolExprDecls.size()) { 5992 // Rewrite Objective-c meta data* 5993 std::string ResultStr; 5994 RewriteMetaDataIntoBuffer(ResultStr); 5995 // Emit metadata. 5996 *OutFile << ResultStr; 5997 } 5998 // Emit ImageInfo; 5999 { 6000 std::string ResultStr; 6001 WriteImageInfo(ResultStr); 6002 *OutFile << ResultStr; 6003 } 6004 OutFile->flush(); 6005 } 6006 6007 void RewriteModernObjC::Initialize(ASTContext &context) { 6008 InitializeCommon(context); 6009 6010 Preamble += "#ifndef __OBJC2__\n"; 6011 Preamble += "#define __OBJC2__\n"; 6012 Preamble += "#endif\n"; 6013 6014 // declaring objc_selector outside the parameter list removes a silly 6015 // scope related warning... 6016 if (IsHeader) 6017 Preamble = "#pragma once\n"; 6018 Preamble += "struct objc_selector; struct objc_class;\n"; 6019 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; "; 6020 Preamble += "\n\tstruct objc_object *superClass; "; 6021 // Add a constructor for creating temporary objects. 6022 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) "; 6023 Preamble += ": object(o), superClass(s) {} "; 6024 Preamble += "\n};\n"; 6025 6026 if (LangOpts.MicrosoftExt) { 6027 // Define all sections using syntax that makes sense. 6028 // These are currently generated. 6029 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n"; 6030 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n"; 6031 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n"; 6032 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n"; 6033 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n"; 6034 // These are generated but not necessary for functionality. 6035 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n"; 6036 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n"; 6037 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n"; 6038 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n"; 6039 6040 // These need be generated for performance. Currently they are not, 6041 // using API calls instead. 6042 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n"; 6043 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n"; 6044 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n"; 6045 6046 } 6047 Preamble += "#ifndef _REWRITER_typedef_Protocol\n"; 6048 Preamble += "typedef struct objc_object Protocol;\n"; 6049 Preamble += "#define _REWRITER_typedef_Protocol\n"; 6050 Preamble += "#endif\n"; 6051 if (LangOpts.MicrosoftExt) { 6052 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n"; 6053 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n"; 6054 } 6055 else 6056 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n"; 6057 6058 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n"; 6059 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n"; 6060 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n"; 6061 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n"; 6062 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n"; 6063 6064 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass"; 6065 Preamble += "(const char *);\n"; 6066 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass"; 6067 Preamble += "(struct objc_class *);\n"; 6068 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass"; 6069 Preamble += "(const char *);\n"; 6070 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n"; 6071 // @synchronized hooks. 6072 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n"; 6073 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n"; 6074 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n"; 6075 Preamble += "#ifdef _WIN64\n"; 6076 Preamble += "typedef unsigned long long _WIN_NSUInteger;\n"; 6077 Preamble += "#else\n"; 6078 Preamble += "typedef unsigned int _WIN_NSUInteger;\n"; 6079 Preamble += "#endif\n"; 6080 Preamble += "#ifndef __FASTENUMERATIONSTATE\n"; 6081 Preamble += "struct __objcFastEnumerationState {\n\t"; 6082 Preamble += "unsigned long state;\n\t"; 6083 Preamble += "void **itemsPtr;\n\t"; 6084 Preamble += "unsigned long *mutationsPtr;\n\t"; 6085 Preamble += "unsigned long extra[5];\n};\n"; 6086 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n"; 6087 Preamble += "#define __FASTENUMERATIONSTATE\n"; 6088 Preamble += "#endif\n"; 6089 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n"; 6090 Preamble += "struct __NSConstantStringImpl {\n"; 6091 Preamble += " int *isa;\n"; 6092 Preamble += " int flags;\n"; 6093 Preamble += " char *str;\n"; 6094 Preamble += "#if _WIN64\n"; 6095 Preamble += " long long length;\n"; 6096 Preamble += "#else\n"; 6097 Preamble += " long length;\n"; 6098 Preamble += "#endif\n"; 6099 Preamble += "};\n"; 6100 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n"; 6101 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n"; 6102 Preamble += "#else\n"; 6103 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n"; 6104 Preamble += "#endif\n"; 6105 Preamble += "#define __NSCONSTANTSTRINGIMPL\n"; 6106 Preamble += "#endif\n"; 6107 // Blocks preamble. 6108 Preamble += "#ifndef BLOCK_IMPL\n"; 6109 Preamble += "#define BLOCK_IMPL\n"; 6110 Preamble += "struct __block_impl {\n"; 6111 Preamble += " void *isa;\n"; 6112 Preamble += " int Flags;\n"; 6113 Preamble += " int Reserved;\n"; 6114 Preamble += " void *FuncPtr;\n"; 6115 Preamble += "};\n"; 6116 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n"; 6117 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n"; 6118 Preamble += "extern \"C\" __declspec(dllexport) " 6119 "void _Block_object_assign(void *, const void *, const int);\n"; 6120 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n"; 6121 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n"; 6122 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n"; 6123 Preamble += "#else\n"; 6124 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n"; 6125 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n"; 6126 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n"; 6127 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n"; 6128 Preamble += "#endif\n"; 6129 Preamble += "#endif\n"; 6130 if (LangOpts.MicrosoftExt) { 6131 Preamble += "#undef __OBJC_RW_DLLIMPORT\n"; 6132 Preamble += "#undef __OBJC_RW_STATICIMPORT\n"; 6133 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests. 6134 Preamble += "#define __attribute__(X)\n"; 6135 Preamble += "#endif\n"; 6136 Preamble += "#ifndef __weak\n"; 6137 Preamble += "#define __weak\n"; 6138 Preamble += "#endif\n"; 6139 Preamble += "#ifndef __block\n"; 6140 Preamble += "#define __block\n"; 6141 Preamble += "#endif\n"; 6142 } 6143 else { 6144 Preamble += "#define __block\n"; 6145 Preamble += "#define __weak\n"; 6146 } 6147 6148 // Declarations required for modern objective-c array and dictionary literals. 6149 Preamble += "\n#include <stdarg.h>\n"; 6150 Preamble += "struct __NSContainer_literal {\n"; 6151 Preamble += " void * *arr;\n"; 6152 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n"; 6153 Preamble += "\tva_list marker;\n"; 6154 Preamble += "\tva_start(marker, count);\n"; 6155 Preamble += "\tarr = new void *[count];\n"; 6156 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n"; 6157 Preamble += "\t arr[i] = va_arg(marker, void *);\n"; 6158 Preamble += "\tva_end( marker );\n"; 6159 Preamble += " };\n"; 6160 Preamble += " ~__NSContainer_literal() {\n"; 6161 Preamble += "\tdelete[] arr;\n"; 6162 Preamble += " }\n"; 6163 Preamble += "};\n"; 6164 6165 // Declaration required for implementation of @autoreleasepool statement. 6166 Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n"; 6167 Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n"; 6168 Preamble += "struct __AtAutoreleasePool {\n"; 6169 Preamble += " __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n"; 6170 Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n"; 6171 Preamble += " void * atautoreleasepoolobj;\n"; 6172 Preamble += "};\n"; 6173 6174 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long 6175 // as this avoids warning in any 64bit/32bit compilation model. 6176 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n"; 6177 } 6178 6179 /// RewriteIvarOffsetComputation - This rutine synthesizes computation of 6180 /// ivar offset. 6181 void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar, 6182 std::string &Result) { 6183 Result += "__OFFSETOFIVAR__(struct "; 6184 Result += ivar->getContainingInterface()->getNameAsString(); 6185 if (LangOpts.MicrosoftExt) 6186 Result += "_IMPL"; 6187 Result += ", "; 6188 if (ivar->isBitField()) 6189 ObjCIvarBitfieldGroupDecl(ivar, Result); 6190 else 6191 Result += ivar->getNameAsString(); 6192 Result += ")"; 6193 } 6194 6195 /// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI. 6196 /// struct _prop_t { 6197 /// const char *name; 6198 /// char *attributes; 6199 /// } 6200 6201 /// struct _prop_list_t { 6202 /// uint32_t entsize; // sizeof(struct _prop_t) 6203 /// uint32_t count_of_properties; 6204 /// struct _prop_t prop_list[count_of_properties]; 6205 /// } 6206 6207 /// struct _protocol_t; 6208 6209 /// struct _protocol_list_t { 6210 /// long protocol_count; // Note, this is 32/64 bit 6211 /// struct _protocol_t * protocol_list[protocol_count]; 6212 /// } 6213 6214 /// struct _objc_method { 6215 /// SEL _cmd; 6216 /// const char *method_type; 6217 /// char *_imp; 6218 /// } 6219 6220 /// struct _method_list_t { 6221 /// uint32_t entsize; // sizeof(struct _objc_method) 6222 /// uint32_t method_count; 6223 /// struct _objc_method method_list[method_count]; 6224 /// } 6225 6226 /// struct _protocol_t { 6227 /// id isa; // NULL 6228 /// const char *protocol_name; 6229 /// const struct _protocol_list_t * protocol_list; // super protocols 6230 /// const struct method_list_t *instance_methods; 6231 /// const struct method_list_t *class_methods; 6232 /// const struct method_list_t *optionalInstanceMethods; 6233 /// const struct method_list_t *optionalClassMethods; 6234 /// const struct _prop_list_t * properties; 6235 /// const uint32_t size; // sizeof(struct _protocol_t) 6236 /// const uint32_t flags; // = 0 6237 /// const char ** extendedMethodTypes; 6238 /// } 6239 6240 /// struct _ivar_t { 6241 /// unsigned long int *offset; // pointer to ivar offset location 6242 /// const char *name; 6243 /// const char *type; 6244 /// uint32_t alignment; 6245 /// uint32_t size; 6246 /// } 6247 6248 /// struct _ivar_list_t { 6249 /// uint32 entsize; // sizeof(struct _ivar_t) 6250 /// uint32 count; 6251 /// struct _ivar_t list[count]; 6252 /// } 6253 6254 /// struct _class_ro_t { 6255 /// uint32_t flags; 6256 /// uint32_t instanceStart; 6257 /// uint32_t instanceSize; 6258 /// uint32_t reserved; // only when building for 64bit targets 6259 /// const uint8_t *ivarLayout; 6260 /// const char *name; 6261 /// const struct _method_list_t *baseMethods; 6262 /// const struct _protocol_list_t *baseProtocols; 6263 /// const struct _ivar_list_t *ivars; 6264 /// const uint8_t *weakIvarLayout; 6265 /// const struct _prop_list_t *properties; 6266 /// } 6267 6268 /// struct _class_t { 6269 /// struct _class_t *isa; 6270 /// struct _class_t *superclass; 6271 /// void *cache; 6272 /// IMP *vtable; 6273 /// struct _class_ro_t *ro; 6274 /// } 6275 6276 /// struct _category_t { 6277 /// const char *name; 6278 /// struct _class_t *cls; 6279 /// const struct _method_list_t *instance_methods; 6280 /// const struct _method_list_t *class_methods; 6281 /// const struct _protocol_list_t *protocols; 6282 /// const struct _prop_list_t *properties; 6283 /// } 6284 6285 /// MessageRefTy - LLVM for: 6286 /// struct _message_ref_t { 6287 /// IMP messenger; 6288 /// SEL name; 6289 /// }; 6290 6291 /// SuperMessageRefTy - LLVM for: 6292 /// struct _super_message_ref_t { 6293 /// SUPER_IMP messenger; 6294 /// SEL name; 6295 /// }; 6296 6297 static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) { 6298 static bool meta_data_declared = false; 6299 if (meta_data_declared) 6300 return; 6301 6302 Result += "\nstruct _prop_t {\n"; 6303 Result += "\tconst char *name;\n"; 6304 Result += "\tconst char *attributes;\n"; 6305 Result += "};\n"; 6306 6307 Result += "\nstruct _protocol_t;\n"; 6308 6309 Result += "\nstruct _objc_method {\n"; 6310 Result += "\tstruct objc_selector * _cmd;\n"; 6311 Result += "\tconst char *method_type;\n"; 6312 Result += "\tvoid *_imp;\n"; 6313 Result += "};\n"; 6314 6315 Result += "\nstruct _protocol_t {\n"; 6316 Result += "\tvoid * isa; // NULL\n"; 6317 Result += "\tconst char *protocol_name;\n"; 6318 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n"; 6319 Result += "\tconst struct method_list_t *instance_methods;\n"; 6320 Result += "\tconst struct method_list_t *class_methods;\n"; 6321 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n"; 6322 Result += "\tconst struct method_list_t *optionalClassMethods;\n"; 6323 Result += "\tconst struct _prop_list_t * properties;\n"; 6324 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n"; 6325 Result += "\tconst unsigned int flags; // = 0\n"; 6326 Result += "\tconst char ** extendedMethodTypes;\n"; 6327 Result += "};\n"; 6328 6329 Result += "\nstruct _ivar_t {\n"; 6330 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n"; 6331 Result += "\tconst char *name;\n"; 6332 Result += "\tconst char *type;\n"; 6333 Result += "\tunsigned int alignment;\n"; 6334 Result += "\tunsigned int size;\n"; 6335 Result += "};\n"; 6336 6337 Result += "\nstruct _class_ro_t {\n"; 6338 Result += "\tunsigned int flags;\n"; 6339 Result += "\tunsigned int instanceStart;\n"; 6340 Result += "\tunsigned int instanceSize;\n"; 6341 const llvm::Triple &Triple(Context->getTargetInfo().getTriple()); 6342 if (Triple.getArch() == llvm::Triple::x86_64) 6343 Result += "\tunsigned int reserved;\n"; 6344 Result += "\tconst unsigned char *ivarLayout;\n"; 6345 Result += "\tconst char *name;\n"; 6346 Result += "\tconst struct _method_list_t *baseMethods;\n"; 6347 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n"; 6348 Result += "\tconst struct _ivar_list_t *ivars;\n"; 6349 Result += "\tconst unsigned char *weakIvarLayout;\n"; 6350 Result += "\tconst struct _prop_list_t *properties;\n"; 6351 Result += "};\n"; 6352 6353 Result += "\nstruct _class_t {\n"; 6354 Result += "\tstruct _class_t *isa;\n"; 6355 Result += "\tstruct _class_t *superclass;\n"; 6356 Result += "\tvoid *cache;\n"; 6357 Result += "\tvoid *vtable;\n"; 6358 Result += "\tstruct _class_ro_t *ro;\n"; 6359 Result += "};\n"; 6360 6361 Result += "\nstruct _category_t {\n"; 6362 Result += "\tconst char *name;\n"; 6363 Result += "\tstruct _class_t *cls;\n"; 6364 Result += "\tconst struct _method_list_t *instance_methods;\n"; 6365 Result += "\tconst struct _method_list_t *class_methods;\n"; 6366 Result += "\tconst struct _protocol_list_t *protocols;\n"; 6367 Result += "\tconst struct _prop_list_t *properties;\n"; 6368 Result += "};\n"; 6369 6370 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n"; 6371 Result += "#pragma warning(disable:4273)\n"; 6372 meta_data_declared = true; 6373 } 6374 6375 static void Write_protocol_list_t_TypeDecl(std::string &Result, 6376 long super_protocol_count) { 6377 Result += "struct /*_protocol_list_t*/"; Result += " {\n"; 6378 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n"; 6379 Result += "\tstruct _protocol_t *super_protocols["; 6380 Result += utostr(super_protocol_count); Result += "];\n"; 6381 Result += "}"; 6382 } 6383 6384 static void Write_method_list_t_TypeDecl(std::string &Result, 6385 unsigned int method_count) { 6386 Result += "struct /*_method_list_t*/"; Result += " {\n"; 6387 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n"; 6388 Result += "\tunsigned int method_count;\n"; 6389 Result += "\tstruct _objc_method method_list["; 6390 Result += utostr(method_count); Result += "];\n"; 6391 Result += "}"; 6392 } 6393 6394 static void Write__prop_list_t_TypeDecl(std::string &Result, 6395 unsigned int property_count) { 6396 Result += "struct /*_prop_list_t*/"; Result += " {\n"; 6397 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n"; 6398 Result += "\tunsigned int count_of_properties;\n"; 6399 Result += "\tstruct _prop_t prop_list["; 6400 Result += utostr(property_count); Result += "];\n"; 6401 Result += "}"; 6402 } 6403 6404 static void Write__ivar_list_t_TypeDecl(std::string &Result, 6405 unsigned int ivar_count) { 6406 Result += "struct /*_ivar_list_t*/"; Result += " {\n"; 6407 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n"; 6408 Result += "\tunsigned int count;\n"; 6409 Result += "\tstruct _ivar_t ivar_list["; 6410 Result += utostr(ivar_count); Result += "];\n"; 6411 Result += "}"; 6412 } 6413 6414 static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result, 6415 ArrayRef<ObjCProtocolDecl *> SuperProtocols, 6416 StringRef VarName, 6417 StringRef ProtocolName) { 6418 if (SuperProtocols.size() > 0) { 6419 Result += "\nstatic "; 6420 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size()); 6421 Result += " "; Result += VarName; 6422 Result += ProtocolName; 6423 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n"; 6424 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n"; 6425 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) { 6426 ObjCProtocolDecl *SuperPD = SuperProtocols[i]; 6427 Result += "\t&"; Result += "_OBJC_PROTOCOL_"; 6428 Result += SuperPD->getNameAsString(); 6429 if (i == e-1) 6430 Result += "\n};\n"; 6431 else 6432 Result += ",\n"; 6433 } 6434 } 6435 } 6436 6437 static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj, 6438 ASTContext *Context, std::string &Result, 6439 ArrayRef<ObjCMethodDecl *> Methods, 6440 StringRef VarName, 6441 StringRef TopLevelDeclName, 6442 bool MethodImpl) { 6443 if (Methods.size() > 0) { 6444 Result += "\nstatic "; 6445 Write_method_list_t_TypeDecl(Result, Methods.size()); 6446 Result += " "; Result += VarName; 6447 Result += TopLevelDeclName; 6448 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n"; 6449 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n"; 6450 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n"; 6451 for (unsigned i = 0, e = Methods.size(); i < e; i++) { 6452 ObjCMethodDecl *MD = Methods[i]; 6453 if (i == 0) 6454 Result += "\t{{(struct objc_selector *)\""; 6455 else 6456 Result += "\t{(struct objc_selector *)\""; 6457 Result += (MD)->getSelector().getAsString(); Result += "\""; 6458 Result += ", "; 6459 std::string MethodTypeString; 6460 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString); 6461 Result += "\""; Result += MethodTypeString; Result += "\""; 6462 Result += ", "; 6463 if (!MethodImpl) 6464 Result += "0"; 6465 else { 6466 Result += "(void *)"; 6467 Result += RewriteObj.MethodInternalNames[MD]; 6468 } 6469 if (i == e-1) 6470 Result += "}}\n"; 6471 else 6472 Result += "},\n"; 6473 } 6474 Result += "};\n"; 6475 } 6476 } 6477 6478 static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj, 6479 ASTContext *Context, std::string &Result, 6480 ArrayRef<ObjCPropertyDecl *> Properties, 6481 const Decl *Container, 6482 StringRef VarName, 6483 StringRef ProtocolName) { 6484 if (Properties.size() > 0) { 6485 Result += "\nstatic "; 6486 Write__prop_list_t_TypeDecl(Result, Properties.size()); 6487 Result += " "; Result += VarName; 6488 Result += ProtocolName; 6489 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n"; 6490 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n"; 6491 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n"; 6492 for (unsigned i = 0, e = Properties.size(); i < e; i++) { 6493 ObjCPropertyDecl *PropDecl = Properties[i]; 6494 if (i == 0) 6495 Result += "\t{{\""; 6496 else 6497 Result += "\t{\""; 6498 Result += PropDecl->getName(); Result += "\","; 6499 std::string PropertyTypeString, QuotePropertyTypeString; 6500 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString); 6501 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString); 6502 Result += "\""; Result += QuotePropertyTypeString; Result += "\""; 6503 if (i == e-1) 6504 Result += "}}\n"; 6505 else 6506 Result += "},\n"; 6507 } 6508 Result += "};\n"; 6509 } 6510 } 6511 6512 // Metadata flags 6513 enum MetaDataDlags { 6514 CLS = 0x0, 6515 CLS_META = 0x1, 6516 CLS_ROOT = 0x2, 6517 OBJC2_CLS_HIDDEN = 0x10, 6518 CLS_EXCEPTION = 0x20, 6519 6520 /// (Obsolete) ARC-specific: this class has a .release_ivars method 6521 CLS_HAS_IVAR_RELEASER = 0x40, 6522 /// class was compiled with -fobjc-arr 6523 CLS_COMPILED_BY_ARC = 0x80 // (1<<7) 6524 }; 6525 6526 static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result, 6527 unsigned int flags, 6528 const std::string &InstanceStart, 6529 const std::string &InstanceSize, 6530 ArrayRef<ObjCMethodDecl *>baseMethods, 6531 ArrayRef<ObjCProtocolDecl *>baseProtocols, 6532 ArrayRef<ObjCIvarDecl *>ivars, 6533 ArrayRef<ObjCPropertyDecl *>Properties, 6534 StringRef VarName, 6535 StringRef ClassName) { 6536 Result += "\nstatic struct _class_ro_t "; 6537 Result += VarName; Result += ClassName; 6538 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n"; 6539 Result += "\t"; 6540 Result += llvm::utostr(flags); Result += ", "; 6541 Result += InstanceStart; Result += ", "; 6542 Result += InstanceSize; Result += ", \n"; 6543 Result += "\t"; 6544 const llvm::Triple &Triple(Context->getTargetInfo().getTriple()); 6545 if (Triple.getArch() == llvm::Triple::x86_64) 6546 // uint32_t const reserved; // only when building for 64bit targets 6547 Result += "(unsigned int)0, \n\t"; 6548 // const uint8_t * const ivarLayout; 6549 Result += "0, \n\t"; 6550 Result += "\""; Result += ClassName; Result += "\",\n\t"; 6551 bool metaclass = ((flags & CLS_META) != 0); 6552 if (baseMethods.size() > 0) { 6553 Result += "(const struct _method_list_t *)&"; 6554 if (metaclass) 6555 Result += "_OBJC_$_CLASS_METHODS_"; 6556 else 6557 Result += "_OBJC_$_INSTANCE_METHODS_"; 6558 Result += ClassName; 6559 Result += ",\n\t"; 6560 } 6561 else 6562 Result += "0, \n\t"; 6563 6564 if (!metaclass && baseProtocols.size() > 0) { 6565 Result += "(const struct _objc_protocol_list *)&"; 6566 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName; 6567 Result += ",\n\t"; 6568 } 6569 else 6570 Result += "0, \n\t"; 6571 6572 if (!metaclass && ivars.size() > 0) { 6573 Result += "(const struct _ivar_list_t *)&"; 6574 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName; 6575 Result += ",\n\t"; 6576 } 6577 else 6578 Result += "0, \n\t"; 6579 6580 // weakIvarLayout 6581 Result += "0, \n\t"; 6582 if (!metaclass && Properties.size() > 0) { 6583 Result += "(const struct _prop_list_t *)&"; 6584 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName; 6585 Result += ",\n"; 6586 } 6587 else 6588 Result += "0, \n"; 6589 6590 Result += "};\n"; 6591 } 6592 6593 static void Write_class_t(ASTContext *Context, std::string &Result, 6594 StringRef VarName, 6595 const ObjCInterfaceDecl *CDecl, bool metaclass) { 6596 bool rootClass = (!CDecl->getSuperClass()); 6597 const ObjCInterfaceDecl *RootClass = CDecl; 6598 6599 if (!rootClass) { 6600 // Find the Root class 6601 RootClass = CDecl->getSuperClass(); 6602 while (RootClass->getSuperClass()) { 6603 RootClass = RootClass->getSuperClass(); 6604 } 6605 } 6606 6607 if (metaclass && rootClass) { 6608 // Need to handle a case of use of forward declaration. 6609 Result += "\n"; 6610 Result += "extern \"C\" "; 6611 if (CDecl->getImplementation()) 6612 Result += "__declspec(dllexport) "; 6613 else 6614 Result += "__declspec(dllimport) "; 6615 6616 Result += "struct _class_t OBJC_CLASS_$_"; 6617 Result += CDecl->getNameAsString(); 6618 Result += ";\n"; 6619 } 6620 // Also, for possibility of 'super' metadata class not having been defined yet. 6621 if (!rootClass) { 6622 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass(); 6623 Result += "\n"; 6624 Result += "extern \"C\" "; 6625 if (SuperClass->getImplementation()) 6626 Result += "__declspec(dllexport) "; 6627 else 6628 Result += "__declspec(dllimport) "; 6629 6630 Result += "struct _class_t "; 6631 Result += VarName; 6632 Result += SuperClass->getNameAsString(); 6633 Result += ";\n"; 6634 6635 if (metaclass && RootClass != SuperClass) { 6636 Result += "extern \"C\" "; 6637 if (RootClass->getImplementation()) 6638 Result += "__declspec(dllexport) "; 6639 else 6640 Result += "__declspec(dllimport) "; 6641 6642 Result += "struct _class_t "; 6643 Result += VarName; 6644 Result += RootClass->getNameAsString(); 6645 Result += ";\n"; 6646 } 6647 } 6648 6649 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t "; 6650 Result += VarName; Result += CDecl->getNameAsString(); 6651 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n"; 6652 Result += "\t"; 6653 if (metaclass) { 6654 if (!rootClass) { 6655 Result += "0, // &"; Result += VarName; 6656 Result += RootClass->getNameAsString(); 6657 Result += ",\n\t"; 6658 Result += "0, // &"; Result += VarName; 6659 Result += CDecl->getSuperClass()->getNameAsString(); 6660 Result += ",\n\t"; 6661 } 6662 else { 6663 Result += "0, // &"; Result += VarName; 6664 Result += CDecl->getNameAsString(); 6665 Result += ",\n\t"; 6666 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString(); 6667 Result += ",\n\t"; 6668 } 6669 } 6670 else { 6671 Result += "0, // &OBJC_METACLASS_$_"; 6672 Result += CDecl->getNameAsString(); 6673 Result += ",\n\t"; 6674 if (!rootClass) { 6675 Result += "0, // &"; Result += VarName; 6676 Result += CDecl->getSuperClass()->getNameAsString(); 6677 Result += ",\n\t"; 6678 } 6679 else 6680 Result += "0,\n\t"; 6681 } 6682 Result += "0, // (void *)&_objc_empty_cache,\n\t"; 6683 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t"; 6684 if (metaclass) 6685 Result += "&_OBJC_METACLASS_RO_$_"; 6686 else 6687 Result += "&_OBJC_CLASS_RO_$_"; 6688 Result += CDecl->getNameAsString(); 6689 Result += ",\n};\n"; 6690 6691 // Add static function to initialize some of the meta-data fields. 6692 // avoid doing it twice. 6693 if (metaclass) 6694 return; 6695 6696 const ObjCInterfaceDecl *SuperClass = 6697 rootClass ? CDecl : CDecl->getSuperClass(); 6698 6699 Result += "static void OBJC_CLASS_SETUP_$_"; 6700 Result += CDecl->getNameAsString(); 6701 Result += "(void ) {\n"; 6702 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString(); 6703 Result += ".isa = "; Result += "&OBJC_METACLASS_$_"; 6704 Result += RootClass->getNameAsString(); Result += ";\n"; 6705 6706 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString(); 6707 Result += ".superclass = "; 6708 if (rootClass) 6709 Result += "&OBJC_CLASS_$_"; 6710 else 6711 Result += "&OBJC_METACLASS_$_"; 6712 6713 Result += SuperClass->getNameAsString(); Result += ";\n"; 6714 6715 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString(); 6716 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n"; 6717 6718 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString(); 6719 Result += ".isa = "; Result += "&OBJC_METACLASS_$_"; 6720 Result += CDecl->getNameAsString(); Result += ";\n"; 6721 6722 if (!rootClass) { 6723 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString(); 6724 Result += ".superclass = "; Result += "&OBJC_CLASS_$_"; 6725 Result += SuperClass->getNameAsString(); Result += ";\n"; 6726 } 6727 6728 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString(); 6729 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n"; 6730 Result += "}\n"; 6731 } 6732 6733 static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context, 6734 std::string &Result, 6735 ObjCCategoryDecl *CatDecl, 6736 ObjCInterfaceDecl *ClassDecl, 6737 ArrayRef<ObjCMethodDecl *> InstanceMethods, 6738 ArrayRef<ObjCMethodDecl *> ClassMethods, 6739 ArrayRef<ObjCProtocolDecl *> RefedProtocols, 6740 ArrayRef<ObjCPropertyDecl *> ClassProperties) { 6741 StringRef CatName = CatDecl->getName(); 6742 StringRef ClassName = ClassDecl->getName(); 6743 // must declare an extern class object in case this class is not implemented 6744 // in this TU. 6745 Result += "\n"; 6746 Result += "extern \"C\" "; 6747 if (ClassDecl->getImplementation()) 6748 Result += "__declspec(dllexport) "; 6749 else 6750 Result += "__declspec(dllimport) "; 6751 6752 Result += "struct _class_t "; 6753 Result += "OBJC_CLASS_$_"; Result += ClassName; 6754 Result += ";\n"; 6755 6756 Result += "\nstatic struct _category_t "; 6757 Result += "_OBJC_$_CATEGORY_"; 6758 Result += ClassName; Result += "_$_"; Result += CatName; 6759 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n"; 6760 Result += "{\n"; 6761 Result += "\t\""; Result += ClassName; Result += "\",\n"; 6762 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName; 6763 Result += ",\n"; 6764 if (InstanceMethods.size() > 0) { 6765 Result += "\t(const struct _method_list_t *)&"; 6766 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_"; 6767 Result += ClassName; Result += "_$_"; Result += CatName; 6768 Result += ",\n"; 6769 } 6770 else 6771 Result += "\t0,\n"; 6772 6773 if (ClassMethods.size() > 0) { 6774 Result += "\t(const struct _method_list_t *)&"; 6775 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_"; 6776 Result += ClassName; Result += "_$_"; Result += CatName; 6777 Result += ",\n"; 6778 } 6779 else 6780 Result += "\t0,\n"; 6781 6782 if (RefedProtocols.size() > 0) { 6783 Result += "\t(const struct _protocol_list_t *)&"; 6784 Result += "_OBJC_CATEGORY_PROTOCOLS_$_"; 6785 Result += ClassName; Result += "_$_"; Result += CatName; 6786 Result += ",\n"; 6787 } 6788 else 6789 Result += "\t0,\n"; 6790 6791 if (ClassProperties.size() > 0) { 6792 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_"; 6793 Result += ClassName; Result += "_$_"; Result += CatName; 6794 Result += ",\n"; 6795 } 6796 else 6797 Result += "\t0,\n"; 6798 6799 Result += "};\n"; 6800 6801 // Add static function to initialize the class pointer in the category structure. 6802 Result += "static void OBJC_CATEGORY_SETUP_$_"; 6803 Result += ClassDecl->getNameAsString(); 6804 Result += "_$_"; 6805 Result += CatName; 6806 Result += "(void ) {\n"; 6807 Result += "\t_OBJC_$_CATEGORY_"; 6808 Result += ClassDecl->getNameAsString(); 6809 Result += "_$_"; 6810 Result += CatName; 6811 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName; 6812 Result += ";\n}\n"; 6813 } 6814 6815 static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj, 6816 ASTContext *Context, std::string &Result, 6817 ArrayRef<ObjCMethodDecl *> Methods, 6818 StringRef VarName, 6819 StringRef ProtocolName) { 6820 if (Methods.size() == 0) 6821 return; 6822 6823 Result += "\nstatic const char *"; 6824 Result += VarName; Result += ProtocolName; 6825 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n"; 6826 Result += "{\n"; 6827 for (unsigned i = 0, e = Methods.size(); i < e; i++) { 6828 ObjCMethodDecl *MD = Methods[i]; 6829 std::string MethodTypeString, QuoteMethodTypeString; 6830 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true); 6831 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString); 6832 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\""; 6833 if (i == e-1) 6834 Result += "\n};\n"; 6835 else { 6836 Result += ",\n"; 6837 } 6838 } 6839 } 6840 6841 static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj, 6842 ASTContext *Context, 6843 std::string &Result, 6844 ArrayRef<ObjCIvarDecl *> Ivars, 6845 ObjCInterfaceDecl *CDecl) { 6846 // FIXME. visibilty of offset symbols may have to be set; for Darwin 6847 // this is what happens: 6848 /** 6849 if (Ivar->getAccessControl() == ObjCIvarDecl::Private || 6850 Ivar->getAccessControl() == ObjCIvarDecl::Package || 6851 Class->getVisibility() == HiddenVisibility) 6852 Visibility shoud be: HiddenVisibility; 6853 else 6854 Visibility shoud be: DefaultVisibility; 6855 */ 6856 6857 Result += "\n"; 6858 for (unsigned i =0, e = Ivars.size(); i < e; i++) { 6859 ObjCIvarDecl *IvarDecl = Ivars[i]; 6860 if (Context->getLangOpts().MicrosoftExt) 6861 Result += "__declspec(allocate(\".objc_ivar$B\")) "; 6862 6863 if (!Context->getLangOpts().MicrosoftExt || 6864 IvarDecl->getAccessControl() == ObjCIvarDecl::Private || 6865 IvarDecl->getAccessControl() == ObjCIvarDecl::Package) 6866 Result += "extern \"C\" unsigned long int "; 6867 else 6868 Result += "extern \"C\" __declspec(dllexport) unsigned long int "; 6869 if (Ivars[i]->isBitField()) 6870 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result); 6871 else 6872 WriteInternalIvarName(CDecl, IvarDecl, Result); 6873 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))"; 6874 Result += " = "; 6875 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result); 6876 Result += ";\n"; 6877 if (Ivars[i]->isBitField()) { 6878 // skip over rest of the ivar bitfields. 6879 SKIP_BITFIELDS(i , e, Ivars); 6880 } 6881 } 6882 } 6883 6884 static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj, 6885 ASTContext *Context, std::string &Result, 6886 ArrayRef<ObjCIvarDecl *> OriginalIvars, 6887 StringRef VarName, 6888 ObjCInterfaceDecl *CDecl) { 6889 if (OriginalIvars.size() > 0) { 6890 Write_IvarOffsetVar(RewriteObj, Context, Result, OriginalIvars, CDecl); 6891 SmallVector<ObjCIvarDecl *, 8> Ivars; 6892 // strip off all but the first ivar bitfield from each group of ivars. 6893 // Such ivars in the ivar list table will be replaced by their grouping struct 6894 // 'ivar'. 6895 for (unsigned i = 0, e = OriginalIvars.size(); i < e; i++) { 6896 if (OriginalIvars[i]->isBitField()) { 6897 Ivars.push_back(OriginalIvars[i]); 6898 // skip over rest of the ivar bitfields. 6899 SKIP_BITFIELDS(i , e, OriginalIvars); 6900 } 6901 else 6902 Ivars.push_back(OriginalIvars[i]); 6903 } 6904 6905 Result += "\nstatic "; 6906 Write__ivar_list_t_TypeDecl(Result, Ivars.size()); 6907 Result += " "; Result += VarName; 6908 Result += CDecl->getNameAsString(); 6909 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n"; 6910 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n"; 6911 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n"; 6912 for (unsigned i =0, e = Ivars.size(); i < e; i++) { 6913 ObjCIvarDecl *IvarDecl = Ivars[i]; 6914 if (i == 0) 6915 Result += "\t{{"; 6916 else 6917 Result += "\t {"; 6918 Result += "(unsigned long int *)&"; 6919 if (Ivars[i]->isBitField()) 6920 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result); 6921 else 6922 WriteInternalIvarName(CDecl, IvarDecl, Result); 6923 Result += ", "; 6924 6925 Result += "\""; 6926 if (Ivars[i]->isBitField()) 6927 RewriteObj.ObjCIvarBitfieldGroupDecl(Ivars[i], Result); 6928 else 6929 Result += IvarDecl->getName(); 6930 Result += "\", "; 6931 6932 QualType IVQT = IvarDecl->getType(); 6933 if (IvarDecl->isBitField()) 6934 IVQT = RewriteObj.GetGroupRecordTypeForObjCIvarBitfield(IvarDecl); 6935 6936 std::string IvarTypeString, QuoteIvarTypeString; 6937 Context->getObjCEncodingForType(IVQT, IvarTypeString, 6938 IvarDecl); 6939 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString); 6940 Result += "\""; Result += QuoteIvarTypeString; Result += "\", "; 6941 6942 // FIXME. this alignment represents the host alignment and need be changed to 6943 // represent the target alignment. 6944 unsigned Align = Context->getTypeAlign(IVQT)/8; 6945 Align = llvm::Log2_32(Align); 6946 Result += llvm::utostr(Align); Result += ", "; 6947 CharUnits Size = Context->getTypeSizeInChars(IVQT); 6948 Result += llvm::utostr(Size.getQuantity()); 6949 if (i == e-1) 6950 Result += "}}\n"; 6951 else 6952 Result += "},\n"; 6953 } 6954 Result += "};\n"; 6955 } 6956 } 6957 6958 /// RewriteObjCProtocolMetaData - Rewrite protocols meta-data. 6959 void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, 6960 std::string &Result) { 6961 6962 // Do not synthesize the protocol more than once. 6963 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl())) 6964 return; 6965 WriteModernMetadataDeclarations(Context, Result); 6966 6967 if (ObjCProtocolDecl *Def = PDecl->getDefinition()) 6968 PDecl = Def; 6969 // Must write out all protocol definitions in current qualifier list, 6970 // and in their nested qualifiers before writing out current definition. 6971 for (auto *I : PDecl->protocols()) 6972 RewriteObjCProtocolMetaData(I, Result); 6973 6974 // Construct method lists. 6975 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods; 6976 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods; 6977 for (auto *MD : PDecl->instance_methods()) { 6978 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) { 6979 OptInstanceMethods.push_back(MD); 6980 } else { 6981 InstanceMethods.push_back(MD); 6982 } 6983 } 6984 6985 for (auto *MD : PDecl->class_methods()) { 6986 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) { 6987 OptClassMethods.push_back(MD); 6988 } else { 6989 ClassMethods.push_back(MD); 6990 } 6991 } 6992 std::vector<ObjCMethodDecl *> AllMethods; 6993 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++) 6994 AllMethods.push_back(InstanceMethods[i]); 6995 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++) 6996 AllMethods.push_back(ClassMethods[i]); 6997 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++) 6998 AllMethods.push_back(OptInstanceMethods[i]); 6999 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++) 7000 AllMethods.push_back(OptClassMethods[i]); 7001 7002 Write__extendedMethodTypes_initializer(*this, Context, Result, 7003 AllMethods, 7004 "_OBJC_PROTOCOL_METHOD_TYPES_", 7005 PDecl->getNameAsString()); 7006 // Protocol's super protocol list 7007 SmallVector<ObjCProtocolDecl *, 8> SuperProtocols(PDecl->protocols()); 7008 Write_protocol_list_initializer(Context, Result, SuperProtocols, 7009 "_OBJC_PROTOCOL_REFS_", 7010 PDecl->getNameAsString()); 7011 7012 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods, 7013 "_OBJC_PROTOCOL_INSTANCE_METHODS_", 7014 PDecl->getNameAsString(), false); 7015 7016 Write_method_list_t_initializer(*this, Context, Result, ClassMethods, 7017 "_OBJC_PROTOCOL_CLASS_METHODS_", 7018 PDecl->getNameAsString(), false); 7019 7020 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods, 7021 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_", 7022 PDecl->getNameAsString(), false); 7023 7024 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods, 7025 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_", 7026 PDecl->getNameAsString(), false); 7027 7028 // Protocol's property metadata. 7029 SmallVector<ObjCPropertyDecl *, 8> ProtocolProperties(PDecl->properties()); 7030 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties, 7031 /* Container */nullptr, 7032 "_OBJC_PROTOCOL_PROPERTIES_", 7033 PDecl->getNameAsString()); 7034 7035 // Writer out root metadata for current protocol: struct _protocol_t 7036 Result += "\n"; 7037 if (LangOpts.MicrosoftExt) 7038 Result += "static "; 7039 Result += "struct _protocol_t _OBJC_PROTOCOL_"; 7040 Result += PDecl->getNameAsString(); 7041 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n"; 7042 Result += "\t0,\n"; // id is; is null 7043 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n"; 7044 if (SuperProtocols.size() > 0) { 7045 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_"; 7046 Result += PDecl->getNameAsString(); Result += ",\n"; 7047 } 7048 else 7049 Result += "\t0,\n"; 7050 if (InstanceMethods.size() > 0) { 7051 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_"; 7052 Result += PDecl->getNameAsString(); Result += ",\n"; 7053 } 7054 else 7055 Result += "\t0,\n"; 7056 7057 if (ClassMethods.size() > 0) { 7058 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_"; 7059 Result += PDecl->getNameAsString(); Result += ",\n"; 7060 } 7061 else 7062 Result += "\t0,\n"; 7063 7064 if (OptInstanceMethods.size() > 0) { 7065 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_"; 7066 Result += PDecl->getNameAsString(); Result += ",\n"; 7067 } 7068 else 7069 Result += "\t0,\n"; 7070 7071 if (OptClassMethods.size() > 0) { 7072 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_"; 7073 Result += PDecl->getNameAsString(); Result += ",\n"; 7074 } 7075 else 7076 Result += "\t0,\n"; 7077 7078 if (ProtocolProperties.size() > 0) { 7079 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_"; 7080 Result += PDecl->getNameAsString(); Result += ",\n"; 7081 } 7082 else 7083 Result += "\t0,\n"; 7084 7085 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n"; 7086 Result += "\t0,\n"; 7087 7088 if (AllMethods.size() > 0) { 7089 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_"; 7090 Result += PDecl->getNameAsString(); 7091 Result += "\n};\n"; 7092 } 7093 else 7094 Result += "\t0\n};\n"; 7095 7096 if (LangOpts.MicrosoftExt) 7097 Result += "static "; 7098 Result += "struct _protocol_t *"; 7099 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString(); 7100 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString(); 7101 Result += ";\n"; 7102 7103 // Mark this protocol as having been generated. 7104 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl())) 7105 llvm_unreachable("protocol already synthesized"); 7106 7107 } 7108 7109 void RewriteModernObjC::RewriteObjCProtocolListMetaData( 7110 const ObjCList<ObjCProtocolDecl> &Protocols, 7111 StringRef prefix, StringRef ClassName, 7112 std::string &Result) { 7113 if (Protocols.empty()) return; 7114 7115 for (unsigned i = 0; i != Protocols.size(); i++) 7116 RewriteObjCProtocolMetaData(Protocols[i], Result); 7117 7118 // Output the top lovel protocol meta-data for the class. 7119 /* struct _objc_protocol_list { 7120 struct _objc_protocol_list *next; 7121 int protocol_count; 7122 struct _objc_protocol *class_protocols[]; 7123 } 7124 */ 7125 Result += "\n"; 7126 if (LangOpts.MicrosoftExt) 7127 Result += "__declspec(allocate(\".cat_cls_meth$B\")) "; 7128 Result += "static struct {\n"; 7129 Result += "\tstruct _objc_protocol_list *next;\n"; 7130 Result += "\tint protocol_count;\n"; 7131 Result += "\tstruct _objc_protocol *class_protocols["; 7132 Result += utostr(Protocols.size()); 7133 Result += "];\n} _OBJC_"; 7134 Result += prefix; 7135 Result += "_PROTOCOLS_"; 7136 Result += ClassName; 7137 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= " 7138 "{\n\t0, "; 7139 Result += utostr(Protocols.size()); 7140 Result += "\n"; 7141 7142 Result += "\t,{&_OBJC_PROTOCOL_"; 7143 Result += Protocols[0]->getNameAsString(); 7144 Result += " \n"; 7145 7146 for (unsigned i = 1; i != Protocols.size(); i++) { 7147 Result += "\t ,&_OBJC_PROTOCOL_"; 7148 Result += Protocols[i]->getNameAsString(); 7149 Result += "\n"; 7150 } 7151 Result += "\t }\n};\n"; 7152 } 7153 7154 /// hasObjCExceptionAttribute - Return true if this class or any super 7155 /// class has the __objc_exception__ attribute. 7156 /// FIXME. Move this to ASTContext.cpp as it is also used for IRGen. 7157 static bool hasObjCExceptionAttribute(ASTContext &Context, 7158 const ObjCInterfaceDecl *OID) { 7159 if (OID->hasAttr<ObjCExceptionAttr>()) 7160 return true; 7161 if (const ObjCInterfaceDecl *Super = OID->getSuperClass()) 7162 return hasObjCExceptionAttribute(Context, Super); 7163 return false; 7164 } 7165 7166 void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl, 7167 std::string &Result) { 7168 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface(); 7169 7170 // Explicitly declared @interface's are already synthesized. 7171 if (CDecl->isImplicitInterfaceDecl()) 7172 assert(false && 7173 "Legacy implicit interface rewriting not supported in moder abi"); 7174 7175 WriteModernMetadataDeclarations(Context, Result); 7176 SmallVector<ObjCIvarDecl *, 8> IVars; 7177 7178 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin(); 7179 IVD; IVD = IVD->getNextIvar()) { 7180 // Ignore unnamed bit-fields. 7181 if (!IVD->getDeclName()) 7182 continue; 7183 IVars.push_back(IVD); 7184 } 7185 7186 Write__ivar_list_t_initializer(*this, Context, Result, IVars, 7187 "_OBJC_$_INSTANCE_VARIABLES_", 7188 CDecl); 7189 7190 // Build _objc_method_list for class's instance methods if needed 7191 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods()); 7192 7193 // If any of our property implementations have associated getters or 7194 // setters, produce metadata for them as well. 7195 for (const auto *Prop : IDecl->property_impls()) { 7196 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic) 7197 continue; 7198 if (!Prop->getPropertyIvarDecl()) 7199 continue; 7200 ObjCPropertyDecl *PD = Prop->getPropertyDecl(); 7201 if (!PD) 7202 continue; 7203 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl()) 7204 if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/)) 7205 InstanceMethods.push_back(Getter); 7206 if (PD->isReadOnly()) 7207 continue; 7208 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl()) 7209 if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/)) 7210 InstanceMethods.push_back(Setter); 7211 } 7212 7213 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods, 7214 "_OBJC_$_INSTANCE_METHODS_", 7215 IDecl->getNameAsString(), true); 7216 7217 SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods()); 7218 7219 Write_method_list_t_initializer(*this, Context, Result, ClassMethods, 7220 "_OBJC_$_CLASS_METHODS_", 7221 IDecl->getNameAsString(), true); 7222 7223 // Protocols referenced in class declaration? 7224 // Protocol's super protocol list 7225 std::vector<ObjCProtocolDecl *> RefedProtocols; 7226 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols(); 7227 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 7228 E = Protocols.end(); 7229 I != E; ++I) { 7230 RefedProtocols.push_back(*I); 7231 // Must write out all protocol definitions in current qualifier list, 7232 // and in their nested qualifiers before writing out current definition. 7233 RewriteObjCProtocolMetaData(*I, Result); 7234 } 7235 7236 Write_protocol_list_initializer(Context, Result, 7237 RefedProtocols, 7238 "_OBJC_CLASS_PROTOCOLS_$_", 7239 IDecl->getNameAsString()); 7240 7241 // Protocol's property metadata. 7242 SmallVector<ObjCPropertyDecl *, 8> ClassProperties(CDecl->properties()); 7243 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties, 7244 /* Container */IDecl, 7245 "_OBJC_$_PROP_LIST_", 7246 CDecl->getNameAsString()); 7247 7248 7249 // Data for initializing _class_ro_t metaclass meta-data 7250 uint32_t flags = CLS_META; 7251 std::string InstanceSize; 7252 std::string InstanceStart; 7253 7254 7255 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility; 7256 if (classIsHidden) 7257 flags |= OBJC2_CLS_HIDDEN; 7258 7259 if (!CDecl->getSuperClass()) 7260 // class is root 7261 flags |= CLS_ROOT; 7262 InstanceSize = "sizeof(struct _class_t)"; 7263 InstanceStart = InstanceSize; 7264 Write__class_ro_t_initializer(Context, Result, flags, 7265 InstanceStart, InstanceSize, 7266 ClassMethods, 7267 nullptr, 7268 nullptr, 7269 nullptr, 7270 "_OBJC_METACLASS_RO_$_", 7271 CDecl->getNameAsString()); 7272 7273 // Data for initializing _class_ro_t meta-data 7274 flags = CLS; 7275 if (classIsHidden) 7276 flags |= OBJC2_CLS_HIDDEN; 7277 7278 if (hasObjCExceptionAttribute(*Context, CDecl)) 7279 flags |= CLS_EXCEPTION; 7280 7281 if (!CDecl->getSuperClass()) 7282 // class is root 7283 flags |= CLS_ROOT; 7284 7285 InstanceSize.clear(); 7286 InstanceStart.clear(); 7287 if (!ObjCSynthesizedStructs.count(CDecl)) { 7288 InstanceSize = "0"; 7289 InstanceStart = "0"; 7290 } 7291 else { 7292 InstanceSize = "sizeof(struct "; 7293 InstanceSize += CDecl->getNameAsString(); 7294 InstanceSize += "_IMPL)"; 7295 7296 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin(); 7297 if (IVD) { 7298 RewriteIvarOffsetComputation(IVD, InstanceStart); 7299 } 7300 else 7301 InstanceStart = InstanceSize; 7302 } 7303 Write__class_ro_t_initializer(Context, Result, flags, 7304 InstanceStart, InstanceSize, 7305 InstanceMethods, 7306 RefedProtocols, 7307 IVars, 7308 ClassProperties, 7309 "_OBJC_CLASS_RO_$_", 7310 CDecl->getNameAsString()); 7311 7312 Write_class_t(Context, Result, 7313 "OBJC_METACLASS_$_", 7314 CDecl, /*metaclass*/true); 7315 7316 Write_class_t(Context, Result, 7317 "OBJC_CLASS_$_", 7318 CDecl, /*metaclass*/false); 7319 7320 if (ImplementationIsNonLazy(IDecl)) 7321 DefinedNonLazyClasses.push_back(CDecl); 7322 7323 } 7324 7325 void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) { 7326 int ClsDefCount = ClassImplementation.size(); 7327 if (!ClsDefCount) 7328 return; 7329 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n"; 7330 Result += "__declspec(allocate(\".objc_inithooks$B\")) "; 7331 Result += "static void *OBJC_CLASS_SETUP[] = {\n"; 7332 for (int i = 0; i < ClsDefCount; i++) { 7333 ObjCImplementationDecl *IDecl = ClassImplementation[i]; 7334 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface(); 7335 Result += "\t(void *)&OBJC_CLASS_SETUP_$_"; 7336 Result += CDecl->getName(); Result += ",\n"; 7337 } 7338 Result += "};\n"; 7339 } 7340 7341 void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) { 7342 int ClsDefCount = ClassImplementation.size(); 7343 int CatDefCount = CategoryImplementation.size(); 7344 7345 // For each implemented class, write out all its meta data. 7346 for (int i = 0; i < ClsDefCount; i++) 7347 RewriteObjCClassMetaData(ClassImplementation[i], Result); 7348 7349 RewriteClassSetupInitHook(Result); 7350 7351 // For each implemented category, write out all its meta data. 7352 for (int i = 0; i < CatDefCount; i++) 7353 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result); 7354 7355 RewriteCategorySetupInitHook(Result); 7356 7357 if (ClsDefCount > 0) { 7358 if (LangOpts.MicrosoftExt) 7359 Result += "__declspec(allocate(\".objc_classlist$B\")) "; 7360 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ ["; 7361 Result += llvm::utostr(ClsDefCount); Result += "]"; 7362 Result += 7363 " __attribute__((used, section (\"__DATA, __objc_classlist," 7364 "regular,no_dead_strip\")))= {\n"; 7365 for (int i = 0; i < ClsDefCount; i++) { 7366 Result += "\t&OBJC_CLASS_$_"; 7367 Result += ClassImplementation[i]->getNameAsString(); 7368 Result += ",\n"; 7369 } 7370 Result += "};\n"; 7371 7372 if (!DefinedNonLazyClasses.empty()) { 7373 if (LangOpts.MicrosoftExt) 7374 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n"; 7375 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t"; 7376 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) { 7377 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString(); 7378 Result += ",\n"; 7379 } 7380 Result += "};\n"; 7381 } 7382 } 7383 7384 if (CatDefCount > 0) { 7385 if (LangOpts.MicrosoftExt) 7386 Result += "__declspec(allocate(\".objc_catlist$B\")) "; 7387 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ ["; 7388 Result += llvm::utostr(CatDefCount); Result += "]"; 7389 Result += 7390 " __attribute__((used, section (\"__DATA, __objc_catlist," 7391 "regular,no_dead_strip\")))= {\n"; 7392 for (int i = 0; i < CatDefCount; i++) { 7393 Result += "\t&_OBJC_$_CATEGORY_"; 7394 Result += 7395 CategoryImplementation[i]->getClassInterface()->getNameAsString(); 7396 Result += "_$_"; 7397 Result += CategoryImplementation[i]->getNameAsString(); 7398 Result += ",\n"; 7399 } 7400 Result += "};\n"; 7401 } 7402 7403 if (!DefinedNonLazyCategories.empty()) { 7404 if (LangOpts.MicrosoftExt) 7405 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n"; 7406 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t"; 7407 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) { 7408 Result += "\t&_OBJC_$_CATEGORY_"; 7409 Result += 7410 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString(); 7411 Result += "_$_"; 7412 Result += DefinedNonLazyCategories[i]->getNameAsString(); 7413 Result += ",\n"; 7414 } 7415 Result += "};\n"; 7416 } 7417 } 7418 7419 void RewriteModernObjC::WriteImageInfo(std::string &Result) { 7420 if (LangOpts.MicrosoftExt) 7421 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n"; 7422 7423 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } "; 7424 // version 0, ObjCABI is 2 7425 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n"; 7426 } 7427 7428 /// RewriteObjCCategoryImplDecl - Rewrite metadata for each category 7429 /// implementation. 7430 void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl, 7431 std::string &Result) { 7432 WriteModernMetadataDeclarations(Context, Result); 7433 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface(); 7434 // Find category declaration for this implementation. 7435 ObjCCategoryDecl *CDecl 7436 = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier()); 7437 7438 std::string FullCategoryName = ClassDecl->getNameAsString(); 7439 FullCategoryName += "_$_"; 7440 FullCategoryName += CDecl->getNameAsString(); 7441 7442 // Build _objc_method_list for class's instance methods if needed 7443 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods()); 7444 7445 // If any of our property implementations have associated getters or 7446 // setters, produce metadata for them as well. 7447 for (const auto *Prop : IDecl->property_impls()) { 7448 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic) 7449 continue; 7450 if (!Prop->getPropertyIvarDecl()) 7451 continue; 7452 ObjCPropertyDecl *PD = Prop->getPropertyDecl(); 7453 if (!PD) 7454 continue; 7455 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl()) 7456 InstanceMethods.push_back(Getter); 7457 if (PD->isReadOnly()) 7458 continue; 7459 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl()) 7460 InstanceMethods.push_back(Setter); 7461 } 7462 7463 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods, 7464 "_OBJC_$_CATEGORY_INSTANCE_METHODS_", 7465 FullCategoryName, true); 7466 7467 SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods()); 7468 7469 Write_method_list_t_initializer(*this, Context, Result, ClassMethods, 7470 "_OBJC_$_CATEGORY_CLASS_METHODS_", 7471 FullCategoryName, true); 7472 7473 // Protocols referenced in class declaration? 7474 // Protocol's super protocol list 7475 SmallVector<ObjCProtocolDecl *, 8> RefedProtocols(CDecl->protocols()); 7476 for (auto *I : CDecl->protocols()) 7477 // Must write out all protocol definitions in current qualifier list, 7478 // and in their nested qualifiers before writing out current definition. 7479 RewriteObjCProtocolMetaData(I, Result); 7480 7481 Write_protocol_list_initializer(Context, Result, 7482 RefedProtocols, 7483 "_OBJC_CATEGORY_PROTOCOLS_$_", 7484 FullCategoryName); 7485 7486 // Protocol's property metadata. 7487 SmallVector<ObjCPropertyDecl *, 8> ClassProperties(CDecl->properties()); 7488 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties, 7489 /* Container */IDecl, 7490 "_OBJC_$_PROP_LIST_", 7491 FullCategoryName); 7492 7493 Write_category_t(*this, Context, Result, 7494 CDecl, 7495 ClassDecl, 7496 InstanceMethods, 7497 ClassMethods, 7498 RefedProtocols, 7499 ClassProperties); 7500 7501 // Determine if this category is also "non-lazy". 7502 if (ImplementationIsNonLazy(IDecl)) 7503 DefinedNonLazyCategories.push_back(CDecl); 7504 7505 } 7506 7507 void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) { 7508 int CatDefCount = CategoryImplementation.size(); 7509 if (!CatDefCount) 7510 return; 7511 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n"; 7512 Result += "__declspec(allocate(\".objc_inithooks$B\")) "; 7513 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n"; 7514 for (int i = 0; i < CatDefCount; i++) { 7515 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i]; 7516 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl(); 7517 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface(); 7518 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_"; 7519 Result += ClassDecl->getName(); 7520 Result += "_$_"; 7521 Result += CatDecl->getName(); 7522 Result += ",\n"; 7523 } 7524 Result += "};\n"; 7525 } 7526 7527 // RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or 7528 /// class methods. 7529 template<typename MethodIterator> 7530 void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin, 7531 MethodIterator MethodEnd, 7532 bool IsInstanceMethod, 7533 StringRef prefix, 7534 StringRef ClassName, 7535 std::string &Result) { 7536 if (MethodBegin == MethodEnd) return; 7537 7538 if (!objc_impl_method) { 7539 /* struct _objc_method { 7540 SEL _cmd; 7541 char *method_types; 7542 void *_imp; 7543 } 7544 */ 7545 Result += "\nstruct _objc_method {\n"; 7546 Result += "\tSEL _cmd;\n"; 7547 Result += "\tchar *method_types;\n"; 7548 Result += "\tvoid *_imp;\n"; 7549 Result += "};\n"; 7550 7551 objc_impl_method = true; 7552 } 7553 7554 // Build _objc_method_list for class's methods if needed 7555 7556 /* struct { 7557 struct _objc_method_list *next_method; 7558 int method_count; 7559 struct _objc_method method_list[]; 7560 } 7561 */ 7562 unsigned NumMethods = std::distance(MethodBegin, MethodEnd); 7563 Result += "\n"; 7564 if (LangOpts.MicrosoftExt) { 7565 if (IsInstanceMethod) 7566 Result += "__declspec(allocate(\".inst_meth$B\")) "; 7567 else 7568 Result += "__declspec(allocate(\".cls_meth$B\")) "; 7569 } 7570 Result += "static struct {\n"; 7571 Result += "\tstruct _objc_method_list *next_method;\n"; 7572 Result += "\tint method_count;\n"; 7573 Result += "\tstruct _objc_method method_list["; 7574 Result += utostr(NumMethods); 7575 Result += "];\n} _OBJC_"; 7576 Result += prefix; 7577 Result += IsInstanceMethod ? "INSTANCE" : "CLASS"; 7578 Result += "_METHODS_"; 7579 Result += ClassName; 7580 Result += " __attribute__ ((used, section (\"__OBJC, __"; 7581 Result += IsInstanceMethod ? "inst" : "cls"; 7582 Result += "_meth\")))= "; 7583 Result += "{\n\t0, " + utostr(NumMethods) + "\n"; 7584 7585 Result += "\t,{{(SEL)\""; 7586 Result += (*MethodBegin)->getSelector().getAsString().c_str(); 7587 std::string MethodTypeString; 7588 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString); 7589 Result += "\", \""; 7590 Result += MethodTypeString; 7591 Result += "\", (void *)"; 7592 Result += MethodInternalNames[*MethodBegin]; 7593 Result += "}\n"; 7594 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) { 7595 Result += "\t ,{(SEL)\""; 7596 Result += (*MethodBegin)->getSelector().getAsString().c_str(); 7597 std::string MethodTypeString; 7598 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString); 7599 Result += "\", \""; 7600 Result += MethodTypeString; 7601 Result += "\", (void *)"; 7602 Result += MethodInternalNames[*MethodBegin]; 7603 Result += "}\n"; 7604 } 7605 Result += "\t }\n};\n"; 7606 } 7607 7608 Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) { 7609 SourceRange OldRange = IV->getSourceRange(); 7610 Expr *BaseExpr = IV->getBase(); 7611 7612 // Rewrite the base, but without actually doing replaces. 7613 { 7614 DisableReplaceStmtScope S(*this); 7615 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr)); 7616 IV->setBase(BaseExpr); 7617 } 7618 7619 ObjCIvarDecl *D = IV->getDecl(); 7620 7621 Expr *Replacement = IV; 7622 7623 if (BaseExpr->getType()->isObjCObjectPointerType()) { 7624 const ObjCInterfaceType *iFaceDecl = 7625 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType()); 7626 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null"); 7627 // lookup which class implements the instance variable. 7628 ObjCInterfaceDecl *clsDeclared = nullptr; 7629 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), 7630 clsDeclared); 7631 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class"); 7632 7633 // Build name of symbol holding ivar offset. 7634 std::string IvarOffsetName; 7635 if (D->isBitField()) 7636 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName); 7637 else 7638 WriteInternalIvarName(clsDeclared, D, IvarOffsetName); 7639 7640 ReferencedIvars[clsDeclared].insert(D); 7641 7642 // cast offset to "char *". 7643 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, 7644 Context->getPointerType(Context->CharTy), 7645 CK_BitCast, 7646 BaseExpr); 7647 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(), 7648 SourceLocation(), &Context->Idents.get(IvarOffsetName), 7649 Context->UnsignedLongTy, nullptr, 7650 SC_Extern); 7651 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, 7652 Context->UnsignedLongTy, VK_LValue, 7653 SourceLocation()); 7654 BinaryOperator *addExpr = 7655 new (Context) BinaryOperator(castExpr, DRE, BO_Add, 7656 Context->getPointerType(Context->CharTy), 7657 VK_RValue, OK_Ordinary, SourceLocation(), false); 7658 // Don't forget the parens to enforce the proper binding. 7659 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), 7660 SourceLocation(), 7661 addExpr); 7662 QualType IvarT = D->getType(); 7663 if (D->isBitField()) 7664 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D); 7665 7666 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) { 7667 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl(); 7668 RD = RD->getDefinition(); 7669 if (RD && !RD->getDeclName().getAsIdentifierInfo()) { 7670 // decltype(((Foo_IMPL*)0)->bar) * 7671 ObjCContainerDecl *CDecl = 7672 dyn_cast<ObjCContainerDecl>(D->getDeclContext()); 7673 // ivar in class extensions requires special treatment. 7674 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl)) 7675 CDecl = CatDecl->getClassInterface(); 7676 std::string RecName = CDecl->getName(); 7677 RecName += "_IMPL"; 7678 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl, 7679 SourceLocation(), SourceLocation(), 7680 &Context->Idents.get(RecName.c_str())); 7681 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD)); 7682 unsigned UnsignedIntSize = 7683 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy)); 7684 Expr *Zero = IntegerLiteral::Create(*Context, 7685 llvm::APInt(UnsignedIntSize, 0), 7686 Context->UnsignedIntTy, SourceLocation()); 7687 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero); 7688 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), 7689 Zero); 7690 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), 7691 SourceLocation(), 7692 &Context->Idents.get(D->getNameAsString()), 7693 IvarT, nullptr, 7694 /*BitWidth=*/nullptr, 7695 /*Mutable=*/true, ICIS_NoInit); 7696 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(), 7697 FD->getType(), VK_LValue, 7698 OK_Ordinary); 7699 IvarT = Context->getDecltypeType(ME, ME->getType()); 7700 } 7701 } 7702 convertObjCTypeToCStyleType(IvarT); 7703 QualType castT = Context->getPointerType(IvarT); 7704 7705 castExpr = NoTypeInfoCStyleCastExpr(Context, 7706 castT, 7707 CK_BitCast, 7708 PE); 7709 7710 7711 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT, 7712 VK_LValue, OK_Ordinary, 7713 SourceLocation()); 7714 PE = new (Context) ParenExpr(OldRange.getBegin(), 7715 OldRange.getEnd(), 7716 Exp); 7717 7718 if (D->isBitField()) { 7719 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), 7720 SourceLocation(), 7721 &Context->Idents.get(D->getNameAsString()), 7722 D->getType(), nullptr, 7723 /*BitWidth=*/D->getBitWidth(), 7724 /*Mutable=*/true, ICIS_NoInit); 7725 MemberExpr *ME = new (Context) MemberExpr(PE, /*isArrow*/false, FD, SourceLocation(), 7726 FD->getType(), VK_LValue, 7727 OK_Ordinary); 7728 Replacement = ME; 7729 7730 } 7731 else 7732 Replacement = PE; 7733 } 7734 7735 ReplaceStmtWithRange(IV, Replacement, OldRange); 7736 return Replacement; 7737 } 7738 7739 #endif 7740