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