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