Shih-wei Liao | f8fd82b | 2010-02-10 11:10:31 -0800 | [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/Frontend/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 | using namespace clang; |
| 30 | using llvm::utostr; |
| 31 | |
| 32 | namespace { |
| 33 | class RewriteObjC : public ASTConsumer { |
| 34 | enum { |
| 35 | BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)), |
| 36 | block, ... */ |
| 37 | BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */ |
| 38 | BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the |
| 39 | __block variable */ |
| 40 | BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy |
| 41 | helpers */ |
| 42 | BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose |
| 43 | support routines */ |
| 44 | BLOCK_BYREF_CURRENT_MAX = 256 |
| 45 | }; |
| 46 | |
| 47 | enum { |
| 48 | BLOCK_NEEDS_FREE = (1 << 24), |
| 49 | BLOCK_HAS_COPY_DISPOSE = (1 << 25), |
| 50 | BLOCK_HAS_CXX_OBJ = (1 << 26), |
| 51 | BLOCK_IS_GC = (1 << 27), |
| 52 | BLOCK_IS_GLOBAL = (1 << 28), |
| 53 | BLOCK_HAS_DESCRIPTOR = (1 << 29) |
| 54 | }; |
| 55 | |
| 56 | Rewriter Rewrite; |
| 57 | Diagnostic &Diags; |
| 58 | const LangOptions &LangOpts; |
| 59 | unsigned RewriteFailedDiag; |
| 60 | unsigned TryFinallyContainsReturnDiag; |
| 61 | |
| 62 | ASTContext *Context; |
| 63 | SourceManager *SM; |
| 64 | TranslationUnitDecl *TUDecl; |
| 65 | FileID MainFileID; |
| 66 | const char *MainFileStart, *MainFileEnd; |
| 67 | SourceLocation LastIncLoc; |
| 68 | |
| 69 | llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation; |
| 70 | llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation; |
| 71 | llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs; |
| 72 | llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols; |
| 73 | llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls; |
| 74 | llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames; |
| 75 | llvm::SmallVector<Stmt *, 32> Stmts; |
| 76 | llvm::SmallVector<int, 8> ObjCBcLabelNo; |
| 77 | // Remember all the @protocol(<expr>) expressions. |
| 78 | llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls; |
| 79 | |
| 80 | llvm::DenseSet<uint64_t> CopyDestroyCache; |
| 81 | |
| 82 | unsigned NumObjCStringLiterals; |
| 83 | |
| 84 | FunctionDecl *MsgSendFunctionDecl; |
| 85 | FunctionDecl *MsgSendSuperFunctionDecl; |
| 86 | FunctionDecl *MsgSendStretFunctionDecl; |
| 87 | FunctionDecl *MsgSendSuperStretFunctionDecl; |
| 88 | FunctionDecl *MsgSendFpretFunctionDecl; |
| 89 | FunctionDecl *GetClassFunctionDecl; |
| 90 | FunctionDecl *GetMetaClassFunctionDecl; |
| 91 | FunctionDecl *SelGetUidFunctionDecl; |
| 92 | FunctionDecl *CFStringFunctionDecl; |
| 93 | FunctionDecl *SuperContructorFunctionDecl; |
| 94 | |
| 95 | // ObjC string constant support. |
| 96 | VarDecl *ConstantStringClassReference; |
| 97 | RecordDecl *NSStringRecord; |
| 98 | |
| 99 | // ObjC foreach break/continue generation support. |
| 100 | int BcLabelCount; |
| 101 | |
| 102 | // Needed for super. |
| 103 | ObjCMethodDecl *CurMethodDef; |
| 104 | RecordDecl *SuperStructDecl; |
| 105 | RecordDecl *ConstantStringDecl; |
| 106 | |
| 107 | TypeDecl *ProtocolTypeDecl; |
| 108 | QualType getProtocolType(); |
| 109 | |
| 110 | // Needed for header files being rewritten |
| 111 | bool IsHeader; |
| 112 | |
| 113 | std::string InFileName; |
| 114 | llvm::raw_ostream* OutFile; |
| 115 | |
| 116 | bool SilenceRewriteMacroWarning; |
| 117 | bool objc_impl_method; |
| 118 | |
| 119 | std::string Preamble; |
| 120 | |
| 121 | // Block expressions. |
| 122 | llvm::SmallVector<BlockExpr *, 32> Blocks; |
| 123 | llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs; |
| 124 | llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs; |
| 125 | |
| 126 | // Block related declarations. |
| 127 | llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls; |
| 128 | llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls; |
| 129 | llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo; |
| 130 | llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls; |
| 131 | |
| 132 | llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs; |
| 133 | |
| 134 | // This maps a property to it's assignment statement. |
| 135 | llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters; |
| 136 | // This maps a property to it's synthesied message expression. |
| 137 | // This allows us to rewrite chained getters (e.g. o.a.b.c). |
| 138 | llvm::DenseMap<ObjCPropertyRefExpr *, Stmt *> PropGetters; |
| 139 | |
| 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 | FunctionDecl *CurFunctionDef; |
| 146 | FunctionDecl *CurFunctionDeclToDeclareForBlock; |
| 147 | VarDecl *GlobalVarDecl; |
| 148 | |
| 149 | bool DisableReplaceStmt; |
| 150 | |
| 151 | static const int OBJC_ABI_VERSION =7 ; |
| 152 | public: |
| 153 | virtual void Initialize(ASTContext &context); |
| 154 | |
| 155 | // Top Level Driver code. |
| 156 | virtual void HandleTopLevelDecl(DeclGroupRef D) { |
| 157 | for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) |
| 158 | HandleTopLevelSingleDecl(*I); |
| 159 | } |
| 160 | void HandleTopLevelSingleDecl(Decl *D); |
| 161 | void HandleDeclInMainFile(Decl *D); |
| 162 | RewriteObjC(std::string inFile, llvm::raw_ostream *OS, |
| 163 | Diagnostic &D, const LangOptions &LOpts, |
| 164 | bool silenceMacroWarn); |
| 165 | |
| 166 | ~RewriteObjC() {} |
| 167 | |
| 168 | virtual void HandleTranslationUnit(ASTContext &C); |
| 169 | |
| 170 | void ReplaceStmt(Stmt *Old, Stmt *New) { |
| 171 | Stmt *ReplacingStmt = ReplacedNodes[Old]; |
| 172 | |
| 173 | if (ReplacingStmt) |
| 174 | return; // We can't rewrite the same node twice. |
| 175 | |
| 176 | if (DisableReplaceStmt) |
| 177 | return; // Used when rewriting the assignment of a property setter. |
| 178 | |
| 179 | // If replacement succeeded or warning disabled return with no warning. |
| 180 | if (!Rewrite.ReplaceStmt(Old, New)) { |
| 181 | ReplacedNodes[Old] = New; |
| 182 | return; |
| 183 | } |
| 184 | if (SilenceRewriteMacroWarning) |
| 185 | return; |
| 186 | Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag) |
| 187 | << Old->getSourceRange(); |
| 188 | } |
| 189 | |
| 190 | void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) { |
| 191 | // Measaure the old text. |
| 192 | int Size = Rewrite.getRangeSize(SrcRange); |
| 193 | if (Size == -1) { |
| 194 | Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag) |
| 195 | << Old->getSourceRange(); |
| 196 | return; |
| 197 | } |
| 198 | // Get the new text. |
| 199 | std::string SStr; |
| 200 | llvm::raw_string_ostream S(SStr); |
| 201 | New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts)); |
| 202 | const std::string &Str = S.str(); |
| 203 | |
| 204 | // If replacement succeeded or warning disabled return with no warning. |
| 205 | if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) { |
| 206 | ReplacedNodes[Old] = New; |
| 207 | return; |
| 208 | } |
| 209 | if (SilenceRewriteMacroWarning) |
| 210 | return; |
| 211 | Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag) |
| 212 | << Old->getSourceRange(); |
| 213 | } |
| 214 | |
| 215 | void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen, |
| 216 | bool InsertAfter = true) { |
| 217 | // If insertion succeeded or warning disabled return with no warning. |
| 218 | if (!Rewrite.InsertText(Loc, llvm::StringRef(StrData, StrLen), |
| 219 | InsertAfter) || |
| 220 | SilenceRewriteMacroWarning) |
| 221 | return; |
| 222 | |
| 223 | Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag); |
| 224 | } |
| 225 | |
| 226 | void RemoveText(SourceLocation Loc, unsigned StrLen) { |
| 227 | // If removal succeeded or warning disabled return with no warning. |
| 228 | if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning) |
| 229 | return; |
| 230 | |
| 231 | Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag); |
| 232 | } |
| 233 | |
| 234 | void ReplaceText(SourceLocation Start, unsigned OrigLength, |
| 235 | const char *NewStr, unsigned NewLength) { |
| 236 | // If removal succeeded or warning disabled return with no warning. |
| 237 | if (!Rewrite.ReplaceText(Start, OrigLength, |
| 238 | llvm::StringRef(NewStr, NewLength)) || |
| 239 | SilenceRewriteMacroWarning) |
| 240 | return; |
| 241 | |
| 242 | Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag); |
| 243 | } |
| 244 | |
| 245 | // Syntactic Rewriting. |
| 246 | void RewritePrologue(SourceLocation Loc); |
| 247 | void RewriteInclude(); |
| 248 | void RewriteTabs(); |
| 249 | void RewriteForwardClassDecl(ObjCClassDecl *Dcl); |
| 250 | void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, |
| 251 | ObjCImplementationDecl *IMD, |
| 252 | ObjCCategoryImplDecl *CID); |
| 253 | void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl); |
| 254 | void RewriteImplementationDecl(Decl *Dcl); |
| 255 | void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr); |
| 256 | void RewriteByRefString(std::string &ResultStr, const std::string &Name, |
| 257 | ValueDecl *VD); |
| 258 | void RewriteCategoryDecl(ObjCCategoryDecl *Dcl); |
| 259 | void RewriteProtocolDecl(ObjCProtocolDecl *Dcl); |
| 260 | void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl); |
| 261 | void RewriteMethodDeclaration(ObjCMethodDecl *Method); |
| 262 | void RewriteProperty(ObjCPropertyDecl *prop); |
| 263 | void RewriteFunctionDecl(FunctionDecl *FD); |
| 264 | void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD); |
| 265 | void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl); |
| 266 | void RewriteObjCQualifiedInterfaceTypes(Expr *E); |
| 267 | bool needToScanForQualifiers(QualType T); |
| 268 | ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr); |
| 269 | QualType getSuperStructType(); |
| 270 | QualType getConstantStringStructType(); |
| 271 | bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf); |
| 272 | |
| 273 | // Expression Rewriting. |
| 274 | Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S); |
| 275 | void CollectPropertySetters(Stmt *S); |
| 276 | |
| 277 | Stmt *CurrentBody; |
| 278 | ParentMap *PropParentMap; // created lazily. |
| 279 | |
| 280 | Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp); |
| 281 | Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart, |
| 282 | bool &replaced); |
| 283 | Stmt *RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced); |
| 284 | Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr); |
| 285 | Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt, |
| 286 | SourceRange SrcRange); |
| 287 | Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp); |
| 288 | Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp); |
| 289 | Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp); |
| 290 | Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp); |
| 291 | void WarnAboutReturnGotoStmts(Stmt *S); |
| 292 | void HasReturnStmts(Stmt *S, bool &hasReturns); |
| 293 | void RewriteTryReturnStmts(Stmt *S); |
| 294 | void RewriteSyncReturnStmts(Stmt *S, std::string buf); |
| 295 | Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S); |
| 296 | Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S); |
| 297 | Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S); |
| 298 | Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S); |
| 299 | Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S); |
| 300 | Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S, |
| 301 | SourceLocation OrigEnd); |
| 302 | CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD, |
| 303 | Expr **args, unsigned nargs); |
| 304 | Stmt *SynthMessageExpr(ObjCMessageExpr *Exp); |
| 305 | Stmt *RewriteBreakStmt(BreakStmt *S); |
| 306 | Stmt *RewriteContinueStmt(ContinueStmt *S); |
| 307 | void SynthCountByEnumWithState(std::string &buf); |
| 308 | |
| 309 | void SynthMsgSendFunctionDecl(); |
| 310 | void SynthMsgSendSuperFunctionDecl(); |
| 311 | void SynthMsgSendStretFunctionDecl(); |
| 312 | void SynthMsgSendFpretFunctionDecl(); |
| 313 | void SynthMsgSendSuperStretFunctionDecl(); |
| 314 | void SynthGetClassFunctionDecl(); |
| 315 | void SynthGetMetaClassFunctionDecl(); |
| 316 | void SynthSelGetUidFunctionDecl(); |
| 317 | void SynthSuperContructorFunctionDecl(); |
| 318 | |
| 319 | // Metadata emission. |
| 320 | void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl, |
| 321 | std::string &Result); |
| 322 | |
| 323 | void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl, |
| 324 | std::string &Result); |
| 325 | |
| 326 | template<typename MethodIterator> |
| 327 | void RewriteObjCMethodsMetaData(MethodIterator MethodBegin, |
| 328 | MethodIterator MethodEnd, |
| 329 | bool IsInstanceMethod, |
| 330 | const char *prefix, |
| 331 | const char *ClassName, |
| 332 | std::string &Result); |
| 333 | |
| 334 | void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol, |
| 335 | const char *prefix, |
| 336 | const char *ClassName, |
| 337 | std::string &Result); |
| 338 | void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots, |
| 339 | const char *prefix, |
| 340 | const char *ClassName, |
| 341 | std::string &Result); |
| 342 | void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl, |
| 343 | std::string &Result); |
| 344 | void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl, |
| 345 | ObjCIvarDecl *ivar, |
| 346 | std::string &Result); |
| 347 | void RewriteImplementations(); |
| 348 | void SynthesizeMetaDataIntoBuffer(std::string &Result); |
| 349 | |
| 350 | // Block rewriting. |
| 351 | void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D); |
| 352 | void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND); |
| 353 | |
| 354 | void InsertBlockLiteralsWithinFunction(FunctionDecl *FD); |
| 355 | void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD); |
| 356 | |
| 357 | // Block specific rewrite rules. |
| 358 | void RewriteBlockCall(CallExpr *Exp); |
| 359 | void RewriteBlockPointerDecl(NamedDecl *VD); |
| 360 | void RewriteByRefVar(VarDecl *VD); |
| 361 | std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag); |
| 362 | Stmt *RewriteBlockDeclRefExpr(Expr *VD); |
| 363 | void RewriteBlockPointerFunctionArgs(FunctionDecl *FD); |
| 364 | |
| 365 | std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i, |
| 366 | const char *funcName, std::string Tag); |
| 367 | std::string SynthesizeBlockFunc(BlockExpr *CE, int i, |
| 368 | const char *funcName, std::string Tag); |
| 369 | std::string SynthesizeBlockImpl(BlockExpr *CE, |
| 370 | std::string Tag, std::string Desc); |
| 371 | std::string SynthesizeBlockDescriptor(std::string DescTag, |
| 372 | std::string ImplTag, |
| 373 | int i, const char *funcName, |
| 374 | unsigned hasCopy); |
| 375 | Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp); |
| 376 | void SynthesizeBlockLiterals(SourceLocation FunLocStart, |
| 377 | const char *FunName); |
| 378 | void RewriteRecordBody(RecordDecl *RD); |
| 379 | |
| 380 | void CollectBlockDeclRefInfo(BlockExpr *Exp); |
| 381 | void GetBlockCallExprs(Stmt *S); |
| 382 | void GetBlockDeclRefExprs(Stmt *S); |
| 383 | |
| 384 | // We avoid calling Type::isBlockPointerType(), since it operates on the |
| 385 | // canonical type. We only care if the top-level type is a closure pointer. |
| 386 | bool isTopLevelBlockPointerType(QualType T) { |
| 387 | return isa<BlockPointerType>(T); |
| 388 | } |
| 389 | |
| 390 | // FIXME: This predicate seems like it would be useful to add to ASTContext. |
| 391 | bool isObjCType(QualType T) { |
| 392 | if (!LangOpts.ObjC1 && !LangOpts.ObjC2) |
| 393 | return false; |
| 394 | |
| 395 | QualType OCT = Context->getCanonicalType(T).getUnqualifiedType(); |
| 396 | |
| 397 | if (OCT == Context->getCanonicalType(Context->getObjCIdType()) || |
| 398 | OCT == Context->getCanonicalType(Context->getObjCClassType())) |
| 399 | return true; |
| 400 | |
| 401 | if (const PointerType *PT = OCT->getAs<PointerType>()) { |
| 402 | if (isa<ObjCInterfaceType>(PT->getPointeeType()) || |
| 403 | PT->getPointeeType()->isObjCQualifiedIdType()) |
| 404 | return true; |
| 405 | } |
| 406 | return false; |
| 407 | } |
| 408 | bool PointerTypeTakesAnyBlockArguments(QualType QT); |
| 409 | void GetExtentOfArgList(const char *Name, const char *&LParen, |
| 410 | const char *&RParen); |
| 411 | void RewriteCastExpr(CStyleCastExpr *CE); |
| 412 | |
| 413 | FunctionDecl *SynthBlockInitFunctionDecl(const char *name); |
| 414 | Stmt *SynthBlockInitExpr(BlockExpr *Exp); |
| 415 | |
| 416 | void QuoteDoublequotes(std::string &From, std::string &To) { |
| 417 | for (unsigned i = 0; i < From.length(); i++) { |
| 418 | if (From[i] == '"') |
| 419 | To += "\\\""; |
| 420 | else |
| 421 | To += From[i]; |
| 422 | } |
| 423 | } |
| 424 | }; |
| 425 | |
| 426 | // Helper function: create a CStyleCastExpr with trivial type source info. |
| 427 | CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty, |
| 428 | CastExpr::CastKind Kind, Expr *E) { |
| 429 | TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation()); |
| 430 | return new (Ctx) CStyleCastExpr(Ty, Kind, E, TInfo, |
| 431 | SourceLocation(), SourceLocation()); |
| 432 | } |
| 433 | } |
| 434 | |
| 435 | void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType, |
| 436 | NamedDecl *D) { |
| 437 | if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) { |
| 438 | for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(), |
| 439 | E = fproto->arg_type_end(); I && (I != E); ++I) |
| 440 | if (isTopLevelBlockPointerType(*I)) { |
| 441 | // All the args are checked/rewritten. Don't call twice! |
| 442 | RewriteBlockPointerDecl(D); |
| 443 | break; |
| 444 | } |
| 445 | } |
| 446 | } |
| 447 | |
| 448 | void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) { |
| 449 | const PointerType *PT = funcType->getAs<PointerType>(); |
| 450 | if (PT && PointerTypeTakesAnyBlockArguments(funcType)) |
| 451 | RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND); |
| 452 | } |
| 453 | |
| 454 | static bool IsHeaderFile(const std::string &Filename) { |
| 455 | std::string::size_type DotPos = Filename.rfind('.'); |
| 456 | |
| 457 | if (DotPos == std::string::npos) { |
| 458 | // no file extension |
| 459 | return false; |
| 460 | } |
| 461 | |
| 462 | std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end()); |
| 463 | // C header: .h |
| 464 | // C++ header: .hh or .H; |
| 465 | return Ext == "h" || Ext == "hh" || Ext == "H"; |
| 466 | } |
| 467 | |
| 468 | RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS, |
| 469 | Diagnostic &D, const LangOptions &LOpts, |
| 470 | bool silenceMacroWarn) |
| 471 | : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS), |
| 472 | SilenceRewriteMacroWarning(silenceMacroWarn) { |
| 473 | IsHeader = IsHeaderFile(inFile); |
| 474 | RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning, |
| 475 | "rewriting sub-expression within a macro (may not be correct)"); |
| 476 | TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning, |
| 477 | "rewriter doesn't support user-specified control flow semantics " |
| 478 | "for @try/@finally (code may not execute properly)"); |
| 479 | } |
| 480 | |
| 481 | ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile, |
| 482 | llvm::raw_ostream* OS, |
| 483 | Diagnostic &Diags, |
| 484 | const LangOptions &LOpts, |
| 485 | bool SilenceRewriteMacroWarning) { |
| 486 | return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning); |
| 487 | } |
| 488 | |
| 489 | void RewriteObjC::Initialize(ASTContext &context) { |
| 490 | Context = &context; |
| 491 | SM = &Context->getSourceManager(); |
| 492 | TUDecl = Context->getTranslationUnitDecl(); |
| 493 | MsgSendFunctionDecl = 0; |
| 494 | MsgSendSuperFunctionDecl = 0; |
| 495 | MsgSendStretFunctionDecl = 0; |
| 496 | MsgSendSuperStretFunctionDecl = 0; |
| 497 | MsgSendFpretFunctionDecl = 0; |
| 498 | GetClassFunctionDecl = 0; |
| 499 | GetMetaClassFunctionDecl = 0; |
| 500 | SelGetUidFunctionDecl = 0; |
| 501 | CFStringFunctionDecl = 0; |
| 502 | ConstantStringClassReference = 0; |
| 503 | NSStringRecord = 0; |
| 504 | CurMethodDef = 0; |
| 505 | CurFunctionDef = 0; |
| 506 | CurFunctionDeclToDeclareForBlock = 0; |
| 507 | GlobalVarDecl = 0; |
| 508 | SuperStructDecl = 0; |
| 509 | ProtocolTypeDecl = 0; |
| 510 | ConstantStringDecl = 0; |
| 511 | BcLabelCount = 0; |
| 512 | SuperContructorFunctionDecl = 0; |
| 513 | NumObjCStringLiterals = 0; |
| 514 | PropParentMap = 0; |
| 515 | CurrentBody = 0; |
| 516 | DisableReplaceStmt = false; |
| 517 | objc_impl_method = false; |
| 518 | |
| 519 | // Get the ID and start/end of the main file. |
| 520 | MainFileID = SM->getMainFileID(); |
| 521 | const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID); |
| 522 | MainFileStart = MainBuf->getBufferStart(); |
| 523 | MainFileEnd = MainBuf->getBufferEnd(); |
| 524 | |
| 525 | Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions()); |
| 526 | |
| 527 | // declaring objc_selector outside the parameter list removes a silly |
| 528 | // scope related warning... |
| 529 | if (IsHeader) |
| 530 | Preamble = "#pragma once\n"; |
| 531 | Preamble += "struct objc_selector; struct objc_class;\n"; |
| 532 | Preamble += "struct __rw_objc_super { struct objc_object *object; "; |
| 533 | Preamble += "struct objc_object *superClass; "; |
| 534 | if (LangOpts.Microsoft) { |
| 535 | // Add a constructor for creating temporary objects. |
| 536 | Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) " |
| 537 | ": "; |
| 538 | Preamble += "object(o), superClass(s) {} "; |
| 539 | } |
| 540 | Preamble += "};\n"; |
| 541 | Preamble += "#ifndef _REWRITER_typedef_Protocol\n"; |
| 542 | Preamble += "typedef struct objc_object Protocol;\n"; |
| 543 | Preamble += "#define _REWRITER_typedef_Protocol\n"; |
| 544 | Preamble += "#endif\n"; |
| 545 | if (LangOpts.Microsoft) { |
| 546 | Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n"; |
| 547 | Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n"; |
| 548 | } else |
| 549 | Preamble += "#define __OBJC_RW_DLLIMPORT extern\n"; |
| 550 | Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend"; |
| 551 | Preamble += "(struct objc_object *, struct objc_selector *, ...);\n"; |
| 552 | Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper"; |
| 553 | Preamble += "(struct objc_super *, struct objc_selector *, ...);\n"; |
| 554 | Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret"; |
| 555 | Preamble += "(struct objc_object *, struct objc_selector *, ...);\n"; |
| 556 | Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret"; |
| 557 | Preamble += "(struct objc_super *, struct objc_selector *, ...);\n"; |
| 558 | Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret"; |
| 559 | Preamble += "(struct objc_object *, struct objc_selector *, ...);\n"; |
| 560 | Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass"; |
| 561 | Preamble += "(const char *);\n"; |
| 562 | Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass"; |
| 563 | Preamble += "(const char *);\n"; |
| 564 | Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n"; |
| 565 | Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n"; |
| 566 | Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n"; |
| 567 | Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n"; |
| 568 | Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match"; |
| 569 | Preamble += "(struct objc_class *, struct objc_object *);\n"; |
| 570 | // @synchronized hooks. |
| 571 | Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n"; |
| 572 | Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n"; |
| 573 | Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n"; |
| 574 | Preamble += "#ifndef __FASTENUMERATIONSTATE\n"; |
| 575 | Preamble += "struct __objcFastEnumerationState {\n\t"; |
| 576 | Preamble += "unsigned long state;\n\t"; |
| 577 | Preamble += "void **itemsPtr;\n\t"; |
| 578 | Preamble += "unsigned long *mutationsPtr;\n\t"; |
| 579 | Preamble += "unsigned long extra[5];\n};\n"; |
| 580 | Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n"; |
| 581 | Preamble += "#define __FASTENUMERATIONSTATE\n"; |
| 582 | Preamble += "#endif\n"; |
| 583 | Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n"; |
| 584 | Preamble += "struct __NSConstantStringImpl {\n"; |
| 585 | Preamble += " int *isa;\n"; |
| 586 | Preamble += " int flags;\n"; |
| 587 | Preamble += " char *str;\n"; |
| 588 | Preamble += " long length;\n"; |
| 589 | Preamble += "};\n"; |
| 590 | Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n"; |
| 591 | Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n"; |
| 592 | Preamble += "#else\n"; |
| 593 | Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n"; |
| 594 | Preamble += "#endif\n"; |
| 595 | Preamble += "#define __NSCONSTANTSTRINGIMPL\n"; |
| 596 | Preamble += "#endif\n"; |
| 597 | // Blocks preamble. |
| 598 | Preamble += "#ifndef BLOCK_IMPL\n"; |
| 599 | Preamble += "#define BLOCK_IMPL\n"; |
| 600 | Preamble += "struct __block_impl {\n"; |
| 601 | Preamble += " void *isa;\n"; |
| 602 | Preamble += " int Flags;\n"; |
| 603 | Preamble += " int Reserved;\n"; |
| 604 | Preamble += " void *FuncPtr;\n"; |
| 605 | Preamble += "};\n"; |
| 606 | Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n"; |
| 607 | Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n"; |
| 608 | Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_assign(void *, const void *, const int);\n"; |
| 609 | Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n"; |
| 610 | Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n"; |
| 611 | Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n"; |
| 612 | Preamble += "#else\n"; |
| 613 | Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n"; |
| 614 | Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n"; |
| 615 | Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n"; |
| 616 | Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n"; |
| 617 | Preamble += "#endif\n"; |
| 618 | Preamble += "#endif\n"; |
| 619 | if (LangOpts.Microsoft) { |
| 620 | Preamble += "#undef __OBJC_RW_DLLIMPORT\n"; |
| 621 | Preamble += "#undef __OBJC_RW_STATICIMPORT\n"; |
| 622 | Preamble += "#define __attribute__(X)\n"; |
| 623 | Preamble += "#define __weak\n"; |
| 624 | } |
| 625 | else { |
| 626 | Preamble += "#define __block\n"; |
| 627 | Preamble += "#define __weak\n"; |
| 628 | } |
| 629 | } |
| 630 | |
| 631 | |
| 632 | //===----------------------------------------------------------------------===// |
| 633 | // Top Level Driver Code |
| 634 | //===----------------------------------------------------------------------===// |
| 635 | |
| 636 | void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) { |
| 637 | if (Diags.hasErrorOccurred()) |
| 638 | return; |
| 639 | |
| 640 | // Two cases: either the decl could be in the main file, or it could be in a |
| 641 | // #included file. If the former, rewrite it now. If the later, check to see |
| 642 | // if we rewrote the #include/#import. |
| 643 | SourceLocation Loc = D->getLocation(); |
| 644 | Loc = SM->getInstantiationLoc(Loc); |
| 645 | |
| 646 | // If this is for a builtin, ignore it. |
| 647 | if (Loc.isInvalid()) return; |
| 648 | |
| 649 | // Look for built-in declarations that we need to refer during the rewrite. |
| 650 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { |
| 651 | RewriteFunctionDecl(FD); |
| 652 | } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) { |
| 653 | // declared in <Foundation/NSString.h> |
| 654 | if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) { |
| 655 | ConstantStringClassReference = FVD; |
| 656 | return; |
| 657 | } |
| 658 | } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) { |
| 659 | RewriteInterfaceDecl(MD); |
| 660 | } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) { |
| 661 | RewriteCategoryDecl(CD); |
| 662 | } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) { |
| 663 | RewriteProtocolDecl(PD); |
| 664 | } else if (ObjCForwardProtocolDecl *FP = |
| 665 | dyn_cast<ObjCForwardProtocolDecl>(D)){ |
| 666 | RewriteForwardProtocolDecl(FP); |
| 667 | } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) { |
| 668 | // Recurse into linkage specifications |
| 669 | for (DeclContext::decl_iterator DI = LSD->decls_begin(), |
| 670 | DIEnd = LSD->decls_end(); |
| 671 | DI != DIEnd; ++DI) |
| 672 | HandleTopLevelSingleDecl(*DI); |
| 673 | } |
| 674 | // If we have a decl in the main file, see if we should rewrite it. |
| 675 | if (SM->isFromMainFile(Loc)) |
| 676 | return HandleDeclInMainFile(D); |
| 677 | } |
| 678 | |
| 679 | //===----------------------------------------------------------------------===// |
| 680 | // Syntactic (non-AST) Rewriting Code |
| 681 | //===----------------------------------------------------------------------===// |
| 682 | |
| 683 | void RewriteObjC::RewriteInclude() { |
| 684 | SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID); |
| 685 | std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID); |
| 686 | const char *MainBufStart = MainBuf.first; |
| 687 | const char *MainBufEnd = MainBuf.second; |
| 688 | size_t ImportLen = strlen("import"); |
| 689 | size_t IncludeLen = strlen("include"); |
| 690 | |
| 691 | // Loop over the whole file, looking for includes. |
| 692 | for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) { |
| 693 | if (*BufPtr == '#') { |
| 694 | if (++BufPtr == MainBufEnd) |
| 695 | return; |
| 696 | while (*BufPtr == ' ' || *BufPtr == '\t') |
| 697 | if (++BufPtr == MainBufEnd) |
| 698 | return; |
| 699 | if (!strncmp(BufPtr, "import", ImportLen)) { |
| 700 | // replace import with include |
| 701 | SourceLocation ImportLoc = |
| 702 | LocStart.getFileLocWithOffset(BufPtr-MainBufStart); |
| 703 | ReplaceText(ImportLoc, ImportLen, "include", IncludeLen); |
| 704 | BufPtr += ImportLen; |
| 705 | } |
| 706 | } |
| 707 | } |
| 708 | } |
| 709 | |
| 710 | void RewriteObjC::RewriteTabs() { |
| 711 | std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID); |
| 712 | const char *MainBufStart = MainBuf.first; |
| 713 | const char *MainBufEnd = MainBuf.second; |
| 714 | |
| 715 | // Loop over the whole file, looking for tabs. |
| 716 | for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) { |
| 717 | if (*BufPtr != '\t') |
| 718 | continue; |
| 719 | |
| 720 | // Okay, we found a tab. This tab will turn into at least one character, |
| 721 | // but it depends on which 'virtual column' it is in. Compute that now. |
| 722 | unsigned VCol = 0; |
| 723 | while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' && |
| 724 | BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r') |
| 725 | ++VCol; |
| 726 | |
| 727 | // Okay, now that we know the virtual column, we know how many spaces to |
| 728 | // insert. We assume 8-character tab-stops. |
| 729 | unsigned Spaces = 8-(VCol & 7); |
| 730 | |
| 731 | // Get the location of the tab. |
| 732 | SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID); |
| 733 | TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart); |
| 734 | |
| 735 | // Rewrite the single tab character into a sequence of spaces. |
| 736 | ReplaceText(TabLoc, 1, " ", Spaces); |
| 737 | } |
| 738 | } |
| 739 | |
| 740 | static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl, |
| 741 | ObjCIvarDecl *OID) { |
| 742 | std::string S; |
| 743 | S = "((struct "; |
| 744 | S += ClassDecl->getIdentifier()->getName(); |
| 745 | S += "_IMPL *)self)->"; |
| 746 | S += OID->getName(); |
| 747 | return S; |
| 748 | } |
| 749 | |
| 750 | void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, |
| 751 | ObjCImplementationDecl *IMD, |
| 752 | ObjCCategoryImplDecl *CID) { |
| 753 | SourceLocation startLoc = PID->getLocStart(); |
| 754 | InsertText(startLoc, "// ", 3); |
| 755 | const char *startBuf = SM->getCharacterData(startLoc); |
| 756 | assert((*startBuf == '@') && "bogus @synthesize location"); |
| 757 | const char *semiBuf = strchr(startBuf, ';'); |
| 758 | assert((*semiBuf == ';') && "@synthesize: can't find ';'"); |
| 759 | SourceLocation onePastSemiLoc = |
| 760 | startLoc.getFileLocWithOffset(semiBuf-startBuf+1); |
| 761 | |
| 762 | if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic) |
| 763 | return; // FIXME: is this correct? |
| 764 | |
| 765 | // Generate the 'getter' function. |
| 766 | ObjCPropertyDecl *PD = PID->getPropertyDecl(); |
| 767 | ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface(); |
| 768 | ObjCIvarDecl *OID = PID->getPropertyIvarDecl(); |
| 769 | |
| 770 | if (!OID) |
| 771 | return; |
| 772 | |
| 773 | std::string Getr; |
| 774 | RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr); |
| 775 | Getr += "{ "; |
| 776 | // Synthesize an explicit cast to gain access to the ivar. |
| 777 | // FIXME: deal with code generation implications for various property |
| 778 | // attributes (copy, retain, nonatomic). |
| 779 | // See objc-act.c:objc_synthesize_new_getter() for details. |
| 780 | Getr += "return " + getIvarAccessString(ClassDecl, OID); |
| 781 | Getr += "; }"; |
| 782 | InsertText(onePastSemiLoc, Getr.c_str(), Getr.size()); |
| 783 | if (PD->isReadOnly()) |
| 784 | return; |
| 785 | |
| 786 | // Generate the 'setter' function. |
| 787 | std::string Setr; |
| 788 | RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr); |
| 789 | Setr += "{ "; |
| 790 | // Synthesize an explicit cast to initialize the ivar. |
| 791 | // FIXME: deal with code generation implications for various property |
| 792 | // attributes (copy, retain, nonatomic). |
| 793 | // See objc-act.c:objc_synthesize_new_setter() for details. |
| 794 | Setr += getIvarAccessString(ClassDecl, OID) + " = "; |
| 795 | Setr += PD->getNameAsCString(); |
| 796 | Setr += "; }"; |
| 797 | InsertText(onePastSemiLoc, Setr.c_str(), Setr.size()); |
| 798 | } |
| 799 | |
| 800 | void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) { |
| 801 | // Get the start location and compute the semi location. |
| 802 | SourceLocation startLoc = ClassDecl->getLocation(); |
| 803 | const char *startBuf = SM->getCharacterData(startLoc); |
| 804 | const char *semiPtr = strchr(startBuf, ';'); |
| 805 | |
| 806 | // Translate to typedef's that forward reference structs with the same name |
| 807 | // as the class. As a convenience, we include the original declaration |
| 808 | // as a comment. |
| 809 | std::string typedefString; |
| 810 | typedefString += "// @class "; |
| 811 | for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end(); |
| 812 | I != E; ++I) { |
| 813 | ObjCInterfaceDecl *ForwardDecl = I->getInterface(); |
| 814 | typedefString += ForwardDecl->getNameAsString(); |
| 815 | if (I+1 != E) |
| 816 | typedefString += ", "; |
| 817 | else |
| 818 | typedefString += ";\n"; |
| 819 | } |
| 820 | |
| 821 | for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end(); |
| 822 | I != E; ++I) { |
| 823 | ObjCInterfaceDecl *ForwardDecl = I->getInterface(); |
| 824 | typedefString += "#ifndef _REWRITER_typedef_"; |
| 825 | typedefString += ForwardDecl->getNameAsString(); |
| 826 | typedefString += "\n"; |
| 827 | typedefString += "#define _REWRITER_typedef_"; |
| 828 | typedefString += ForwardDecl->getNameAsString(); |
| 829 | typedefString += "\n"; |
| 830 | typedefString += "typedef struct objc_object "; |
| 831 | typedefString += ForwardDecl->getNameAsString(); |
| 832 | typedefString += ";\n#endif\n"; |
| 833 | } |
| 834 | |
| 835 | // Replace the @class with typedefs corresponding to the classes. |
| 836 | ReplaceText(startLoc, semiPtr-startBuf+1, |
| 837 | typedefString.c_str(), typedefString.size()); |
| 838 | } |
| 839 | |
| 840 | void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) { |
| 841 | // When method is a synthesized one, such as a getter/setter there is |
| 842 | // nothing to rewrite. |
| 843 | if (Method->isSynthesized()) |
| 844 | return; |
| 845 | SourceLocation LocStart = Method->getLocStart(); |
| 846 | SourceLocation LocEnd = Method->getLocEnd(); |
| 847 | |
| 848 | if (SM->getInstantiationLineNumber(LocEnd) > |
| 849 | SM->getInstantiationLineNumber(LocStart)) { |
| 850 | InsertText(LocStart, "#if 0\n", 6); |
| 851 | ReplaceText(LocEnd, 1, ";\n#endif\n", 9); |
| 852 | } else { |
| 853 | InsertText(LocStart, "// ", 3); |
| 854 | } |
| 855 | } |
| 856 | |
| 857 | void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) { |
| 858 | SourceLocation Loc = prop->getAtLoc(); |
| 859 | |
| 860 | ReplaceText(Loc, 0, "// ", 3); |
| 861 | // FIXME: handle properties that are declared across multiple lines. |
| 862 | } |
| 863 | |
| 864 | void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) { |
| 865 | SourceLocation LocStart = CatDecl->getLocStart(); |
| 866 | |
| 867 | // FIXME: handle category headers that are declared across multiple lines. |
| 868 | ReplaceText(LocStart, 0, "// ", 3); |
| 869 | |
| 870 | for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(), |
| 871 | E = CatDecl->prop_end(); I != E; ++I) |
| 872 | RewriteProperty(*I); |
| 873 | |
| 874 | for (ObjCCategoryDecl::instmeth_iterator |
| 875 | I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end(); |
| 876 | I != E; ++I) |
| 877 | RewriteMethodDeclaration(*I); |
| 878 | for (ObjCCategoryDecl::classmeth_iterator |
| 879 | I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end(); |
| 880 | I != E; ++I) |
| 881 | RewriteMethodDeclaration(*I); |
| 882 | |
| 883 | // Lastly, comment out the @end. |
| 884 | ReplaceText(CatDecl->getAtEndRange().getBegin(), 0, "// ", 3); |
| 885 | } |
| 886 | |
| 887 | void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) { |
| 888 | std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID); |
| 889 | |
| 890 | SourceLocation LocStart = PDecl->getLocStart(); |
| 891 | |
| 892 | // FIXME: handle protocol headers that are declared across multiple lines. |
| 893 | ReplaceText(LocStart, 0, "// ", 3); |
| 894 | |
| 895 | for (ObjCProtocolDecl::instmeth_iterator |
| 896 | I = PDecl->instmeth_begin(), E = PDecl->instmeth_end(); |
| 897 | I != E; ++I) |
| 898 | RewriteMethodDeclaration(*I); |
| 899 | for (ObjCProtocolDecl::classmeth_iterator |
| 900 | I = PDecl->classmeth_begin(), E = PDecl->classmeth_end(); |
| 901 | I != E; ++I) |
| 902 | RewriteMethodDeclaration(*I); |
| 903 | |
| 904 | // Lastly, comment out the @end. |
| 905 | SourceLocation LocEnd = PDecl->getAtEndRange().getBegin(); |
| 906 | ReplaceText(LocEnd, 0, "// ", 3); |
| 907 | |
| 908 | // Must comment out @optional/@required |
| 909 | const char *startBuf = SM->getCharacterData(LocStart); |
| 910 | const char *endBuf = SM->getCharacterData(LocEnd); |
| 911 | for (const char *p = startBuf; p < endBuf; p++) { |
| 912 | if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) { |
| 913 | std::string CommentedOptional = "/* @optional */"; |
| 914 | SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf); |
| 915 | ReplaceText(OptionalLoc, strlen("@optional"), |
| 916 | CommentedOptional.c_str(), CommentedOptional.size()); |
| 917 | |
| 918 | } |
| 919 | else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) { |
| 920 | std::string CommentedRequired = "/* @required */"; |
| 921 | SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf); |
| 922 | ReplaceText(OptionalLoc, strlen("@required"), |
| 923 | CommentedRequired.c_str(), CommentedRequired.size()); |
| 924 | |
| 925 | } |
| 926 | } |
| 927 | } |
| 928 | |
| 929 | void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) { |
| 930 | SourceLocation LocStart = PDecl->getLocation(); |
| 931 | if (LocStart.isInvalid()) |
| 932 | assert(false && "Invalid SourceLocation"); |
| 933 | // FIXME: handle forward protocol that are declared across multiple lines. |
| 934 | ReplaceText(LocStart, 0, "// ", 3); |
| 935 | } |
| 936 | |
| 937 | void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD, |
| 938 | std::string &ResultStr) { |
| 939 | //fprintf(stderr,"In RewriteObjCMethodDecl\n"); |
| 940 | const FunctionType *FPRetType = 0; |
| 941 | ResultStr += "\nstatic "; |
| 942 | if (OMD->getResultType()->isObjCQualifiedIdType()) |
| 943 | ResultStr += "id"; |
| 944 | else if (OMD->getResultType()->isFunctionPointerType() || |
| 945 | OMD->getResultType()->isBlockPointerType()) { |
| 946 | // needs special handling, since pointer-to-functions have special |
| 947 | // syntax (where a decaration models use). |
| 948 | QualType retType = OMD->getResultType(); |
| 949 | QualType PointeeTy; |
| 950 | if (const PointerType* PT = retType->getAs<PointerType>()) |
| 951 | PointeeTy = PT->getPointeeType(); |
| 952 | else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>()) |
| 953 | PointeeTy = BPT->getPointeeType(); |
| 954 | if ((FPRetType = PointeeTy->getAs<FunctionType>())) { |
| 955 | ResultStr += FPRetType->getResultType().getAsString(); |
| 956 | ResultStr += "(*"; |
| 957 | } |
| 958 | } else |
| 959 | ResultStr += OMD->getResultType().getAsString(); |
| 960 | ResultStr += " "; |
| 961 | |
| 962 | // Unique method name |
| 963 | std::string NameStr; |
| 964 | |
| 965 | if (OMD->isInstanceMethod()) |
| 966 | NameStr += "_I_"; |
| 967 | else |
| 968 | NameStr += "_C_"; |
| 969 | |
| 970 | NameStr += OMD->getClassInterface()->getNameAsString(); |
| 971 | NameStr += "_"; |
| 972 | |
| 973 | if (ObjCCategoryImplDecl *CID = |
| 974 | dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) { |
| 975 | NameStr += CID->getNameAsString(); |
| 976 | NameStr += "_"; |
| 977 | } |
| 978 | // Append selector names, replacing ':' with '_' |
| 979 | { |
| 980 | std::string selString = OMD->getSelector().getAsString(); |
| 981 | int len = selString.size(); |
| 982 | for (int i = 0; i < len; i++) |
| 983 | if (selString[i] == ':') |
| 984 | selString[i] = '_'; |
| 985 | NameStr += selString; |
| 986 | } |
| 987 | // Remember this name for metadata emission |
| 988 | MethodInternalNames[OMD] = NameStr; |
| 989 | ResultStr += NameStr; |
| 990 | |
| 991 | // Rewrite arguments |
| 992 | ResultStr += "("; |
| 993 | |
| 994 | // invisible arguments |
| 995 | if (OMD->isInstanceMethod()) { |
| 996 | QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface()); |
| 997 | selfTy = Context->getPointerType(selfTy); |
| 998 | if (!LangOpts.Microsoft) { |
| 999 | if (ObjCSynthesizedStructs.count(OMD->getClassInterface())) |
| 1000 | ResultStr += "struct "; |
| 1001 | } |
| 1002 | // When rewriting for Microsoft, explicitly omit the structure name. |
| 1003 | ResultStr += OMD->getClassInterface()->getNameAsString(); |
| 1004 | ResultStr += " *"; |
| 1005 | } |
| 1006 | else |
| 1007 | ResultStr += Context->getObjCClassType().getAsString(); |
| 1008 | |
| 1009 | ResultStr += " self, "; |
| 1010 | ResultStr += Context->getObjCSelType().getAsString(); |
| 1011 | ResultStr += " _cmd"; |
| 1012 | |
| 1013 | // Method arguments. |
| 1014 | for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(), |
| 1015 | E = OMD->param_end(); PI != E; ++PI) { |
| 1016 | ParmVarDecl *PDecl = *PI; |
| 1017 | ResultStr += ", "; |
| 1018 | if (PDecl->getType()->isObjCQualifiedIdType()) { |
| 1019 | ResultStr += "id "; |
| 1020 | ResultStr += PDecl->getNameAsString(); |
| 1021 | } else { |
| 1022 | std::string Name = PDecl->getNameAsString(); |
| 1023 | if (isTopLevelBlockPointerType(PDecl->getType())) { |
| 1024 | // Make sure we convert "t (^)(...)" to "t (*)(...)". |
| 1025 | const BlockPointerType *BPT = PDecl->getType()->getAs<BlockPointerType>(); |
| 1026 | Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name, |
| 1027 | Context->PrintingPolicy); |
| 1028 | } else |
| 1029 | PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy); |
| 1030 | ResultStr += Name; |
| 1031 | } |
| 1032 | } |
| 1033 | if (OMD->isVariadic()) |
| 1034 | ResultStr += ", ..."; |
| 1035 | ResultStr += ") "; |
| 1036 | |
| 1037 | if (FPRetType) { |
| 1038 | ResultStr += ")"; // close the precedence "scope" for "*". |
| 1039 | |
| 1040 | // Now, emit the argument types (if any). |
| 1041 | if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) { |
| 1042 | ResultStr += "("; |
| 1043 | for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) { |
| 1044 | if (i) ResultStr += ", "; |
| 1045 | std::string ParamStr = FT->getArgType(i).getAsString(); |
| 1046 | ResultStr += ParamStr; |
| 1047 | } |
| 1048 | if (FT->isVariadic()) { |
| 1049 | if (FT->getNumArgs()) ResultStr += ", "; |
| 1050 | ResultStr += "..."; |
| 1051 | } |
| 1052 | ResultStr += ")"; |
| 1053 | } else { |
| 1054 | ResultStr += "()"; |
| 1055 | } |
| 1056 | } |
| 1057 | } |
| 1058 | void RewriteObjC::RewriteImplementationDecl(Decl *OID) { |
| 1059 | ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID); |
| 1060 | ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID); |
| 1061 | |
| 1062 | if (IMD) |
| 1063 | InsertText(IMD->getLocStart(), "// ", 3); |
| 1064 | else |
| 1065 | InsertText(CID->getLocStart(), "// ", 3); |
| 1066 | |
| 1067 | for (ObjCCategoryImplDecl::instmeth_iterator |
| 1068 | I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(), |
| 1069 | E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); |
| 1070 | I != E; ++I) { |
| 1071 | std::string ResultStr; |
| 1072 | ObjCMethodDecl *OMD = *I; |
| 1073 | RewriteObjCMethodDecl(OMD, ResultStr); |
| 1074 | SourceLocation LocStart = OMD->getLocStart(); |
| 1075 | SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart(); |
| 1076 | |
| 1077 | const char *startBuf = SM->getCharacterData(LocStart); |
| 1078 | const char *endBuf = SM->getCharacterData(LocEnd); |
| 1079 | ReplaceText(LocStart, endBuf-startBuf, |
| 1080 | ResultStr.c_str(), ResultStr.size()); |
| 1081 | } |
| 1082 | |
| 1083 | for (ObjCCategoryImplDecl::classmeth_iterator |
| 1084 | I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(), |
| 1085 | E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); |
| 1086 | I != E; ++I) { |
| 1087 | std::string ResultStr; |
| 1088 | ObjCMethodDecl *OMD = *I; |
| 1089 | RewriteObjCMethodDecl(OMD, ResultStr); |
| 1090 | SourceLocation LocStart = OMD->getLocStart(); |
| 1091 | SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart(); |
| 1092 | |
| 1093 | const char *startBuf = SM->getCharacterData(LocStart); |
| 1094 | const char *endBuf = SM->getCharacterData(LocEnd); |
| 1095 | ReplaceText(LocStart, endBuf-startBuf, |
| 1096 | ResultStr.c_str(), ResultStr.size()); |
| 1097 | } |
| 1098 | for (ObjCCategoryImplDecl::propimpl_iterator |
| 1099 | I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(), |
| 1100 | E = IMD ? IMD->propimpl_end() : CID->propimpl_end(); |
| 1101 | I != E; ++I) { |
| 1102 | RewritePropertyImplDecl(*I, IMD, CID); |
| 1103 | } |
| 1104 | |
| 1105 | if (IMD) |
| 1106 | InsertText(IMD->getLocEnd(), "// ", 3); |
| 1107 | else |
| 1108 | InsertText(CID->getLocEnd(), "// ", 3); |
| 1109 | } |
| 1110 | |
| 1111 | void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) { |
| 1112 | std::string ResultStr; |
| 1113 | if (!ObjCForwardDecls.count(ClassDecl)) { |
| 1114 | // we haven't seen a forward decl - generate a typedef. |
| 1115 | ResultStr = "#ifndef _REWRITER_typedef_"; |
| 1116 | ResultStr += ClassDecl->getNameAsString(); |
| 1117 | ResultStr += "\n"; |
| 1118 | ResultStr += "#define _REWRITER_typedef_"; |
| 1119 | ResultStr += ClassDecl->getNameAsString(); |
| 1120 | ResultStr += "\n"; |
| 1121 | ResultStr += "typedef struct objc_object "; |
| 1122 | ResultStr += ClassDecl->getNameAsString(); |
| 1123 | ResultStr += ";\n#endif\n"; |
| 1124 | // Mark this typedef as having been generated. |
| 1125 | ObjCForwardDecls.insert(ClassDecl); |
| 1126 | } |
| 1127 | SynthesizeObjCInternalStruct(ClassDecl, ResultStr); |
| 1128 | |
| 1129 | for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(), |
| 1130 | E = ClassDecl->prop_end(); I != E; ++I) |
| 1131 | RewriteProperty(*I); |
| 1132 | for (ObjCInterfaceDecl::instmeth_iterator |
| 1133 | I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end(); |
| 1134 | I != E; ++I) |
| 1135 | RewriteMethodDeclaration(*I); |
| 1136 | for (ObjCInterfaceDecl::classmeth_iterator |
| 1137 | I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end(); |
| 1138 | I != E; ++I) |
| 1139 | RewriteMethodDeclaration(*I); |
| 1140 | |
| 1141 | // Lastly, comment out the @end. |
| 1142 | ReplaceText(ClassDecl->getAtEndRange().getBegin(), 0, "// ", 3); |
| 1143 | } |
| 1144 | |
| 1145 | Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt, |
| 1146 | SourceRange SrcRange) { |
| 1147 | // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr. |
| 1148 | // This allows us to reuse all the fun and games in SynthMessageExpr(). |
| 1149 | ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()); |
| 1150 | ObjCMessageExpr *MsgExpr; |
| 1151 | ObjCPropertyDecl *PDecl = PropRefExpr->getProperty(); |
| 1152 | llvm::SmallVector<Expr *, 1> ExprVec; |
| 1153 | ExprVec.push_back(newStmt); |
| 1154 | |
| 1155 | Stmt *Receiver = PropRefExpr->getBase(); |
| 1156 | ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver); |
| 1157 | if (PRE && PropGetters[PRE]) { |
| 1158 | // This allows us to handle chain/nested property getters. |
| 1159 | Receiver = PropGetters[PRE]; |
| 1160 | } |
| 1161 | MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver), |
| 1162 | PDecl->getSetterName(), PDecl->getType(), |
| 1163 | PDecl->getSetterMethodDecl(), |
| 1164 | SourceLocation(), SourceLocation(), |
| 1165 | &ExprVec[0], 1); |
| 1166 | Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr); |
| 1167 | |
| 1168 | // Now do the actual rewrite. |
| 1169 | ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange); |
| 1170 | //delete BinOp; |
| 1171 | // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references |
| 1172 | // to things that stay around. |
| 1173 | Context->Deallocate(MsgExpr); |
| 1174 | return ReplacingStmt; |
| 1175 | } |
| 1176 | |
| 1177 | Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) { |
| 1178 | // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr. |
| 1179 | // This allows us to reuse all the fun and games in SynthMessageExpr(). |
| 1180 | ObjCMessageExpr *MsgExpr; |
| 1181 | ObjCPropertyDecl *PDecl = PropRefExpr->getProperty(); |
| 1182 | |
| 1183 | Stmt *Receiver = PropRefExpr->getBase(); |
| 1184 | |
| 1185 | ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver); |
| 1186 | if (PRE && PropGetters[PRE]) { |
| 1187 | // This allows us to handle chain/nested property getters. |
| 1188 | Receiver = PropGetters[PRE]; |
| 1189 | } |
| 1190 | MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver), |
| 1191 | PDecl->getGetterName(), PDecl->getType(), |
| 1192 | PDecl->getGetterMethodDecl(), |
| 1193 | SourceLocation(), SourceLocation(), |
| 1194 | 0, 0); |
| 1195 | |
| 1196 | Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr); |
| 1197 | |
| 1198 | if (!PropParentMap) |
| 1199 | PropParentMap = new ParentMap(CurrentBody); |
| 1200 | |
| 1201 | Stmt *Parent = PropParentMap->getParent(PropRefExpr); |
| 1202 | if (Parent && isa<ObjCPropertyRefExpr>(Parent)) { |
| 1203 | // We stash away the ReplacingStmt since actually doing the |
| 1204 | // replacement/rewrite won't work for nested getters (e.g. obj.p.i) |
| 1205 | PropGetters[PropRefExpr] = ReplacingStmt; |
| 1206 | // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references |
| 1207 | // to things that stay around. |
| 1208 | Context->Deallocate(MsgExpr); |
| 1209 | return PropRefExpr; // return the original... |
| 1210 | } else { |
| 1211 | ReplaceStmt(PropRefExpr, ReplacingStmt); |
| 1212 | // delete PropRefExpr; elsewhere... |
| 1213 | // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references |
| 1214 | // to things that stay around. |
| 1215 | Context->Deallocate(MsgExpr); |
| 1216 | return ReplacingStmt; |
| 1217 | } |
| 1218 | } |
| 1219 | |
| 1220 | Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, |
| 1221 | SourceLocation OrigStart, |
| 1222 | bool &replaced) { |
| 1223 | ObjCIvarDecl *D = IV->getDecl(); |
| 1224 | const Expr *BaseExpr = IV->getBase(); |
| 1225 | if (CurMethodDef) { |
| 1226 | if (BaseExpr->getType()->isObjCObjectPointerType()) { |
| 1227 | ObjCInterfaceType *iFaceDecl = |
| 1228 | dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType()); |
| 1229 | assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null"); |
| 1230 | // lookup which class implements the instance variable. |
| 1231 | ObjCInterfaceDecl *clsDeclared = 0; |
| 1232 | iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), |
| 1233 | clsDeclared); |
| 1234 | assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class"); |
| 1235 | |
| 1236 | // Synthesize an explicit cast to gain access to the ivar. |
| 1237 | std::string RecName = clsDeclared->getIdentifier()->getName(); |
| 1238 | RecName += "_IMPL"; |
| 1239 | IdentifierInfo *II = &Context->Idents.get(RecName.c_str()); |
| 1240 | RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl, |
| 1241 | SourceLocation(), II); |
| 1242 | assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl"); |
| 1243 | QualType castT = Context->getPointerType(Context->getTagDeclType(RD)); |
| 1244 | CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT, |
| 1245 | CastExpr::CK_Unknown, |
| 1246 | IV->getBase()); |
| 1247 | // Don't forget the parens to enforce the proper binding. |
| 1248 | ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(), |
| 1249 | IV->getBase()->getLocEnd(), |
| 1250 | castExpr); |
| 1251 | replaced = true; |
| 1252 | if (IV->isFreeIvar() && |
| 1253 | CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) { |
| 1254 | MemberExpr *ME = new (Context) MemberExpr(PE, true, D, |
| 1255 | IV->getLocation(), |
| 1256 | D->getType()); |
| 1257 | // delete IV; leak for now, see RewritePropertySetter() usage for more info. |
| 1258 | return ME; |
| 1259 | } |
| 1260 | // Get the new text |
| 1261 | // Cannot delete IV->getBase(), since PE points to it. |
| 1262 | // Replace the old base with the cast. This is important when doing |
| 1263 | // embedded rewrites. For example, [newInv->_container addObject:0]. |
| 1264 | IV->setBase(PE); |
| 1265 | return IV; |
| 1266 | } |
| 1267 | } else { // we are outside a method. |
| 1268 | assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method"); |
| 1269 | |
| 1270 | // Explicit ivar refs need to have a cast inserted. |
| 1271 | // FIXME: consider sharing some of this code with the code above. |
| 1272 | if (BaseExpr->getType()->isObjCObjectPointerType()) { |
| 1273 | ObjCInterfaceType *iFaceDecl = |
| 1274 | dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType()); |
| 1275 | // lookup which class implements the instance variable. |
| 1276 | ObjCInterfaceDecl *clsDeclared = 0; |
| 1277 | iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), |
| 1278 | clsDeclared); |
| 1279 | assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class"); |
| 1280 | |
| 1281 | // Synthesize an explicit cast to gain access to the ivar. |
| 1282 | std::string RecName = clsDeclared->getIdentifier()->getName(); |
| 1283 | RecName += "_IMPL"; |
| 1284 | IdentifierInfo *II = &Context->Idents.get(RecName.c_str()); |
| 1285 | RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl, |
| 1286 | SourceLocation(), II); |
| 1287 | assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl"); |
| 1288 | QualType castT = Context->getPointerType(Context->getTagDeclType(RD)); |
| 1289 | CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT, |
| 1290 | CastExpr::CK_Unknown, |
| 1291 | IV->getBase()); |
| 1292 | // Don't forget the parens to enforce the proper binding. |
| 1293 | ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(), |
| 1294 | IV->getBase()->getLocEnd(), castExpr); |
| 1295 | replaced = true; |
| 1296 | // Cannot delete IV->getBase(), since PE points to it. |
| 1297 | // Replace the old base with the cast. This is important when doing |
| 1298 | // embedded rewrites. For example, [newInv->_container addObject:0]. |
| 1299 | IV->setBase(PE); |
| 1300 | return IV; |
| 1301 | } |
| 1302 | } |
| 1303 | return IV; |
| 1304 | } |
| 1305 | |
| 1306 | Stmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) { |
| 1307 | for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); |
| 1308 | CI != E; ++CI) { |
| 1309 | if (*CI) { |
| 1310 | Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced); |
| 1311 | if (newStmt) |
| 1312 | *CI = newStmt; |
| 1313 | } |
| 1314 | } |
| 1315 | if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) { |
| 1316 | SourceRange OrigStmtRange = S->getSourceRange(); |
| 1317 | Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(), |
| 1318 | replaced); |
| 1319 | return newStmt; |
| 1320 | } |
| 1321 | if (ObjCMessageExpr *MsgRefExpr = dyn_cast<ObjCMessageExpr>(S)) { |
| 1322 | Stmt *newStmt = SynthMessageExpr(MsgRefExpr); |
| 1323 | return newStmt; |
| 1324 | } |
| 1325 | return S; |
| 1326 | } |
| 1327 | |
| 1328 | /// SynthCountByEnumWithState - To print: |
| 1329 | /// ((unsigned int (*) |
| 1330 | /// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int)) |
| 1331 | /// (void *)objc_msgSend)((id)l_collection, |
| 1332 | /// sel_registerName( |
| 1333 | /// "countByEnumeratingWithState:objects:count:"), |
| 1334 | /// &enumState, |
| 1335 | /// (id *)items, (unsigned int)16) |
| 1336 | /// |
| 1337 | void RewriteObjC::SynthCountByEnumWithState(std::string &buf) { |
| 1338 | buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, " |
| 1339 | "id *, unsigned int))(void *)objc_msgSend)"; |
| 1340 | buf += "\n\t\t"; |
| 1341 | buf += "((id)l_collection,\n\t\t"; |
| 1342 | buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),"; |
| 1343 | buf += "\n\t\t"; |
| 1344 | buf += "&enumState, " |
| 1345 | "(id *)items, (unsigned int)16)"; |
| 1346 | } |
| 1347 | |
| 1348 | /// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach |
| 1349 | /// statement to exit to its outer synthesized loop. |
| 1350 | /// |
| 1351 | Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) { |
| 1352 | if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back())) |
| 1353 | return S; |
| 1354 | // replace break with goto __break_label |
| 1355 | std::string buf; |
| 1356 | |
| 1357 | SourceLocation startLoc = S->getLocStart(); |
| 1358 | buf = "goto __break_label_"; |
| 1359 | buf += utostr(ObjCBcLabelNo.back()); |
| 1360 | ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size()); |
| 1361 | |
| 1362 | return 0; |
| 1363 | } |
| 1364 | |
| 1365 | /// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach |
| 1366 | /// statement to continue with its inner synthesized loop. |
| 1367 | /// |
| 1368 | Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) { |
| 1369 | if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back())) |
| 1370 | return S; |
| 1371 | // replace continue with goto __continue_label |
| 1372 | std::string buf; |
| 1373 | |
| 1374 | SourceLocation startLoc = S->getLocStart(); |
| 1375 | buf = "goto __continue_label_"; |
| 1376 | buf += utostr(ObjCBcLabelNo.back()); |
| 1377 | ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size()); |
| 1378 | |
| 1379 | return 0; |
| 1380 | } |
| 1381 | |
| 1382 | /// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement. |
| 1383 | /// It rewrites: |
| 1384 | /// for ( type elem in collection) { stmts; } |
| 1385 | |
| 1386 | /// Into: |
| 1387 | /// { |
| 1388 | /// type elem; |
| 1389 | /// struct __objcFastEnumerationState enumState = { 0 }; |
| 1390 | /// id items[16]; |
| 1391 | /// id l_collection = (id)collection; |
| 1392 | /// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState |
| 1393 | /// objects:items count:16]; |
| 1394 | /// if (limit) { |
| 1395 | /// unsigned long startMutations = *enumState.mutationsPtr; |
| 1396 | /// do { |
| 1397 | /// unsigned long counter = 0; |
| 1398 | /// do { |
| 1399 | /// if (startMutations != *enumState.mutationsPtr) |
| 1400 | /// objc_enumerationMutation(l_collection); |
| 1401 | /// elem = (type)enumState.itemsPtr[counter++]; |
| 1402 | /// stmts; |
| 1403 | /// __continue_label: ; |
| 1404 | /// } while (counter < limit); |
| 1405 | /// } while (limit = [l_collection countByEnumeratingWithState:&enumState |
| 1406 | /// objects:items count:16]); |
| 1407 | /// elem = nil; |
| 1408 | /// __break_label: ; |
| 1409 | /// } |
| 1410 | /// else |
| 1411 | /// elem = nil; |
| 1412 | /// } |
| 1413 | /// |
| 1414 | Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S, |
| 1415 | SourceLocation OrigEnd) { |
| 1416 | assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty"); |
| 1417 | assert(isa<ObjCForCollectionStmt>(Stmts.back()) && |
| 1418 | "ObjCForCollectionStmt Statement stack mismatch"); |
| 1419 | assert(!ObjCBcLabelNo.empty() && |
| 1420 | "ObjCForCollectionStmt - Label No stack empty"); |
| 1421 | |
| 1422 | SourceLocation startLoc = S->getLocStart(); |
| 1423 | const char *startBuf = SM->getCharacterData(startLoc); |
| 1424 | const char *elementName; |
| 1425 | std::string elementTypeAsString; |
| 1426 | std::string buf; |
| 1427 | buf = "\n{\n\t"; |
| 1428 | if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) { |
| 1429 | // type elem; |
| 1430 | NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl()); |
| 1431 | QualType ElementType = cast<ValueDecl>(D)->getType(); |
| 1432 | if (ElementType->isObjCQualifiedIdType() || |
| 1433 | ElementType->isObjCQualifiedInterfaceType()) |
| 1434 | // Simply use 'id' for all qualified types. |
| 1435 | elementTypeAsString = "id"; |
| 1436 | else |
| 1437 | elementTypeAsString = ElementType.getAsString(); |
| 1438 | buf += elementTypeAsString; |
| 1439 | buf += " "; |
| 1440 | elementName = D->getNameAsCString(); |
| 1441 | buf += elementName; |
| 1442 | buf += ";\n\t"; |
| 1443 | } |
| 1444 | else { |
| 1445 | DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement()); |
| 1446 | elementName = DR->getDecl()->getNameAsCString(); |
| 1447 | ValueDecl *VD = cast<ValueDecl>(DR->getDecl()); |
| 1448 | if (VD->getType()->isObjCQualifiedIdType() || |
| 1449 | VD->getType()->isObjCQualifiedInterfaceType()) |
| 1450 | // Simply use 'id' for all qualified types. |
| 1451 | elementTypeAsString = "id"; |
| 1452 | else |
| 1453 | elementTypeAsString = VD->getType().getAsString(); |
| 1454 | } |
| 1455 | |
| 1456 | // struct __objcFastEnumerationState enumState = { 0 }; |
| 1457 | buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t"; |
| 1458 | // id items[16]; |
| 1459 | buf += "id items[16];\n\t"; |
| 1460 | // id l_collection = (id) |
| 1461 | buf += "id l_collection = (id)"; |
| 1462 | // Find start location of 'collection' the hard way! |
| 1463 | const char *startCollectionBuf = startBuf; |
| 1464 | startCollectionBuf += 3; // skip 'for' |
| 1465 | startCollectionBuf = strchr(startCollectionBuf, '('); |
| 1466 | startCollectionBuf++; // skip '(' |
| 1467 | // find 'in' and skip it. |
| 1468 | while (*startCollectionBuf != ' ' || |
| 1469 | *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' || |
| 1470 | (*(startCollectionBuf+3) != ' ' && |
| 1471 | *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '(')) |
| 1472 | startCollectionBuf++; |
| 1473 | startCollectionBuf += 3; |
| 1474 | |
| 1475 | // Replace: "for (type element in" with string constructed thus far. |
| 1476 | ReplaceText(startLoc, startCollectionBuf - startBuf, |
| 1477 | buf.c_str(), buf.size()); |
| 1478 | // Replace ')' in for '(' type elem in collection ')' with ';' |
| 1479 | SourceLocation rightParenLoc = S->getRParenLoc(); |
| 1480 | const char *rparenBuf = SM->getCharacterData(rightParenLoc); |
| 1481 | SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf); |
| 1482 | buf = ";\n\t"; |
| 1483 | |
| 1484 | // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState |
| 1485 | // objects:items count:16]; |
| 1486 | // which is synthesized into: |
| 1487 | // unsigned int limit = |
| 1488 | // ((unsigned int (*) |
| 1489 | // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int)) |
| 1490 | // (void *)objc_msgSend)((id)l_collection, |
| 1491 | // sel_registerName( |
| 1492 | // "countByEnumeratingWithState:objects:count:"), |
| 1493 | // (struct __objcFastEnumerationState *)&state, |
| 1494 | // (id *)items, (unsigned int)16); |
| 1495 | buf += "unsigned long limit =\n\t\t"; |
| 1496 | SynthCountByEnumWithState(buf); |
| 1497 | buf += ";\n\t"; |
| 1498 | /// if (limit) { |
| 1499 | /// unsigned long startMutations = *enumState.mutationsPtr; |
| 1500 | /// do { |
| 1501 | /// unsigned long counter = 0; |
| 1502 | /// do { |
| 1503 | /// if (startMutations != *enumState.mutationsPtr) |
| 1504 | /// objc_enumerationMutation(l_collection); |
| 1505 | /// elem = (type)enumState.itemsPtr[counter++]; |
| 1506 | buf += "if (limit) {\n\t"; |
| 1507 | buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t"; |
| 1508 | buf += "do {\n\t\t"; |
| 1509 | buf += "unsigned long counter = 0;\n\t\t"; |
| 1510 | buf += "do {\n\t\t\t"; |
| 1511 | buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t"; |
| 1512 | buf += "objc_enumerationMutation(l_collection);\n\t\t\t"; |
| 1513 | buf += elementName; |
| 1514 | buf += " = ("; |
| 1515 | buf += elementTypeAsString; |
| 1516 | buf += ")enumState.itemsPtr[counter++];"; |
| 1517 | // Replace ')' in for '(' type elem in collection ')' with all of these. |
| 1518 | ReplaceText(lparenLoc, 1, buf.c_str(), buf.size()); |
| 1519 | |
| 1520 | /// __continue_label: ; |
| 1521 | /// } while (counter < limit); |
| 1522 | /// } while (limit = [l_collection countByEnumeratingWithState:&enumState |
| 1523 | /// objects:items count:16]); |
| 1524 | /// elem = nil; |
| 1525 | /// __break_label: ; |
| 1526 | /// } |
| 1527 | /// else |
| 1528 | /// elem = nil; |
| 1529 | /// } |
| 1530 | /// |
| 1531 | buf = ";\n\t"; |
| 1532 | buf += "__continue_label_"; |
| 1533 | buf += utostr(ObjCBcLabelNo.back()); |
| 1534 | buf += ": ;"; |
| 1535 | buf += "\n\t\t"; |
| 1536 | buf += "} while (counter < limit);\n\t"; |
| 1537 | buf += "} while (limit = "; |
| 1538 | SynthCountByEnumWithState(buf); |
| 1539 | buf += ");\n\t"; |
| 1540 | buf += elementName; |
| 1541 | buf += " = (("; |
| 1542 | buf += elementTypeAsString; |
| 1543 | buf += ")0);\n\t"; |
| 1544 | buf += "__break_label_"; |
| 1545 | buf += utostr(ObjCBcLabelNo.back()); |
| 1546 | buf += ": ;\n\t"; |
| 1547 | buf += "}\n\t"; |
| 1548 | buf += "else\n\t\t"; |
| 1549 | buf += elementName; |
| 1550 | buf += " = (("; |
| 1551 | buf += elementTypeAsString; |
| 1552 | buf += ")0);\n\t"; |
| 1553 | buf += "}\n"; |
| 1554 | |
| 1555 | // Insert all these *after* the statement body. |
| 1556 | // FIXME: If this should support Obj-C++, support CXXTryStmt |
| 1557 | if (isa<CompoundStmt>(S->getBody())) { |
| 1558 | SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1); |
| 1559 | InsertText(endBodyLoc, buf.c_str(), buf.size()); |
| 1560 | } else { |
| 1561 | /* Need to treat single statements specially. For example: |
| 1562 | * |
| 1563 | * for (A *a in b) if (stuff()) break; |
| 1564 | * for (A *a in b) xxxyy; |
| 1565 | * |
| 1566 | * The following code simply scans ahead to the semi to find the actual end. |
| 1567 | */ |
| 1568 | const char *stmtBuf = SM->getCharacterData(OrigEnd); |
| 1569 | const char *semiBuf = strchr(stmtBuf, ';'); |
| 1570 | assert(semiBuf && "Can't find ';'"); |
| 1571 | SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1); |
| 1572 | InsertText(endBodyLoc, buf.c_str(), buf.size()); |
| 1573 | } |
| 1574 | Stmts.pop_back(); |
| 1575 | ObjCBcLabelNo.pop_back(); |
| 1576 | return 0; |
| 1577 | } |
| 1578 | |
| 1579 | /// RewriteObjCSynchronizedStmt - |
| 1580 | /// This routine rewrites @synchronized(expr) stmt; |
| 1581 | /// into: |
| 1582 | /// objc_sync_enter(expr); |
| 1583 | /// @try stmt @finally { objc_sync_exit(expr); } |
| 1584 | /// |
| 1585 | Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) { |
| 1586 | // Get the start location and compute the semi location. |
| 1587 | SourceLocation startLoc = S->getLocStart(); |
| 1588 | const char *startBuf = SM->getCharacterData(startLoc); |
| 1589 | |
| 1590 | assert((*startBuf == '@') && "bogus @synchronized location"); |
| 1591 | |
| 1592 | std::string buf; |
| 1593 | buf = "objc_sync_enter((id)"; |
| 1594 | const char *lparenBuf = startBuf; |
| 1595 | while (*lparenBuf != '(') lparenBuf++; |
| 1596 | ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size()); |
| 1597 | // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since |
| 1598 | // the sync expression is typically a message expression that's already |
| 1599 | // been rewritten! (which implies the SourceLocation's are invalid). |
| 1600 | SourceLocation endLoc = S->getSynchBody()->getLocStart(); |
| 1601 | const char *endBuf = SM->getCharacterData(endLoc); |
| 1602 | while (*endBuf != ')') endBuf--; |
| 1603 | SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf); |
| 1604 | buf = ");\n"; |
| 1605 | // declare a new scope with two variables, _stack and _rethrow. |
| 1606 | buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n"; |
| 1607 | buf += "int buf[18/*32-bit i386*/];\n"; |
| 1608 | buf += "char *pointers[4];} _stack;\n"; |
| 1609 | buf += "id volatile _rethrow = 0;\n"; |
| 1610 | buf += "objc_exception_try_enter(&_stack);\n"; |
| 1611 | buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n"; |
| 1612 | ReplaceText(rparenLoc, 1, buf.c_str(), buf.size()); |
| 1613 | startLoc = S->getSynchBody()->getLocEnd(); |
| 1614 | startBuf = SM->getCharacterData(startLoc); |
| 1615 | |
| 1616 | assert((*startBuf == '}') && "bogus @synchronized block"); |
| 1617 | SourceLocation lastCurlyLoc = startLoc; |
| 1618 | buf = "}\nelse {\n"; |
| 1619 | buf += " _rethrow = objc_exception_extract(&_stack);\n"; |
| 1620 | buf += "}\n"; |
| 1621 | buf += "{ /* implicit finally clause */\n"; |
| 1622 | buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n"; |
| 1623 | |
| 1624 | std::string syncBuf; |
| 1625 | syncBuf += " objc_sync_exit("; |
| 1626 | Expr *syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(), |
| 1627 | CastExpr::CK_Unknown, |
| 1628 | S->getSynchExpr()); |
| 1629 | std::string syncExprBufS; |
| 1630 | llvm::raw_string_ostream syncExprBuf(syncExprBufS); |
| 1631 | syncExpr->printPretty(syncExprBuf, *Context, 0, |
| 1632 | PrintingPolicy(LangOpts)); |
| 1633 | syncBuf += syncExprBuf.str(); |
| 1634 | syncBuf += ");"; |
| 1635 | |
| 1636 | buf += syncBuf; |
| 1637 | buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n"; |
| 1638 | buf += "}\n"; |
| 1639 | buf += "}"; |
| 1640 | |
| 1641 | ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size()); |
| 1642 | |
| 1643 | bool hasReturns = false; |
| 1644 | HasReturnStmts(S->getSynchBody(), hasReturns); |
| 1645 | if (hasReturns) |
| 1646 | RewriteSyncReturnStmts(S->getSynchBody(), syncBuf); |
| 1647 | |
| 1648 | return 0; |
| 1649 | } |
| 1650 | |
| 1651 | void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S) |
| 1652 | { |
| 1653 | // Perform a bottom up traversal of all children. |
| 1654 | for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); |
| 1655 | CI != E; ++CI) |
| 1656 | if (*CI) |
| 1657 | WarnAboutReturnGotoStmts(*CI); |
| 1658 | |
| 1659 | if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) { |
| 1660 | Diags.Report(Context->getFullLoc(S->getLocStart()), |
| 1661 | TryFinallyContainsReturnDiag); |
| 1662 | } |
| 1663 | return; |
| 1664 | } |
| 1665 | |
| 1666 | void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns) |
| 1667 | { |
| 1668 | // Perform a bottom up traversal of all children. |
| 1669 | for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); |
| 1670 | CI != E; ++CI) |
| 1671 | if (*CI) |
| 1672 | HasReturnStmts(*CI, hasReturns); |
| 1673 | |
| 1674 | if (isa<ReturnStmt>(S)) |
| 1675 | hasReturns = true; |
| 1676 | return; |
| 1677 | } |
| 1678 | |
| 1679 | void RewriteObjC::RewriteTryReturnStmts(Stmt *S) { |
| 1680 | // Perform a bottom up traversal of all children. |
| 1681 | for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); |
| 1682 | CI != E; ++CI) |
| 1683 | if (*CI) { |
| 1684 | RewriteTryReturnStmts(*CI); |
| 1685 | } |
| 1686 | if (isa<ReturnStmt>(S)) { |
| 1687 | SourceLocation startLoc = S->getLocStart(); |
| 1688 | const char *startBuf = SM->getCharacterData(startLoc); |
| 1689 | |
| 1690 | const char *semiBuf = strchr(startBuf, ';'); |
| 1691 | assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'"); |
| 1692 | SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1); |
| 1693 | |
| 1694 | std::string buf; |
| 1695 | buf = "{ objc_exception_try_exit(&_stack); return"; |
| 1696 | |
| 1697 | ReplaceText(startLoc, 6, buf.c_str(), buf.size()); |
| 1698 | InsertText(onePastSemiLoc, "}", 1); |
| 1699 | } |
| 1700 | return; |
| 1701 | } |
| 1702 | |
| 1703 | void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) { |
| 1704 | // Perform a bottom up traversal of all children. |
| 1705 | for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); |
| 1706 | CI != E; ++CI) |
| 1707 | if (*CI) { |
| 1708 | RewriteSyncReturnStmts(*CI, syncExitBuf); |
| 1709 | } |
| 1710 | if (isa<ReturnStmt>(S)) { |
| 1711 | SourceLocation startLoc = S->getLocStart(); |
| 1712 | const char *startBuf = SM->getCharacterData(startLoc); |
| 1713 | |
| 1714 | const char *semiBuf = strchr(startBuf, ';'); |
| 1715 | assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'"); |
| 1716 | SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1); |
| 1717 | |
| 1718 | std::string buf; |
| 1719 | buf = "{ objc_exception_try_exit(&_stack);"; |
| 1720 | buf += syncExitBuf; |
| 1721 | buf += " return"; |
| 1722 | |
| 1723 | ReplaceText(startLoc, 6, buf.c_str(), buf.size()); |
| 1724 | InsertText(onePastSemiLoc, "}", 1); |
| 1725 | } |
| 1726 | return; |
| 1727 | } |
| 1728 | |
| 1729 | Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) { |
| 1730 | // Get the start location and compute the semi location. |
| 1731 | SourceLocation startLoc = S->getLocStart(); |
| 1732 | const char *startBuf = SM->getCharacterData(startLoc); |
| 1733 | |
| 1734 | assert((*startBuf == '@') && "bogus @try location"); |
| 1735 | |
| 1736 | std::string buf; |
| 1737 | // declare a new scope with two variables, _stack and _rethrow. |
| 1738 | buf = "/* @try scope begin */ { struct _objc_exception_data {\n"; |
| 1739 | buf += "int buf[18/*32-bit i386*/];\n"; |
| 1740 | buf += "char *pointers[4];} _stack;\n"; |
| 1741 | buf += "id volatile _rethrow = 0;\n"; |
| 1742 | buf += "objc_exception_try_enter(&_stack);\n"; |
| 1743 | buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n"; |
| 1744 | |
| 1745 | ReplaceText(startLoc, 4, buf.c_str(), buf.size()); |
| 1746 | |
| 1747 | startLoc = S->getTryBody()->getLocEnd(); |
| 1748 | startBuf = SM->getCharacterData(startLoc); |
| 1749 | |
| 1750 | assert((*startBuf == '}') && "bogus @try block"); |
| 1751 | |
| 1752 | SourceLocation lastCurlyLoc = startLoc; |
| 1753 | ObjCAtCatchStmt *catchList = S->getCatchStmts(); |
| 1754 | if (catchList) { |
| 1755 | startLoc = startLoc.getFileLocWithOffset(1); |
| 1756 | buf = " /* @catch begin */ else {\n"; |
| 1757 | buf += " id _caught = objc_exception_extract(&_stack);\n"; |
| 1758 | buf += " objc_exception_try_enter (&_stack);\n"; |
| 1759 | buf += " if (_setjmp(_stack.buf))\n"; |
| 1760 | buf += " _rethrow = objc_exception_extract(&_stack);\n"; |
| 1761 | buf += " else { /* @catch continue */"; |
| 1762 | |
| 1763 | InsertText(startLoc, buf.c_str(), buf.size()); |
| 1764 | } else { /* no catch list */ |
| 1765 | buf = "}\nelse {\n"; |
| 1766 | buf += " _rethrow = objc_exception_extract(&_stack);\n"; |
| 1767 | buf += "}"; |
| 1768 | ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size()); |
| 1769 | } |
| 1770 | bool sawIdTypedCatch = false; |
| 1771 | Stmt *lastCatchBody = 0; |
| 1772 | while (catchList) { |
| 1773 | ParmVarDecl *catchDecl = catchList->getCatchParamDecl(); |
| 1774 | |
| 1775 | if (catchList == S->getCatchStmts()) |
| 1776 | buf = "if ("; // we are generating code for the first catch clause |
| 1777 | else |
| 1778 | buf = "else if ("; |
| 1779 | startLoc = catchList->getLocStart(); |
| 1780 | startBuf = SM->getCharacterData(startLoc); |
| 1781 | |
| 1782 | assert((*startBuf == '@') && "bogus @catch location"); |
| 1783 | |
| 1784 | const char *lParenLoc = strchr(startBuf, '('); |
| 1785 | |
| 1786 | if (catchList->hasEllipsis()) { |
| 1787 | // Now rewrite the body... |
| 1788 | lastCatchBody = catchList->getCatchBody(); |
| 1789 | SourceLocation bodyLoc = lastCatchBody->getLocStart(); |
| 1790 | const char *bodyBuf = SM->getCharacterData(bodyLoc); |
| 1791 | assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' && |
| 1792 | "bogus @catch paren location"); |
| 1793 | assert((*bodyBuf == '{') && "bogus @catch body location"); |
| 1794 | |
| 1795 | buf += "1) { id _tmp = _caught;"; |
| 1796 | Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf); |
| 1797 | } else if (catchDecl) { |
| 1798 | QualType t = catchDecl->getType(); |
| 1799 | if (t == Context->getObjCIdType()) { |
| 1800 | buf += "1) { "; |
| 1801 | ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size()); |
| 1802 | sawIdTypedCatch = true; |
| 1803 | } else if (t->isObjCObjectPointerType()) { |
| 1804 | QualType InterfaceTy = t->getPointeeType(); |
| 1805 | const ObjCInterfaceType *cls = // Should be a pointer to a class. |
| 1806 | InterfaceTy->getAs<ObjCInterfaceType>(); |
| 1807 | if (cls) { |
| 1808 | buf += "objc_exception_match((struct objc_class *)objc_getClass(\""; |
| 1809 | buf += cls->getDecl()->getNameAsString(); |
| 1810 | buf += "\"), (struct objc_object *)_caught)) { "; |
| 1811 | ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size()); |
| 1812 | } |
| 1813 | } |
| 1814 | // Now rewrite the body... |
| 1815 | lastCatchBody = catchList->getCatchBody(); |
| 1816 | SourceLocation rParenLoc = catchList->getRParenLoc(); |
| 1817 | SourceLocation bodyLoc = lastCatchBody->getLocStart(); |
| 1818 | const char *bodyBuf = SM->getCharacterData(bodyLoc); |
| 1819 | const char *rParenBuf = SM->getCharacterData(rParenLoc); |
| 1820 | assert((*rParenBuf == ')') && "bogus @catch paren location"); |
| 1821 | assert((*bodyBuf == '{') && "bogus @catch body location"); |
| 1822 | |
| 1823 | buf = " = _caught;"; |
| 1824 | // Here we replace ") {" with "= _caught;" (which initializes and |
| 1825 | // declares the @catch parameter). |
| 1826 | ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size()); |
| 1827 | } else { |
| 1828 | assert(false && "@catch rewrite bug"); |
| 1829 | } |
| 1830 | // make sure all the catch bodies get rewritten! |
| 1831 | catchList = catchList->getNextCatchStmt(); |
| 1832 | } |
| 1833 | // Complete the catch list... |
| 1834 | if (lastCatchBody) { |
| 1835 | SourceLocation bodyLoc = lastCatchBody->getLocEnd(); |
| 1836 | assert(*SM->getCharacterData(bodyLoc) == '}' && |
| 1837 | "bogus @catch body location"); |
| 1838 | |
| 1839 | // Insert the last (implicit) else clause *before* the right curly brace. |
| 1840 | bodyLoc = bodyLoc.getFileLocWithOffset(-1); |
| 1841 | buf = "} /* last catch end */\n"; |
| 1842 | buf += "else {\n"; |
| 1843 | buf += " _rethrow = _caught;\n"; |
| 1844 | buf += " objc_exception_try_exit(&_stack);\n"; |
| 1845 | buf += "} } /* @catch end */\n"; |
| 1846 | if (!S->getFinallyStmt()) |
| 1847 | buf += "}\n"; |
| 1848 | InsertText(bodyLoc, buf.c_str(), buf.size()); |
| 1849 | |
| 1850 | // Set lastCurlyLoc |
| 1851 | lastCurlyLoc = lastCatchBody->getLocEnd(); |
| 1852 | } |
| 1853 | if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) { |
| 1854 | startLoc = finalStmt->getLocStart(); |
| 1855 | startBuf = SM->getCharacterData(startLoc); |
| 1856 | assert((*startBuf == '@') && "bogus @finally start"); |
| 1857 | |
| 1858 | buf = "/* @finally */"; |
| 1859 | ReplaceText(startLoc, 8, buf.c_str(), buf.size()); |
| 1860 | |
| 1861 | Stmt *body = finalStmt->getFinallyBody(); |
| 1862 | SourceLocation startLoc = body->getLocStart(); |
| 1863 | SourceLocation endLoc = body->getLocEnd(); |
| 1864 | assert(*SM->getCharacterData(startLoc) == '{' && |
| 1865 | "bogus @finally body location"); |
| 1866 | assert(*SM->getCharacterData(endLoc) == '}' && |
| 1867 | "bogus @finally body location"); |
| 1868 | |
| 1869 | startLoc = startLoc.getFileLocWithOffset(1); |
| 1870 | buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n"; |
| 1871 | InsertText(startLoc, buf.c_str(), buf.size()); |
| 1872 | endLoc = endLoc.getFileLocWithOffset(-1); |
| 1873 | buf = " if (_rethrow) objc_exception_throw(_rethrow);\n"; |
| 1874 | InsertText(endLoc, buf.c_str(), buf.size()); |
| 1875 | |
| 1876 | // Set lastCurlyLoc |
| 1877 | lastCurlyLoc = body->getLocEnd(); |
| 1878 | |
| 1879 | // Now check for any return/continue/go statements within the @try. |
| 1880 | WarnAboutReturnGotoStmts(S->getTryBody()); |
| 1881 | } else { /* no finally clause - make sure we synthesize an implicit one */ |
| 1882 | buf = "{ /* implicit finally clause */\n"; |
| 1883 | buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n"; |
| 1884 | buf += " if (_rethrow) objc_exception_throw(_rethrow);\n"; |
| 1885 | buf += "}"; |
| 1886 | ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size()); |
| 1887 | |
| 1888 | // Now check for any return/continue/go statements within the @try. |
| 1889 | // The implicit finally clause won't called if the @try contains any |
| 1890 | // jump statements. |
| 1891 | bool hasReturns = false; |
| 1892 | HasReturnStmts(S->getTryBody(), hasReturns); |
| 1893 | if (hasReturns) |
| 1894 | RewriteTryReturnStmts(S->getTryBody()); |
| 1895 | } |
| 1896 | // Now emit the final closing curly brace... |
| 1897 | lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1); |
| 1898 | buf = " } /* @try scope end */\n"; |
| 1899 | InsertText(lastCurlyLoc, buf.c_str(), buf.size()); |
| 1900 | return 0; |
| 1901 | } |
| 1902 | |
| 1903 | Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) { |
| 1904 | return 0; |
| 1905 | } |
| 1906 | |
| 1907 | Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) { |
| 1908 | return 0; |
| 1909 | } |
| 1910 | |
| 1911 | // This can't be done with ReplaceStmt(S, ThrowExpr), since |
| 1912 | // the throw expression is typically a message expression that's already |
| 1913 | // been rewritten! (which implies the SourceLocation's are invalid). |
| 1914 | Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) { |
| 1915 | // Get the start location and compute the semi location. |
| 1916 | SourceLocation startLoc = S->getLocStart(); |
| 1917 | const char *startBuf = SM->getCharacterData(startLoc); |
| 1918 | |
| 1919 | assert((*startBuf == '@') && "bogus @throw location"); |
| 1920 | |
| 1921 | std::string buf; |
| 1922 | /* void objc_exception_throw(id) __attribute__((noreturn)); */ |
| 1923 | if (S->getThrowExpr()) |
| 1924 | buf = "objc_exception_throw("; |
| 1925 | else // add an implicit argument |
| 1926 | buf = "objc_exception_throw(_caught"; |
| 1927 | |
| 1928 | // handle "@ throw" correctly. |
| 1929 | const char *wBuf = strchr(startBuf, 'w'); |
| 1930 | assert((*wBuf == 'w') && "@throw: can't find 'w'"); |
| 1931 | ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size()); |
| 1932 | |
| 1933 | const char *semiBuf = strchr(startBuf, ';'); |
| 1934 | assert((*semiBuf == ';') && "@throw: can't find ';'"); |
| 1935 | SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf); |
| 1936 | buf = ");"; |
| 1937 | ReplaceText(semiLoc, 1, buf.c_str(), buf.size()); |
| 1938 | return 0; |
| 1939 | } |
| 1940 | |
| 1941 | Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) { |
| 1942 | // Create a new string expression. |
| 1943 | QualType StrType = Context->getPointerType(Context->CharTy); |
| 1944 | std::string StrEncoding; |
| 1945 | Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding); |
| 1946 | Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(), |
| 1947 | StrEncoding.length(), false,StrType, |
| 1948 | SourceLocation()); |
| 1949 | ReplaceStmt(Exp, Replacement); |
| 1950 | |
| 1951 | // Replace this subexpr in the parent. |
| 1952 | // delete Exp; leak for now, see RewritePropertySetter() usage for more info. |
| 1953 | return Replacement; |
| 1954 | } |
| 1955 | |
| 1956 | Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) { |
| 1957 | if (!SelGetUidFunctionDecl) |
| 1958 | SynthSelGetUidFunctionDecl(); |
| 1959 | assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl"); |
| 1960 | // Create a call to sel_registerName("selName"). |
| 1961 | llvm::SmallVector<Expr*, 8> SelExprs; |
| 1962 | QualType argType = Context->getPointerType(Context->CharTy); |
| 1963 | SelExprs.push_back(StringLiteral::Create(*Context, |
| 1964 | Exp->getSelector().getAsString().c_str(), |
| 1965 | Exp->getSelector().getAsString().size(), |
| 1966 | false, argType, SourceLocation())); |
| 1967 | CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl, |
| 1968 | &SelExprs[0], SelExprs.size()); |
| 1969 | ReplaceStmt(Exp, SelExp); |
| 1970 | // delete Exp; leak for now, see RewritePropertySetter() usage for more info. |
| 1971 | return SelExp; |
| 1972 | } |
| 1973 | |
| 1974 | CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl( |
| 1975 | FunctionDecl *FD, Expr **args, unsigned nargs) { |
| 1976 | // Get the type, we will need to reference it in a couple spots. |
| 1977 | QualType msgSendType = FD->getType(); |
| 1978 | |
| 1979 | // Create a reference to the objc_msgSend() declaration. |
| 1980 | DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation()); |
| 1981 | |
| 1982 | // Now, we cast the reference to a pointer to the objc_msgSend type. |
| 1983 | QualType pToFunc = Context->getPointerType(msgSendType); |
| 1984 | ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc, |
| 1985 | CastExpr::CK_Unknown, |
| 1986 | DRE, |
| 1987 | /*isLvalue=*/false); |
| 1988 | |
| 1989 | const FunctionType *FT = msgSendType->getAs<FunctionType>(); |
| 1990 | |
| 1991 | return new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(), |
| 1992 | SourceLocation()); |
| 1993 | } |
| 1994 | |
| 1995 | static bool scanForProtocolRefs(const char *startBuf, const char *endBuf, |
| 1996 | const char *&startRef, const char *&endRef) { |
| 1997 | while (startBuf < endBuf) { |
| 1998 | if (*startBuf == '<') |
| 1999 | startRef = startBuf; // mark the start. |
| 2000 | if (*startBuf == '>') { |
| 2001 | if (startRef && *startRef == '<') { |
| 2002 | endRef = startBuf; // mark the end. |
| 2003 | return true; |
| 2004 | } |
| 2005 | return false; |
| 2006 | } |
| 2007 | startBuf++; |
| 2008 | } |
| 2009 | return false; |
| 2010 | } |
| 2011 | |
| 2012 | static void scanToNextArgument(const char *&argRef) { |
| 2013 | int angle = 0; |
| 2014 | while (*argRef != ')' && (*argRef != ',' || angle > 0)) { |
| 2015 | if (*argRef == '<') |
| 2016 | angle++; |
| 2017 | else if (*argRef == '>') |
| 2018 | angle--; |
| 2019 | argRef++; |
| 2020 | } |
| 2021 | assert(angle == 0 && "scanToNextArgument - bad protocol type syntax"); |
| 2022 | } |
| 2023 | |
| 2024 | bool RewriteObjC::needToScanForQualifiers(QualType T) { |
| 2025 | if (T->isObjCQualifiedIdType()) |
| 2026 | return true; |
| 2027 | if (const PointerType *PT = T->getAs<PointerType>()) { |
| 2028 | if (PT->getPointeeType()->isObjCQualifiedIdType()) |
| 2029 | return true; |
| 2030 | } |
| 2031 | if (T->isObjCObjectPointerType()) { |
| 2032 | T = T->getPointeeType(); |
| 2033 | return T->isObjCQualifiedInterfaceType(); |
| 2034 | } |
| 2035 | return false; |
| 2036 | } |
| 2037 | |
| 2038 | void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) { |
| 2039 | QualType Type = E->getType(); |
| 2040 | if (needToScanForQualifiers(Type)) { |
| 2041 | SourceLocation Loc, EndLoc; |
| 2042 | |
| 2043 | if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) { |
| 2044 | Loc = ECE->getLParenLoc(); |
| 2045 | EndLoc = ECE->getRParenLoc(); |
| 2046 | } else { |
| 2047 | Loc = E->getLocStart(); |
| 2048 | EndLoc = E->getLocEnd(); |
| 2049 | } |
| 2050 | // This will defend against trying to rewrite synthesized expressions. |
| 2051 | if (Loc.isInvalid() || EndLoc.isInvalid()) |
| 2052 | return; |
| 2053 | |
| 2054 | const char *startBuf = SM->getCharacterData(Loc); |
| 2055 | const char *endBuf = SM->getCharacterData(EndLoc); |
| 2056 | const char *startRef = 0, *endRef = 0; |
| 2057 | if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) { |
| 2058 | // Get the locations of the startRef, endRef. |
| 2059 | SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf); |
| 2060 | SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1); |
| 2061 | // Comment out the protocol references. |
| 2062 | InsertText(LessLoc, "/*", 2); |
| 2063 | InsertText(GreaterLoc, "*/", 2); |
| 2064 | } |
| 2065 | } |
| 2066 | } |
| 2067 | |
| 2068 | void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) { |
| 2069 | SourceLocation Loc; |
| 2070 | QualType Type; |
| 2071 | const FunctionProtoType *proto = 0; |
| 2072 | if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) { |
| 2073 | Loc = VD->getLocation(); |
| 2074 | Type = VD->getType(); |
| 2075 | } |
| 2076 | else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) { |
| 2077 | Loc = FD->getLocation(); |
| 2078 | // Check for ObjC 'id' and class types that have been adorned with protocol |
| 2079 | // information (id<p>, C<p>*). The protocol references need to be rewritten! |
| 2080 | const FunctionType *funcType = FD->getType()->getAs<FunctionType>(); |
| 2081 | assert(funcType && "missing function type"); |
| 2082 | proto = dyn_cast<FunctionProtoType>(funcType); |
| 2083 | if (!proto) |
| 2084 | return; |
| 2085 | Type = proto->getResultType(); |
| 2086 | } |
| 2087 | else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) { |
| 2088 | Loc = FD->getLocation(); |
| 2089 | Type = FD->getType(); |
| 2090 | } |
| 2091 | else |
| 2092 | return; |
| 2093 | |
| 2094 | if (needToScanForQualifiers(Type)) { |
| 2095 | // Since types are unique, we need to scan the buffer. |
| 2096 | |
| 2097 | const char *endBuf = SM->getCharacterData(Loc); |
| 2098 | const char *startBuf = endBuf; |
| 2099 | while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart) |
| 2100 | startBuf--; // scan backward (from the decl location) for return type. |
| 2101 | const char *startRef = 0, *endRef = 0; |
| 2102 | if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) { |
| 2103 | // Get the locations of the startRef, endRef. |
| 2104 | SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf); |
| 2105 | SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1); |
| 2106 | // Comment out the protocol references. |
| 2107 | InsertText(LessLoc, "/*", 2); |
| 2108 | InsertText(GreaterLoc, "*/", 2); |
| 2109 | } |
| 2110 | } |
| 2111 | if (!proto) |
| 2112 | return; // most likely, was a variable |
| 2113 | // Now check arguments. |
| 2114 | const char *startBuf = SM->getCharacterData(Loc); |
| 2115 | const char *startFuncBuf = startBuf; |
| 2116 | for (unsigned i = 0; i < proto->getNumArgs(); i++) { |
| 2117 | if (needToScanForQualifiers(proto->getArgType(i))) { |
| 2118 | // Since types are unique, we need to scan the buffer. |
| 2119 | |
| 2120 | const char *endBuf = startBuf; |
| 2121 | // scan forward (from the decl location) for argument types. |
| 2122 | scanToNextArgument(endBuf); |
| 2123 | const char *startRef = 0, *endRef = 0; |
| 2124 | if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) { |
| 2125 | // Get the locations of the startRef, endRef. |
| 2126 | SourceLocation LessLoc = |
| 2127 | Loc.getFileLocWithOffset(startRef-startFuncBuf); |
| 2128 | SourceLocation GreaterLoc = |
| 2129 | Loc.getFileLocWithOffset(endRef-startFuncBuf+1); |
| 2130 | // Comment out the protocol references. |
| 2131 | InsertText(LessLoc, "/*", 2); |
| 2132 | InsertText(GreaterLoc, "*/", 2); |
| 2133 | } |
| 2134 | startBuf = ++endBuf; |
| 2135 | } |
| 2136 | else { |
| 2137 | // If the function name is derived from a macro expansion, then the |
| 2138 | // argument buffer will not follow the name. Need to speak with Chris. |
| 2139 | while (*startBuf && *startBuf != ')' && *startBuf != ',') |
| 2140 | startBuf++; // scan forward (from the decl location) for argument types. |
| 2141 | startBuf++; |
| 2142 | } |
| 2143 | } |
| 2144 | } |
| 2145 | |
| 2146 | // SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str); |
| 2147 | void RewriteObjC::SynthSelGetUidFunctionDecl() { |
| 2148 | IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName"); |
| 2149 | llvm::SmallVector<QualType, 16> ArgTys; |
| 2150 | ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst())); |
| 2151 | QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(), |
| 2152 | &ArgTys[0], ArgTys.size(), |
| 2153 | false /*isVariadic*/, 0); |
| 2154 | SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl, |
| 2155 | SourceLocation(), |
| 2156 | SelGetUidIdent, getFuncType, 0, |
| 2157 | FunctionDecl::Extern, false); |
| 2158 | } |
| 2159 | |
| 2160 | void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) { |
| 2161 | // declared in <objc/objc.h> |
| 2162 | if (FD->getIdentifier() && |
| 2163 | strcmp(FD->getNameAsCString(), "sel_registerName") == 0) { |
| 2164 | SelGetUidFunctionDecl = FD; |
| 2165 | return; |
| 2166 | } |
| 2167 | RewriteObjCQualifiedInterfaceTypes(FD); |
| 2168 | } |
| 2169 | |
| 2170 | void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) { |
| 2171 | SourceLocation FunLocStart = FD->getTypeSpecStartLoc(); |
| 2172 | const FunctionType *funcType = FD->getType()->getAs<FunctionType>(); |
| 2173 | const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType); |
| 2174 | if (!proto) |
| 2175 | return; |
| 2176 | QualType Type = proto->getResultType(); |
| 2177 | std::string FdStr = Type.getAsString(); |
| 2178 | FdStr += " "; |
| 2179 | FdStr += FD->getNameAsCString(); |
| 2180 | FdStr += "("; |
| 2181 | unsigned numArgs = proto->getNumArgs(); |
| 2182 | for (unsigned i = 0; i < numArgs; i++) { |
| 2183 | QualType ArgType = proto->getArgType(i); |
| 2184 | FdStr += ArgType.getAsString(); |
| 2185 | |
| 2186 | if (i+1 < numArgs) |
| 2187 | FdStr += ", "; |
| 2188 | } |
| 2189 | FdStr += ");\n"; |
| 2190 | InsertText(FunLocStart, FdStr.c_str(), FdStr.size()); |
| 2191 | CurFunctionDeclToDeclareForBlock = 0; |
| 2192 | } |
| 2193 | |
| 2194 | // SynthSuperContructorFunctionDecl - id objc_super(id obj, id super); |
| 2195 | void RewriteObjC::SynthSuperContructorFunctionDecl() { |
| 2196 | if (SuperContructorFunctionDecl) |
| 2197 | return; |
| 2198 | IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super"); |
| 2199 | llvm::SmallVector<QualType, 16> ArgTys; |
| 2200 | QualType argT = Context->getObjCIdType(); |
| 2201 | assert(!argT.isNull() && "Can't find 'id' type"); |
| 2202 | ArgTys.push_back(argT); |
| 2203 | ArgTys.push_back(argT); |
| 2204 | QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(), |
| 2205 | &ArgTys[0], ArgTys.size(), |
| 2206 | false, 0); |
| 2207 | SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl, |
| 2208 | SourceLocation(), |
| 2209 | msgSendIdent, msgSendType, 0, |
| 2210 | FunctionDecl::Extern, false); |
| 2211 | } |
| 2212 | |
| 2213 | // SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...); |
| 2214 | void RewriteObjC::SynthMsgSendFunctionDecl() { |
| 2215 | IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend"); |
| 2216 | llvm::SmallVector<QualType, 16> ArgTys; |
| 2217 | QualType argT = Context->getObjCIdType(); |
| 2218 | assert(!argT.isNull() && "Can't find 'id' type"); |
| 2219 | ArgTys.push_back(argT); |
| 2220 | argT = Context->getObjCSelType(); |
| 2221 | assert(!argT.isNull() && "Can't find 'SEL' type"); |
| 2222 | ArgTys.push_back(argT); |
| 2223 | QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(), |
| 2224 | &ArgTys[0], ArgTys.size(), |
| 2225 | true /*isVariadic*/, 0); |
| 2226 | MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl, |
| 2227 | SourceLocation(), |
| 2228 | msgSendIdent, msgSendType, 0, |
| 2229 | FunctionDecl::Extern, false); |
| 2230 | } |
| 2231 | |
| 2232 | // SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...); |
| 2233 | void RewriteObjC::SynthMsgSendSuperFunctionDecl() { |
| 2234 | IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper"); |
| 2235 | llvm::SmallVector<QualType, 16> ArgTys; |
| 2236 | RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl, |
| 2237 | SourceLocation(), |
| 2238 | &Context->Idents.get("objc_super")); |
| 2239 | QualType argT = Context->getPointerType(Context->getTagDeclType(RD)); |
| 2240 | assert(!argT.isNull() && "Can't build 'struct objc_super *' type"); |
| 2241 | ArgTys.push_back(argT); |
| 2242 | argT = Context->getObjCSelType(); |
| 2243 | assert(!argT.isNull() && "Can't find 'SEL' type"); |
| 2244 | ArgTys.push_back(argT); |
| 2245 | QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(), |
| 2246 | &ArgTys[0], ArgTys.size(), |
| 2247 | true /*isVariadic*/, 0); |
| 2248 | MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl, |
| 2249 | SourceLocation(), |
| 2250 | msgSendIdent, msgSendType, 0, |
| 2251 | FunctionDecl::Extern, false); |
| 2252 | } |
| 2253 | |
| 2254 | // SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...); |
| 2255 | void RewriteObjC::SynthMsgSendStretFunctionDecl() { |
| 2256 | IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret"); |
| 2257 | llvm::SmallVector<QualType, 16> ArgTys; |
| 2258 | QualType argT = Context->getObjCIdType(); |
| 2259 | assert(!argT.isNull() && "Can't find 'id' type"); |
| 2260 | ArgTys.push_back(argT); |
| 2261 | argT = Context->getObjCSelType(); |
| 2262 | assert(!argT.isNull() && "Can't find 'SEL' type"); |
| 2263 | ArgTys.push_back(argT); |
| 2264 | QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(), |
| 2265 | &ArgTys[0], ArgTys.size(), |
| 2266 | true /*isVariadic*/, 0); |
| 2267 | MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl, |
| 2268 | SourceLocation(), |
| 2269 | msgSendIdent, msgSendType, 0, |
| 2270 | FunctionDecl::Extern, false); |
| 2271 | } |
| 2272 | |
| 2273 | // SynthMsgSendSuperStretFunctionDecl - |
| 2274 | // id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...); |
| 2275 | void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() { |
| 2276 | IdentifierInfo *msgSendIdent = |
| 2277 | &Context->Idents.get("objc_msgSendSuper_stret"); |
| 2278 | llvm::SmallVector<QualType, 16> ArgTys; |
| 2279 | RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl, |
| 2280 | SourceLocation(), |
| 2281 | &Context->Idents.get("objc_super")); |
| 2282 | QualType argT = Context->getPointerType(Context->getTagDeclType(RD)); |
| 2283 | assert(!argT.isNull() && "Can't build 'struct objc_super *' type"); |
| 2284 | ArgTys.push_back(argT); |
| 2285 | argT = Context->getObjCSelType(); |
| 2286 | assert(!argT.isNull() && "Can't find 'SEL' type"); |
| 2287 | ArgTys.push_back(argT); |
| 2288 | QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(), |
| 2289 | &ArgTys[0], ArgTys.size(), |
| 2290 | true /*isVariadic*/, 0); |
| 2291 | MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl, |
| 2292 | SourceLocation(), |
| 2293 | msgSendIdent, msgSendType, 0, |
| 2294 | FunctionDecl::Extern, false); |
| 2295 | } |
| 2296 | |
| 2297 | // SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...); |
| 2298 | void RewriteObjC::SynthMsgSendFpretFunctionDecl() { |
| 2299 | IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret"); |
| 2300 | llvm::SmallVector<QualType, 16> ArgTys; |
| 2301 | QualType argT = Context->getObjCIdType(); |
| 2302 | assert(!argT.isNull() && "Can't find 'id' type"); |
| 2303 | ArgTys.push_back(argT); |
| 2304 | argT = Context->getObjCSelType(); |
| 2305 | assert(!argT.isNull() && "Can't find 'SEL' type"); |
| 2306 | ArgTys.push_back(argT); |
| 2307 | QualType msgSendType = Context->getFunctionType(Context->DoubleTy, |
| 2308 | &ArgTys[0], ArgTys.size(), |
| 2309 | true /*isVariadic*/, 0); |
| 2310 | MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl, |
| 2311 | SourceLocation(), |
| 2312 | msgSendIdent, msgSendType, 0, |
| 2313 | FunctionDecl::Extern, false); |
| 2314 | } |
| 2315 | |
| 2316 | // SynthGetClassFunctionDecl - id objc_getClass(const char *name); |
| 2317 | void RewriteObjC::SynthGetClassFunctionDecl() { |
| 2318 | IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass"); |
| 2319 | llvm::SmallVector<QualType, 16> ArgTys; |
| 2320 | ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst())); |
| 2321 | QualType getClassType = Context->getFunctionType(Context->getObjCIdType(), |
| 2322 | &ArgTys[0], ArgTys.size(), |
| 2323 | false /*isVariadic*/, 0); |
| 2324 | GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl, |
| 2325 | SourceLocation(), |
| 2326 | getClassIdent, getClassType, 0, |
| 2327 | FunctionDecl::Extern, false); |
| 2328 | } |
| 2329 | |
| 2330 | // SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name); |
| 2331 | void RewriteObjC::SynthGetMetaClassFunctionDecl() { |
| 2332 | IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass"); |
| 2333 | llvm::SmallVector<QualType, 16> ArgTys; |
| 2334 | ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst())); |
| 2335 | QualType getClassType = Context->getFunctionType(Context->getObjCIdType(), |
| 2336 | &ArgTys[0], ArgTys.size(), |
| 2337 | false /*isVariadic*/, 0); |
| 2338 | GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl, |
| 2339 | SourceLocation(), |
| 2340 | getClassIdent, getClassType, 0, |
| 2341 | FunctionDecl::Extern, false); |
| 2342 | } |
| 2343 | |
| 2344 | Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) { |
| 2345 | QualType strType = getConstantStringStructType(); |
| 2346 | |
| 2347 | std::string S = "__NSConstantStringImpl_"; |
| 2348 | |
| 2349 | std::string tmpName = InFileName; |
| 2350 | unsigned i; |
| 2351 | for (i=0; i < tmpName.length(); i++) { |
| 2352 | char c = tmpName.at(i); |
| 2353 | // replace any non alphanumeric characters with '_'. |
| 2354 | if (!isalpha(c) && (c < '0' || c > '9')) |
| 2355 | tmpName[i] = '_'; |
| 2356 | } |
| 2357 | S += tmpName; |
| 2358 | S += "_"; |
| 2359 | S += utostr(NumObjCStringLiterals++); |
| 2360 | |
| 2361 | Preamble += "static __NSConstantStringImpl " + S; |
| 2362 | Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,"; |
| 2363 | Preamble += "0x000007c8,"; // utf8_str |
| 2364 | // The pretty printer for StringLiteral handles escape characters properly. |
| 2365 | std::string prettyBufS; |
| 2366 | llvm::raw_string_ostream prettyBuf(prettyBufS); |
| 2367 | Exp->getString()->printPretty(prettyBuf, *Context, 0, |
| 2368 | PrintingPolicy(LangOpts)); |
| 2369 | Preamble += prettyBuf.str(); |
| 2370 | Preamble += ","; |
| 2371 | Preamble += utostr(Exp->getString()->getByteLength()) + "};\n"; |
| 2372 | |
| 2373 | VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(), |
| 2374 | &Context->Idents.get(S.c_str()), strType, 0, |
| 2375 | VarDecl::Static); |
| 2376 | DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation()); |
| 2377 | Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf, |
| 2378 | Context->getPointerType(DRE->getType()), |
| 2379 | SourceLocation()); |
| 2380 | // cast to NSConstantString * |
| 2381 | CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(), |
| 2382 | CastExpr::CK_Unknown, Unop); |
| 2383 | ReplaceStmt(Exp, cast); |
| 2384 | // delete Exp; leak for now, see RewritePropertySetter() usage for more info. |
| 2385 | return cast; |
| 2386 | } |
| 2387 | |
| 2388 | ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) { |
| 2389 | // check if we are sending a message to 'super' |
| 2390 | if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0; |
| 2391 | |
| 2392 | if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) { |
| 2393 | const ObjCObjectPointerType *OPT = |
| 2394 | Super->getType()->getAs<ObjCObjectPointerType>(); |
| 2395 | assert(OPT); |
| 2396 | const ObjCInterfaceType *IT = OPT->getInterfaceType(); |
| 2397 | return IT->getDecl(); |
| 2398 | } |
| 2399 | return 0; |
| 2400 | } |
| 2401 | |
| 2402 | // struct objc_super { struct objc_object *receiver; struct objc_class *super; }; |
| 2403 | QualType RewriteObjC::getSuperStructType() { |
| 2404 | if (!SuperStructDecl) { |
| 2405 | SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl, |
| 2406 | SourceLocation(), |
| 2407 | &Context->Idents.get("objc_super")); |
| 2408 | QualType FieldTypes[2]; |
| 2409 | |
| 2410 | // struct objc_object *receiver; |
| 2411 | FieldTypes[0] = Context->getObjCIdType(); |
| 2412 | // struct objc_class *super; |
| 2413 | FieldTypes[1] = Context->getObjCClassType(); |
| 2414 | |
| 2415 | // Create fields |
| 2416 | for (unsigned i = 0; i < 2; ++i) { |
| 2417 | SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl, |
| 2418 | SourceLocation(), 0, |
| 2419 | FieldTypes[i], 0, |
| 2420 | /*BitWidth=*/0, |
| 2421 | /*Mutable=*/false)); |
| 2422 | } |
| 2423 | |
| 2424 | SuperStructDecl->completeDefinition(*Context); |
| 2425 | } |
| 2426 | return Context->getTagDeclType(SuperStructDecl); |
| 2427 | } |
| 2428 | |
| 2429 | QualType RewriteObjC::getConstantStringStructType() { |
| 2430 | if (!ConstantStringDecl) { |
| 2431 | ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl, |
| 2432 | SourceLocation(), |
| 2433 | &Context->Idents.get("__NSConstantStringImpl")); |
| 2434 | QualType FieldTypes[4]; |
| 2435 | |
| 2436 | // struct objc_object *receiver; |
| 2437 | FieldTypes[0] = Context->getObjCIdType(); |
| 2438 | // int flags; |
| 2439 | FieldTypes[1] = Context->IntTy; |
| 2440 | // char *str; |
| 2441 | FieldTypes[2] = Context->getPointerType(Context->CharTy); |
| 2442 | // long length; |
| 2443 | FieldTypes[3] = Context->LongTy; |
| 2444 | |
| 2445 | // Create fields |
| 2446 | for (unsigned i = 0; i < 4; ++i) { |
| 2447 | ConstantStringDecl->addDecl(FieldDecl::Create(*Context, |
| 2448 | ConstantStringDecl, |
| 2449 | SourceLocation(), 0, |
| 2450 | FieldTypes[i], 0, |
| 2451 | /*BitWidth=*/0, |
| 2452 | /*Mutable=*/true)); |
| 2453 | } |
| 2454 | |
| 2455 | ConstantStringDecl->completeDefinition(*Context); |
| 2456 | } |
| 2457 | return Context->getTagDeclType(ConstantStringDecl); |
| 2458 | } |
| 2459 | |
| 2460 | Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) { |
| 2461 | if (!SelGetUidFunctionDecl) |
| 2462 | SynthSelGetUidFunctionDecl(); |
| 2463 | if (!MsgSendFunctionDecl) |
| 2464 | SynthMsgSendFunctionDecl(); |
| 2465 | if (!MsgSendSuperFunctionDecl) |
| 2466 | SynthMsgSendSuperFunctionDecl(); |
| 2467 | if (!MsgSendStretFunctionDecl) |
| 2468 | SynthMsgSendStretFunctionDecl(); |
| 2469 | if (!MsgSendSuperStretFunctionDecl) |
| 2470 | SynthMsgSendSuperStretFunctionDecl(); |
| 2471 | if (!MsgSendFpretFunctionDecl) |
| 2472 | SynthMsgSendFpretFunctionDecl(); |
| 2473 | if (!GetClassFunctionDecl) |
| 2474 | SynthGetClassFunctionDecl(); |
| 2475 | if (!GetMetaClassFunctionDecl) |
| 2476 | SynthGetMetaClassFunctionDecl(); |
| 2477 | |
| 2478 | // default to objc_msgSend(). |
| 2479 | FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl; |
| 2480 | // May need to use objc_msgSend_stret() as well. |
| 2481 | FunctionDecl *MsgSendStretFlavor = 0; |
| 2482 | if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) { |
| 2483 | QualType resultType = mDecl->getResultType(); |
| 2484 | if (resultType->isStructureType() || resultType->isUnionType()) |
| 2485 | MsgSendStretFlavor = MsgSendStretFunctionDecl; |
| 2486 | else if (resultType->isRealFloatingType()) |
| 2487 | MsgSendFlavor = MsgSendFpretFunctionDecl; |
| 2488 | } |
| 2489 | |
| 2490 | // Synthesize a call to objc_msgSend(). |
| 2491 | llvm::SmallVector<Expr*, 8> MsgExprs; |
| 2492 | IdentifierInfo *clsName = Exp->getClassName(); |
| 2493 | |
| 2494 | // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend(). |
| 2495 | if (clsName) { // class message. |
| 2496 | // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle |
| 2497 | // the 'super' idiom within a class method. |
| 2498 | if (clsName->getName() == "super") { |
| 2499 | MsgSendFlavor = MsgSendSuperFunctionDecl; |
| 2500 | if (MsgSendStretFlavor) |
| 2501 | MsgSendStretFlavor = MsgSendSuperStretFunctionDecl; |
| 2502 | assert(MsgSendFlavor && "MsgSendFlavor is NULL!"); |
| 2503 | |
| 2504 | ObjCInterfaceDecl *SuperDecl = |
| 2505 | CurMethodDef->getClassInterface()->getSuperClass(); |
| 2506 | |
| 2507 | llvm::SmallVector<Expr*, 4> InitExprs; |
| 2508 | |
| 2509 | // set the receiver to self, the first argument to all methods. |
| 2510 | InitExprs.push_back( |
| 2511 | NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(), |
| 2512 | CastExpr::CK_Unknown, |
| 2513 | new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(), |
| 2514 | Context->getObjCIdType(), |
| 2515 | SourceLocation())) |
| 2516 | ); // set the 'receiver'. |
| 2517 | |
| 2518 | llvm::SmallVector<Expr*, 8> ClsExprs; |
| 2519 | QualType argType = Context->getPointerType(Context->CharTy); |
| 2520 | ClsExprs.push_back(StringLiteral::Create(*Context, |
| 2521 | SuperDecl->getIdentifier()->getNameStart(), |
| 2522 | SuperDecl->getIdentifier()->getLength(), |
| 2523 | false, argType, SourceLocation())); |
| 2524 | CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl, |
| 2525 | &ClsExprs[0], |
| 2526 | ClsExprs.size()); |
| 2527 | // To turn off a warning, type-cast to 'id' |
| 2528 | InitExprs.push_back( // set 'super class', using objc_getClass(). |
| 2529 | NoTypeInfoCStyleCastExpr(Context, |
| 2530 | Context->getObjCIdType(), |
| 2531 | CastExpr::CK_Unknown, Cls)); |
| 2532 | // struct objc_super |
| 2533 | QualType superType = getSuperStructType(); |
| 2534 | Expr *SuperRep; |
| 2535 | |
| 2536 | if (LangOpts.Microsoft) { |
| 2537 | SynthSuperContructorFunctionDecl(); |
| 2538 | // Simulate a contructor call... |
| 2539 | DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl, |
| 2540 | superType, SourceLocation()); |
| 2541 | SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], |
| 2542 | InitExprs.size(), |
| 2543 | superType, SourceLocation()); |
| 2544 | // The code for super is a little tricky to prevent collision with |
| 2545 | // the structure definition in the header. The rewriter has it's own |
| 2546 | // internal definition (__rw_objc_super) that is uses. This is why |
| 2547 | // we need the cast below. For example: |
| 2548 | // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER")) |
| 2549 | // |
| 2550 | SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf, |
| 2551 | Context->getPointerType(SuperRep->getType()), |
| 2552 | SourceLocation()); |
| 2553 | SuperRep = NoTypeInfoCStyleCastExpr(Context, |
| 2554 | Context->getPointerType(superType), |
| 2555 | CastExpr::CK_Unknown, SuperRep); |
| 2556 | } else { |
| 2557 | // (struct objc_super) { <exprs from above> } |
| 2558 | InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(), |
| 2559 | &InitExprs[0], InitExprs.size(), |
| 2560 | SourceLocation()); |
| 2561 | TypeSourceInfo *superTInfo |
| 2562 | = Context->getTrivialTypeSourceInfo(superType); |
| 2563 | SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo, |
| 2564 | superType, ILE, false); |
| 2565 | // struct objc_super * |
| 2566 | SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf, |
| 2567 | Context->getPointerType(SuperRep->getType()), |
| 2568 | SourceLocation()); |
| 2569 | } |
| 2570 | MsgExprs.push_back(SuperRep); |
| 2571 | } else { |
| 2572 | llvm::SmallVector<Expr*, 8> ClsExprs; |
| 2573 | QualType argType = Context->getPointerType(Context->CharTy); |
| 2574 | ClsExprs.push_back(StringLiteral::Create(*Context, |
| 2575 | clsName->getNameStart(), |
| 2576 | clsName->getLength(), |
| 2577 | false, argType, |
| 2578 | SourceLocation())); |
| 2579 | CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, |
| 2580 | &ClsExprs[0], |
| 2581 | ClsExprs.size()); |
| 2582 | MsgExprs.push_back(Cls); |
| 2583 | } |
| 2584 | } else { // instance message. |
| 2585 | Expr *recExpr = Exp->getReceiver(); |
| 2586 | |
| 2587 | if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) { |
| 2588 | MsgSendFlavor = MsgSendSuperFunctionDecl; |
| 2589 | if (MsgSendStretFlavor) |
| 2590 | MsgSendStretFlavor = MsgSendSuperStretFunctionDecl; |
| 2591 | assert(MsgSendFlavor && "MsgSendFlavor is NULL!"); |
| 2592 | |
| 2593 | llvm::SmallVector<Expr*, 4> InitExprs; |
| 2594 | |
| 2595 | InitExprs.push_back( |
| 2596 | NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(), |
| 2597 | CastExpr::CK_Unknown, |
| 2598 | new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(), |
| 2599 | Context->getObjCIdType(), |
| 2600 | SourceLocation())) |
| 2601 | ); // set the 'receiver'. |
| 2602 | |
| 2603 | llvm::SmallVector<Expr*, 8> ClsExprs; |
| 2604 | QualType argType = Context->getPointerType(Context->CharTy); |
| 2605 | ClsExprs.push_back(StringLiteral::Create(*Context, |
| 2606 | SuperDecl->getIdentifier()->getNameStart(), |
| 2607 | SuperDecl->getIdentifier()->getLength(), |
| 2608 | false, argType, SourceLocation())); |
| 2609 | CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, |
| 2610 | &ClsExprs[0], |
| 2611 | ClsExprs.size()); |
| 2612 | // To turn off a warning, type-cast to 'id' |
| 2613 | InitExprs.push_back( |
| 2614 | // set 'super class', using objc_getClass(). |
| 2615 | NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(), |
| 2616 | CastExpr::CK_Unknown, Cls)); |
| 2617 | // struct objc_super |
| 2618 | QualType superType = getSuperStructType(); |
| 2619 | Expr *SuperRep; |
| 2620 | |
| 2621 | if (LangOpts.Microsoft) { |
| 2622 | SynthSuperContructorFunctionDecl(); |
| 2623 | // Simulate a contructor call... |
| 2624 | DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl, |
| 2625 | superType, SourceLocation()); |
| 2626 | SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], |
| 2627 | InitExprs.size(), |
| 2628 | superType, SourceLocation()); |
| 2629 | // The code for super is a little tricky to prevent collision with |
| 2630 | // the structure definition in the header. The rewriter has it's own |
| 2631 | // internal definition (__rw_objc_super) that is uses. This is why |
| 2632 | // we need the cast below. For example: |
| 2633 | // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER")) |
| 2634 | // |
| 2635 | SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf, |
| 2636 | Context->getPointerType(SuperRep->getType()), |
| 2637 | SourceLocation()); |
| 2638 | SuperRep = NoTypeInfoCStyleCastExpr(Context, |
| 2639 | Context->getPointerType(superType), |
| 2640 | CastExpr::CK_Unknown, SuperRep); |
| 2641 | } else { |
| 2642 | // (struct objc_super) { <exprs from above> } |
| 2643 | InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(), |
| 2644 | &InitExprs[0], InitExprs.size(), |
| 2645 | SourceLocation()); |
| 2646 | TypeSourceInfo *superTInfo |
| 2647 | = Context->getTrivialTypeSourceInfo(superType); |
| 2648 | SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo, |
| 2649 | superType, ILE, false); |
| 2650 | } |
| 2651 | MsgExprs.push_back(SuperRep); |
| 2652 | } else { |
| 2653 | // Remove all type-casts because it may contain objc-style types; e.g. |
| 2654 | // Foo<Proto> *. |
| 2655 | while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr)) |
| 2656 | recExpr = CE->getSubExpr(); |
| 2657 | recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(), |
| 2658 | CastExpr::CK_Unknown, recExpr); |
| 2659 | MsgExprs.push_back(recExpr); |
| 2660 | } |
| 2661 | } |
| 2662 | // Create a call to sel_registerName("selName"), it will be the 2nd argument. |
| 2663 | llvm::SmallVector<Expr*, 8> SelExprs; |
| 2664 | QualType argType = Context->getPointerType(Context->CharTy); |
| 2665 | SelExprs.push_back(StringLiteral::Create(*Context, |
| 2666 | Exp->getSelector().getAsString().c_str(), |
| 2667 | Exp->getSelector().getAsString().size(), |
| 2668 | false, argType, SourceLocation())); |
| 2669 | CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl, |
| 2670 | &SelExprs[0], SelExprs.size()); |
| 2671 | MsgExprs.push_back(SelExp); |
| 2672 | |
| 2673 | // Now push any user supplied arguments. |
| 2674 | for (unsigned i = 0; i < Exp->getNumArgs(); i++) { |
| 2675 | Expr *userExpr = Exp->getArg(i); |
| 2676 | // Make all implicit casts explicit...ICE comes in handy:-) |
| 2677 | if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) { |
| 2678 | // Reuse the ICE type, it is exactly what the doctor ordered. |
| 2679 | QualType type = ICE->getType()->isObjCQualifiedIdType() |
| 2680 | ? Context->getObjCIdType() |
| 2681 | : ICE->getType(); |
| 2682 | userExpr = NoTypeInfoCStyleCastExpr(Context, type, CastExpr::CK_Unknown, |
| 2683 | userExpr); |
| 2684 | } |
| 2685 | // Make id<P...> cast into an 'id' cast. |
| 2686 | else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) { |
| 2687 | if (CE->getType()->isObjCQualifiedIdType()) { |
| 2688 | while ((CE = dyn_cast<CStyleCastExpr>(userExpr))) |
| 2689 | userExpr = CE->getSubExpr(); |
| 2690 | userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(), |
| 2691 | CastExpr::CK_Unknown, userExpr); |
| 2692 | } |
| 2693 | } |
| 2694 | MsgExprs.push_back(userExpr); |
| 2695 | // We've transferred the ownership to MsgExprs. For now, we *don't* null |
| 2696 | // out the argument in the original expression (since we aren't deleting |
| 2697 | // the ObjCMessageExpr). See RewritePropertySetter() usage for more info. |
| 2698 | //Exp->setArg(i, 0); |
| 2699 | } |
| 2700 | // Generate the funky cast. |
| 2701 | CastExpr *cast; |
| 2702 | llvm::SmallVector<QualType, 8> ArgTypes; |
| 2703 | QualType returnType; |
| 2704 | |
| 2705 | // Push 'id' and 'SEL', the 2 implicit arguments. |
| 2706 | if (MsgSendFlavor == MsgSendSuperFunctionDecl) |
| 2707 | ArgTypes.push_back(Context->getPointerType(getSuperStructType())); |
| 2708 | else |
| 2709 | ArgTypes.push_back(Context->getObjCIdType()); |
| 2710 | ArgTypes.push_back(Context->getObjCSelType()); |
| 2711 | if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) { |
| 2712 | // Push any user argument types. |
| 2713 | for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(), |
| 2714 | E = OMD->param_end(); PI != E; ++PI) { |
| 2715 | QualType t = (*PI)->getType()->isObjCQualifiedIdType() |
| 2716 | ? Context->getObjCIdType() |
| 2717 | : (*PI)->getType(); |
| 2718 | // Make sure we convert "t (^)(...)" to "t (*)(...)". |
| 2719 | if (isTopLevelBlockPointerType(t)) { |
| 2720 | const BlockPointerType *BPT = t->getAs<BlockPointerType>(); |
| 2721 | t = Context->getPointerType(BPT->getPointeeType()); |
| 2722 | } |
| 2723 | ArgTypes.push_back(t); |
| 2724 | } |
| 2725 | returnType = OMD->getResultType()->isObjCQualifiedIdType() |
| 2726 | ? Context->getObjCIdType() : OMD->getResultType(); |
| 2727 | } else { |
| 2728 | returnType = Context->getObjCIdType(); |
| 2729 | } |
| 2730 | // Get the type, we will need to reference it in a couple spots. |
| 2731 | QualType msgSendType = MsgSendFlavor->getType(); |
| 2732 | |
| 2733 | // Create a reference to the objc_msgSend() declaration. |
| 2734 | DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType, |
| 2735 | SourceLocation()); |
| 2736 | |
| 2737 | // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid). |
| 2738 | // If we don't do this cast, we get the following bizarre warning/note: |
| 2739 | // xx.m:13: warning: function called through a non-compatible type |
| 2740 | // xx.m:13: note: if this code is reached, the program will abort |
| 2741 | cast = NoTypeInfoCStyleCastExpr(Context, |
| 2742 | Context->getPointerType(Context->VoidTy), |
| 2743 | CastExpr::CK_Unknown, DRE); |
| 2744 | |
| 2745 | // Now do the "normal" pointer to function cast. |
| 2746 | QualType castType = Context->getFunctionType(returnType, |
| 2747 | &ArgTypes[0], ArgTypes.size(), |
| 2748 | // If we don't have a method decl, force a variadic cast. |
| 2749 | Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0); |
| 2750 | castType = Context->getPointerType(castType); |
| 2751 | cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown, |
| 2752 | cast); |
| 2753 | |
| 2754 | // Don't forget the parens to enforce the proper binding. |
| 2755 | ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast); |
| 2756 | |
| 2757 | const FunctionType *FT = msgSendType->getAs<FunctionType>(); |
| 2758 | CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0], |
| 2759 | MsgExprs.size(), |
| 2760 | FT->getResultType(), SourceLocation()); |
| 2761 | Stmt *ReplacingStmt = CE; |
| 2762 | if (MsgSendStretFlavor) { |
| 2763 | // We have the method which returns a struct/union. Must also generate |
| 2764 | // call to objc_msgSend_stret and hang both varieties on a conditional |
| 2765 | // expression which dictate which one to envoke depending on size of |
| 2766 | // method's return type. |
| 2767 | |
| 2768 | // Create a reference to the objc_msgSend_stret() declaration. |
| 2769 | DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType, |
| 2770 | SourceLocation()); |
| 2771 | // Need to cast objc_msgSend_stret to "void *" (see above comment). |
| 2772 | cast = NoTypeInfoCStyleCastExpr(Context, |
| 2773 | Context->getPointerType(Context->VoidTy), |
| 2774 | CastExpr::CK_Unknown, STDRE); |
| 2775 | // Now do the "normal" pointer to function cast. |
| 2776 | castType = Context->getFunctionType(returnType, |
| 2777 | &ArgTypes[0], ArgTypes.size(), |
| 2778 | Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0); |
| 2779 | castType = Context->getPointerType(castType); |
| 2780 | cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown, |
| 2781 | cast); |
| 2782 | |
| 2783 | // Don't forget the parens to enforce the proper binding. |
| 2784 | PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast); |
| 2785 | |
| 2786 | FT = msgSendType->getAs<FunctionType>(); |
| 2787 | CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0], |
| 2788 | MsgExprs.size(), |
| 2789 | FT->getResultType(), SourceLocation()); |
| 2790 | |
| 2791 | // Build sizeof(returnType) |
| 2792 | SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true, |
| 2793 | Context->getTrivialTypeSourceInfo(returnType), |
| 2794 | Context->getSizeType(), |
| 2795 | SourceLocation(), SourceLocation()); |
| 2796 | // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...)) |
| 2797 | // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases. |
| 2798 | // For X86 it is more complicated and some kind of target specific routine |
| 2799 | // is needed to decide what to do. |
| 2800 | unsigned IntSize = |
| 2801 | static_cast<unsigned>(Context->getTypeSize(Context->IntTy)); |
| 2802 | IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8), |
| 2803 | Context->IntTy, |
| 2804 | SourceLocation()); |
| 2805 | BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit, |
| 2806 | BinaryOperator::LE, |
| 2807 | Context->IntTy, |
| 2808 | SourceLocation()); |
| 2809 | // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...)) |
| 2810 | ConditionalOperator *CondExpr = |
| 2811 | new (Context) ConditionalOperator(lessThanExpr, |
| 2812 | SourceLocation(), CE, |
| 2813 | SourceLocation(), STCE, returnType); |
| 2814 | ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr); |
| 2815 | } |
| 2816 | // delete Exp; leak for now, see RewritePropertySetter() usage for more info. |
| 2817 | return ReplacingStmt; |
| 2818 | } |
| 2819 | |
| 2820 | Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) { |
| 2821 | Stmt *ReplacingStmt = SynthMessageExpr(Exp); |
| 2822 | |
| 2823 | // Now do the actual rewrite. |
| 2824 | ReplaceStmt(Exp, ReplacingStmt); |
| 2825 | |
| 2826 | // delete Exp; leak for now, see RewritePropertySetter() usage for more info. |
| 2827 | return ReplacingStmt; |
| 2828 | } |
| 2829 | |
| 2830 | // typedef struct objc_object Protocol; |
| 2831 | QualType RewriteObjC::getProtocolType() { |
| 2832 | if (!ProtocolTypeDecl) { |
| 2833 | TypeSourceInfo *TInfo |
| 2834 | = Context->getTrivialTypeSourceInfo(Context->getObjCIdType()); |
| 2835 | ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl, |
| 2836 | SourceLocation(), |
| 2837 | &Context->Idents.get("Protocol"), |
| 2838 | TInfo); |
| 2839 | } |
| 2840 | return Context->getTypeDeclType(ProtocolTypeDecl); |
| 2841 | } |
| 2842 | |
| 2843 | /// RewriteObjCProtocolExpr - Rewrite a protocol expression into |
| 2844 | /// a synthesized/forward data reference (to the protocol's metadata). |
| 2845 | /// The forward references (and metadata) are generated in |
| 2846 | /// RewriteObjC::HandleTranslationUnit(). |
| 2847 | Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) { |
| 2848 | std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString(); |
| 2849 | IdentifierInfo *ID = &Context->Idents.get(Name); |
| 2850 | VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(), |
| 2851 | ID, getProtocolType(), 0, VarDecl::Extern); |
| 2852 | DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation()); |
| 2853 | Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf, |
| 2854 | Context->getPointerType(DRE->getType()), |
| 2855 | SourceLocation()); |
| 2856 | CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(), |
| 2857 | CastExpr::CK_Unknown, |
| 2858 | DerefExpr); |
| 2859 | ReplaceStmt(Exp, castExpr); |
| 2860 | ProtocolExprDecls.insert(Exp->getProtocol()); |
| 2861 | // delete Exp; leak for now, see RewritePropertySetter() usage for more info. |
| 2862 | return castExpr; |
| 2863 | |
| 2864 | } |
| 2865 | |
| 2866 | bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf, |
| 2867 | const char *endBuf) { |
| 2868 | while (startBuf < endBuf) { |
| 2869 | if (*startBuf == '#') { |
| 2870 | // Skip whitespace. |
| 2871 | for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf) |
| 2872 | ; |
| 2873 | if (!strncmp(startBuf, "if", strlen("if")) || |
| 2874 | !strncmp(startBuf, "ifdef", strlen("ifdef")) || |
| 2875 | !strncmp(startBuf, "ifndef", strlen("ifndef")) || |
| 2876 | !strncmp(startBuf, "define", strlen("define")) || |
| 2877 | !strncmp(startBuf, "undef", strlen("undef")) || |
| 2878 | !strncmp(startBuf, "else", strlen("else")) || |
| 2879 | !strncmp(startBuf, "elif", strlen("elif")) || |
| 2880 | !strncmp(startBuf, "endif", strlen("endif")) || |
| 2881 | !strncmp(startBuf, "pragma", strlen("pragma")) || |
| 2882 | !strncmp(startBuf, "include", strlen("include")) || |
| 2883 | !strncmp(startBuf, "import", strlen("import")) || |
| 2884 | !strncmp(startBuf, "include_next", strlen("include_next"))) |
| 2885 | return true; |
| 2886 | } |
| 2887 | startBuf++; |
| 2888 | } |
| 2889 | return false; |
| 2890 | } |
| 2891 | |
| 2892 | /// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to |
| 2893 | /// an objective-c class with ivars. |
| 2894 | void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl, |
| 2895 | std::string &Result) { |
| 2896 | assert(CDecl && "Class missing in SynthesizeObjCInternalStruct"); |
| 2897 | assert(CDecl->getNameAsCString() && |
| 2898 | "Name missing in SynthesizeObjCInternalStruct"); |
| 2899 | // Do not synthesize more than once. |
| 2900 | if (ObjCSynthesizedStructs.count(CDecl)) |
| 2901 | return; |
| 2902 | ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass(); |
| 2903 | int NumIvars = CDecl->ivar_size(); |
| 2904 | SourceLocation LocStart = CDecl->getLocStart(); |
| 2905 | SourceLocation LocEnd = CDecl->getLocEnd(); |
| 2906 | |
| 2907 | const char *startBuf = SM->getCharacterData(LocStart); |
| 2908 | const char *endBuf = SM->getCharacterData(LocEnd); |
| 2909 | |
| 2910 | // If no ivars and no root or if its root, directly or indirectly, |
| 2911 | // have no ivars (thus not synthesized) then no need to synthesize this class. |
| 2912 | if ((CDecl->isForwardDecl() || NumIvars == 0) && |
| 2913 | (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) { |
| 2914 | endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts); |
| 2915 | ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size()); |
| 2916 | return; |
| 2917 | } |
| 2918 | |
| 2919 | // FIXME: This has potential of causing problem. If |
| 2920 | // SynthesizeObjCInternalStruct is ever called recursively. |
| 2921 | Result += "\nstruct "; |
| 2922 | Result += CDecl->getNameAsString(); |
| 2923 | if (LangOpts.Microsoft) |
| 2924 | Result += "_IMPL"; |
| 2925 | |
| 2926 | if (NumIvars > 0) { |
| 2927 | const char *cursor = strchr(startBuf, '{'); |
| 2928 | assert((cursor && endBuf) |
| 2929 | && "SynthesizeObjCInternalStruct - malformed @interface"); |
| 2930 | // If the buffer contains preprocessor directives, we do more fine-grained |
| 2931 | // rewrites. This is intended to fix code that looks like (which occurs in |
| 2932 | // NSURL.h, for example): |
| 2933 | // |
| 2934 | // #ifdef XYZ |
| 2935 | // @interface Foo : NSObject |
| 2936 | // #else |
| 2937 | // @interface FooBar : NSObject |
| 2938 | // #endif |
| 2939 | // { |
| 2940 | // int i; |
| 2941 | // } |
| 2942 | // @end |
| 2943 | // |
| 2944 | // This clause is segregated to avoid breaking the common case. |
| 2945 | if (BufferContainsPPDirectives(startBuf, cursor)) { |
| 2946 | SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() : |
| 2947 | CDecl->getClassLoc(); |
| 2948 | const char *endHeader = SM->getCharacterData(L); |
| 2949 | endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts); |
| 2950 | |
| 2951 | if (CDecl->protocol_begin() != CDecl->protocol_end()) { |
| 2952 | // advance to the end of the referenced protocols. |
| 2953 | while (endHeader < cursor && *endHeader != '>') endHeader++; |
| 2954 | endHeader++; |
| 2955 | } |
| 2956 | // rewrite the original header |
| 2957 | ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size()); |
| 2958 | } else { |
| 2959 | // rewrite the original header *without* disturbing the '{' |
| 2960 | ReplaceText(LocStart, cursor-startBuf, Result.c_str(), Result.size()); |
| 2961 | } |
| 2962 | if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) { |
| 2963 | Result = "\n struct "; |
| 2964 | Result += RCDecl->getNameAsString(); |
| 2965 | Result += "_IMPL "; |
| 2966 | Result += RCDecl->getNameAsString(); |
| 2967 | Result += "_IVARS;\n"; |
| 2968 | |
| 2969 | // insert the super class structure definition. |
| 2970 | SourceLocation OnePastCurly = |
| 2971 | LocStart.getFileLocWithOffset(cursor-startBuf+1); |
| 2972 | InsertText(OnePastCurly, Result.c_str(), Result.size()); |
| 2973 | } |
| 2974 | cursor++; // past '{' |
| 2975 | |
| 2976 | // Now comment out any visibility specifiers. |
| 2977 | while (cursor < endBuf) { |
| 2978 | if (*cursor == '@') { |
| 2979 | SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf); |
| 2980 | // Skip whitespace. |
| 2981 | for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor) |
| 2982 | /*scan*/; |
| 2983 | |
| 2984 | // FIXME: presence of @public, etc. inside comment results in |
| 2985 | // this transformation as well, which is still correct c-code. |
| 2986 | if (!strncmp(cursor, "public", strlen("public")) || |
| 2987 | !strncmp(cursor, "private", strlen("private")) || |
| 2988 | !strncmp(cursor, "package", strlen("package")) || |
| 2989 | !strncmp(cursor, "protected", strlen("protected"))) |
| 2990 | InsertText(atLoc, "// ", 3); |
| 2991 | } |
| 2992 | // FIXME: If there are cases where '<' is used in ivar declaration part |
| 2993 | // of user code, then scan the ivar list and use needToScanForQualifiers |
| 2994 | // for type checking. |
| 2995 | else if (*cursor == '<') { |
| 2996 | SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf); |
| 2997 | InsertText(atLoc, "/* ", 3); |
| 2998 | cursor = strchr(cursor, '>'); |
| 2999 | cursor++; |
| 3000 | atLoc = LocStart.getFileLocWithOffset(cursor-startBuf); |
| 3001 | InsertText(atLoc, " */", 3); |
| 3002 | } else if (*cursor == '^') { // rewrite block specifier. |
| 3003 | SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf); |
| 3004 | ReplaceText(caretLoc, 1, "*", 1); |
| 3005 | } |
| 3006 | cursor++; |
| 3007 | } |
| 3008 | // Don't forget to add a ';'!! |
| 3009 | InsertText(LocEnd.getFileLocWithOffset(1), ";", 1); |
| 3010 | } else { // we don't have any instance variables - insert super struct. |
| 3011 | endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts); |
| 3012 | Result += " {\n struct "; |
| 3013 | Result += RCDecl->getNameAsString(); |
| 3014 | Result += "_IMPL "; |
| 3015 | Result += RCDecl->getNameAsString(); |
| 3016 | Result += "_IVARS;\n};\n"; |
| 3017 | ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size()); |
| 3018 | } |
| 3019 | // Mark this struct as having been generated. |
| 3020 | if (!ObjCSynthesizedStructs.insert(CDecl)) |
| 3021 | assert(false && "struct already synthesize- SynthesizeObjCInternalStruct"); |
| 3022 | } |
| 3023 | |
| 3024 | // RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or |
| 3025 | /// class methods. |
| 3026 | template<typename MethodIterator> |
| 3027 | void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin, |
| 3028 | MethodIterator MethodEnd, |
| 3029 | bool IsInstanceMethod, |
| 3030 | const char *prefix, |
| 3031 | const char *ClassName, |
| 3032 | std::string &Result) { |
| 3033 | if (MethodBegin == MethodEnd) return; |
| 3034 | |
| 3035 | if (!objc_impl_method) { |
| 3036 | /* struct _objc_method { |
| 3037 | SEL _cmd; |
| 3038 | char *method_types; |
| 3039 | void *_imp; |
| 3040 | } |
| 3041 | */ |
| 3042 | Result += "\nstruct _objc_method {\n"; |
| 3043 | Result += "\tSEL _cmd;\n"; |
| 3044 | Result += "\tchar *method_types;\n"; |
| 3045 | Result += "\tvoid *_imp;\n"; |
| 3046 | Result += "};\n"; |
| 3047 | |
| 3048 | objc_impl_method = true; |
| 3049 | } |
| 3050 | |
| 3051 | // Build _objc_method_list for class's methods if needed |
| 3052 | |
| 3053 | /* struct { |
| 3054 | struct _objc_method_list *next_method; |
| 3055 | int method_count; |
| 3056 | struct _objc_method method_list[]; |
| 3057 | } |
| 3058 | */ |
| 3059 | unsigned NumMethods = std::distance(MethodBegin, MethodEnd); |
| 3060 | Result += "\nstatic struct {\n"; |
| 3061 | Result += "\tstruct _objc_method_list *next_method;\n"; |
| 3062 | Result += "\tint method_count;\n"; |
| 3063 | Result += "\tstruct _objc_method method_list["; |
| 3064 | Result += utostr(NumMethods); |
| 3065 | Result += "];\n} _OBJC_"; |
| 3066 | Result += prefix; |
| 3067 | Result += IsInstanceMethod ? "INSTANCE" : "CLASS"; |
| 3068 | Result += "_METHODS_"; |
| 3069 | Result += ClassName; |
| 3070 | Result += " __attribute__ ((used, section (\"__OBJC, __"; |
| 3071 | Result += IsInstanceMethod ? "inst" : "cls"; |
| 3072 | Result += "_meth\")))= "; |
| 3073 | Result += "{\n\t0, " + utostr(NumMethods) + "\n"; |
| 3074 | |
| 3075 | Result += "\t,{{(SEL)\""; |
| 3076 | Result += (*MethodBegin)->getSelector().getAsString().c_str(); |
| 3077 | std::string MethodTypeString; |
| 3078 | Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString); |
| 3079 | Result += "\", \""; |
| 3080 | Result += MethodTypeString; |
| 3081 | Result += "\", (void *)"; |
| 3082 | Result += MethodInternalNames[*MethodBegin]; |
| 3083 | Result += "}\n"; |
| 3084 | for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) { |
| 3085 | Result += "\t ,{(SEL)\""; |
| 3086 | Result += (*MethodBegin)->getSelector().getAsString().c_str(); |
| 3087 | std::string MethodTypeString; |
| 3088 | Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString); |
| 3089 | Result += "\", \""; |
| 3090 | Result += MethodTypeString; |
| 3091 | Result += "\", (void *)"; |
| 3092 | Result += MethodInternalNames[*MethodBegin]; |
| 3093 | Result += "}\n"; |
| 3094 | } |
| 3095 | Result += "\t }\n};\n"; |
| 3096 | } |
| 3097 | |
| 3098 | /// RewriteObjCProtocolMetaData - Rewrite protocols meta-data. |
| 3099 | void RewriteObjC:: |
| 3100 | RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix, |
| 3101 | const char *ClassName, std::string &Result) { |
| 3102 | static bool objc_protocol_methods = false; |
| 3103 | |
| 3104 | // Output struct protocol_methods holder of method selector and type. |
| 3105 | if (!objc_protocol_methods && !PDecl->isForwardDecl()) { |
| 3106 | /* struct protocol_methods { |
| 3107 | SEL _cmd; |
| 3108 | char *method_types; |
| 3109 | } |
| 3110 | */ |
| 3111 | Result += "\nstruct _protocol_methods {\n"; |
| 3112 | Result += "\tstruct objc_selector *_cmd;\n"; |
| 3113 | Result += "\tchar *method_types;\n"; |
| 3114 | Result += "};\n"; |
| 3115 | |
| 3116 | objc_protocol_methods = true; |
| 3117 | } |
| 3118 | // Do not synthesize the protocol more than once. |
| 3119 | if (ObjCSynthesizedProtocols.count(PDecl)) |
| 3120 | return; |
| 3121 | |
| 3122 | if (PDecl->instmeth_begin() != PDecl->instmeth_end()) { |
| 3123 | unsigned NumMethods = std::distance(PDecl->instmeth_begin(), |
| 3124 | PDecl->instmeth_end()); |
| 3125 | /* struct _objc_protocol_method_list { |
| 3126 | int protocol_method_count; |
| 3127 | struct protocol_methods protocols[]; |
| 3128 | } |
| 3129 | */ |
| 3130 | Result += "\nstatic struct {\n"; |
| 3131 | Result += "\tint protocol_method_count;\n"; |
| 3132 | Result += "\tstruct _protocol_methods protocol_methods["; |
| 3133 | Result += utostr(NumMethods); |
| 3134 | Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_"; |
| 3135 | Result += PDecl->getNameAsString(); |
| 3136 | Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= " |
| 3137 | "{\n\t" + utostr(NumMethods) + "\n"; |
| 3138 | |
| 3139 | // Output instance methods declared in this protocol. |
| 3140 | for (ObjCProtocolDecl::instmeth_iterator |
| 3141 | I = PDecl->instmeth_begin(), E = PDecl->instmeth_end(); |
| 3142 | I != E; ++I) { |
| 3143 | if (I == PDecl->instmeth_begin()) |
| 3144 | Result += "\t ,{{(struct objc_selector *)\""; |
| 3145 | else |
| 3146 | Result += "\t ,{(struct objc_selector *)\""; |
| 3147 | Result += (*I)->getSelector().getAsString().c_str(); |
| 3148 | std::string MethodTypeString; |
| 3149 | Context->getObjCEncodingForMethodDecl((*I), MethodTypeString); |
| 3150 | Result += "\", \""; |
| 3151 | Result += MethodTypeString; |
| 3152 | Result += "\"}\n"; |
| 3153 | } |
| 3154 | Result += "\t }\n};\n"; |
| 3155 | } |
| 3156 | |
| 3157 | // Output class methods declared in this protocol. |
| 3158 | unsigned NumMethods = std::distance(PDecl->classmeth_begin(), |
| 3159 | PDecl->classmeth_end()); |
| 3160 | if (NumMethods > 0) { |
| 3161 | /* struct _objc_protocol_method_list { |
| 3162 | int protocol_method_count; |
| 3163 | struct protocol_methods protocols[]; |
| 3164 | } |
| 3165 | */ |
| 3166 | Result += "\nstatic struct {\n"; |
| 3167 | Result += "\tint protocol_method_count;\n"; |
| 3168 | Result += "\tstruct _protocol_methods protocol_methods["; |
| 3169 | Result += utostr(NumMethods); |
| 3170 | Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_"; |
| 3171 | Result += PDecl->getNameAsString(); |
| 3172 | Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= " |
| 3173 | "{\n\t"; |
| 3174 | Result += utostr(NumMethods); |
| 3175 | Result += "\n"; |
| 3176 | |
| 3177 | // Output instance methods declared in this protocol. |
| 3178 | for (ObjCProtocolDecl::classmeth_iterator |
| 3179 | I = PDecl->classmeth_begin(), E = PDecl->classmeth_end(); |
| 3180 | I != E; ++I) { |
| 3181 | if (I == PDecl->classmeth_begin()) |
| 3182 | Result += "\t ,{{(struct objc_selector *)\""; |
| 3183 | else |
| 3184 | Result += "\t ,{(struct objc_selector *)\""; |
| 3185 | Result += (*I)->getSelector().getAsString().c_str(); |
| 3186 | std::string MethodTypeString; |
| 3187 | Context->getObjCEncodingForMethodDecl((*I), MethodTypeString); |
| 3188 | Result += "\", \""; |
| 3189 | Result += MethodTypeString; |
| 3190 | Result += "\"}\n"; |
| 3191 | } |
| 3192 | Result += "\t }\n};\n"; |
| 3193 | } |
| 3194 | |
| 3195 | // Output: |
| 3196 | /* struct _objc_protocol { |
| 3197 | // Objective-C 1.0 extensions |
| 3198 | struct _objc_protocol_extension *isa; |
| 3199 | char *protocol_name; |
| 3200 | struct _objc_protocol **protocol_list; |
| 3201 | struct _objc_protocol_method_list *instance_methods; |
| 3202 | struct _objc_protocol_method_list *class_methods; |
| 3203 | }; |
| 3204 | */ |
| 3205 | static bool objc_protocol = false; |
| 3206 | if (!objc_protocol) { |
| 3207 | Result += "\nstruct _objc_protocol {\n"; |
| 3208 | Result += "\tstruct _objc_protocol_extension *isa;\n"; |
| 3209 | Result += "\tchar *protocol_name;\n"; |
| 3210 | Result += "\tstruct _objc_protocol **protocol_list;\n"; |
| 3211 | Result += "\tstruct _objc_protocol_method_list *instance_methods;\n"; |
| 3212 | Result += "\tstruct _objc_protocol_method_list *class_methods;\n"; |
| 3213 | Result += "};\n"; |
| 3214 | |
| 3215 | objc_protocol = true; |
| 3216 | } |
| 3217 | |
| 3218 | Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_"; |
| 3219 | Result += PDecl->getNameAsString(); |
| 3220 | Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= " |
| 3221 | "{\n\t0, \""; |
| 3222 | Result += PDecl->getNameAsString(); |
| 3223 | Result += "\", 0, "; |
| 3224 | if (PDecl->instmeth_begin() != PDecl->instmeth_end()) { |
| 3225 | Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_"; |
| 3226 | Result += PDecl->getNameAsString(); |
| 3227 | Result += ", "; |
| 3228 | } |
| 3229 | else |
| 3230 | Result += "0, "; |
| 3231 | if (PDecl->classmeth_begin() != PDecl->classmeth_end()) { |
| 3232 | Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_"; |
| 3233 | Result += PDecl->getNameAsString(); |
| 3234 | Result += "\n"; |
| 3235 | } |
| 3236 | else |
| 3237 | Result += "0\n"; |
| 3238 | Result += "};\n"; |
| 3239 | |
| 3240 | // Mark this protocol as having been generated. |
| 3241 | if (!ObjCSynthesizedProtocols.insert(PDecl)) |
| 3242 | assert(false && "protocol already synthesized"); |
| 3243 | |
| 3244 | } |
| 3245 | |
| 3246 | void RewriteObjC:: |
| 3247 | RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols, |
| 3248 | const char *prefix, const char *ClassName, |
| 3249 | std::string &Result) { |
| 3250 | if (Protocols.empty()) return; |
| 3251 | |
| 3252 | for (unsigned i = 0; i != Protocols.size(); i++) |
| 3253 | RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result); |
| 3254 | |
| 3255 | // Output the top lovel protocol meta-data for the class. |
| 3256 | /* struct _objc_protocol_list { |
| 3257 | struct _objc_protocol_list *next; |
| 3258 | int protocol_count; |
| 3259 | struct _objc_protocol *class_protocols[]; |
| 3260 | } |
| 3261 | */ |
| 3262 | Result += "\nstatic struct {\n"; |
| 3263 | Result += "\tstruct _objc_protocol_list *next;\n"; |
| 3264 | Result += "\tint protocol_count;\n"; |
| 3265 | Result += "\tstruct _objc_protocol *class_protocols["; |
| 3266 | Result += utostr(Protocols.size()); |
| 3267 | Result += "];\n} _OBJC_"; |
| 3268 | Result += prefix; |
| 3269 | Result += "_PROTOCOLS_"; |
| 3270 | Result += ClassName; |
| 3271 | Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= " |
| 3272 | "{\n\t0, "; |
| 3273 | Result += utostr(Protocols.size()); |
| 3274 | Result += "\n"; |
| 3275 | |
| 3276 | Result += "\t,{&_OBJC_PROTOCOL_"; |
| 3277 | Result += Protocols[0]->getNameAsString(); |
| 3278 | Result += " \n"; |
| 3279 | |
| 3280 | for (unsigned i = 1; i != Protocols.size(); i++) { |
| 3281 | Result += "\t ,&_OBJC_PROTOCOL_"; |
| 3282 | Result += Protocols[i]->getNameAsString(); |
| 3283 | Result += "\n"; |
| 3284 | } |
| 3285 | Result += "\t }\n};\n"; |
| 3286 | } |
| 3287 | |
| 3288 | |
| 3289 | /// RewriteObjCCategoryImplDecl - Rewrite metadata for each category |
| 3290 | /// implementation. |
| 3291 | void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl, |
| 3292 | std::string &Result) { |
| 3293 | ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface(); |
| 3294 | // Find category declaration for this implementation. |
| 3295 | ObjCCategoryDecl *CDecl; |
| 3296 | for (CDecl = ClassDecl->getCategoryList(); CDecl; |
| 3297 | CDecl = CDecl->getNextClassCategory()) |
| 3298 | if (CDecl->getIdentifier() == IDecl->getIdentifier()) |
| 3299 | break; |
| 3300 | |
| 3301 | std::string FullCategoryName = ClassDecl->getNameAsString(); |
| 3302 | FullCategoryName += '_'; |
| 3303 | FullCategoryName += IDecl->getNameAsString(); |
| 3304 | |
| 3305 | // Build _objc_method_list for class's instance methods if needed |
| 3306 | llvm::SmallVector<ObjCMethodDecl *, 32> |
| 3307 | InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end()); |
| 3308 | |
| 3309 | // If any of our property implementations have associated getters or |
| 3310 | // setters, produce metadata for them as well. |
| 3311 | for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(), |
| 3312 | PropEnd = IDecl->propimpl_end(); |
| 3313 | Prop != PropEnd; ++Prop) { |
| 3314 | if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic) |
| 3315 | continue; |
| 3316 | if (!(*Prop)->getPropertyIvarDecl()) |
| 3317 | continue; |
| 3318 | ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl(); |
| 3319 | if (!PD) |
| 3320 | continue; |
| 3321 | if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl()) |
| 3322 | InstanceMethods.push_back(Getter); |
| 3323 | if (PD->isReadOnly()) |
| 3324 | continue; |
| 3325 | if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl()) |
| 3326 | InstanceMethods.push_back(Setter); |
| 3327 | } |
| 3328 | RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(), |
| 3329 | true, "CATEGORY_", FullCategoryName.c_str(), |
| 3330 | Result); |
| 3331 | |
| 3332 | // Build _objc_method_list for class's class methods if needed |
| 3333 | RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(), |
| 3334 | false, "CATEGORY_", FullCategoryName.c_str(), |
| 3335 | Result); |
| 3336 | |
| 3337 | // Protocols referenced in class declaration? |
| 3338 | // Null CDecl is case of a category implementation with no category interface |
| 3339 | if (CDecl) |
| 3340 | RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY", |
| 3341 | FullCategoryName.c_str(), Result); |
| 3342 | /* struct _objc_category { |
| 3343 | char *category_name; |
| 3344 | char *class_name; |
| 3345 | struct _objc_method_list *instance_methods; |
| 3346 | struct _objc_method_list *class_methods; |
| 3347 | struct _objc_protocol_list *protocols; |
| 3348 | // Objective-C 1.0 extensions |
| 3349 | uint32_t size; // sizeof (struct _objc_category) |
| 3350 | struct _objc_property_list *instance_properties; // category's own |
| 3351 | // @property decl. |
| 3352 | }; |
| 3353 | */ |
| 3354 | |
| 3355 | static bool objc_category = false; |
| 3356 | if (!objc_category) { |
| 3357 | Result += "\nstruct _objc_category {\n"; |
| 3358 | Result += "\tchar *category_name;\n"; |
| 3359 | Result += "\tchar *class_name;\n"; |
| 3360 | Result += "\tstruct _objc_method_list *instance_methods;\n"; |
| 3361 | Result += "\tstruct _objc_method_list *class_methods;\n"; |
| 3362 | Result += "\tstruct _objc_protocol_list *protocols;\n"; |
| 3363 | Result += "\tunsigned int size;\n"; |
| 3364 | Result += "\tstruct _objc_property_list *instance_properties;\n"; |
| 3365 | Result += "};\n"; |
| 3366 | objc_category = true; |
| 3367 | } |
| 3368 | Result += "\nstatic struct _objc_category _OBJC_CATEGORY_"; |
| 3369 | Result += FullCategoryName; |
| 3370 | Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\""; |
| 3371 | Result += IDecl->getNameAsString(); |
| 3372 | Result += "\"\n\t, \""; |
| 3373 | Result += ClassDecl->getNameAsString(); |
| 3374 | Result += "\"\n"; |
| 3375 | |
| 3376 | if (IDecl->instmeth_begin() != IDecl->instmeth_end()) { |
| 3377 | Result += "\t, (struct _objc_method_list *)" |
| 3378 | "&_OBJC_CATEGORY_INSTANCE_METHODS_"; |
| 3379 | Result += FullCategoryName; |
| 3380 | Result += "\n"; |
| 3381 | } |
| 3382 | else |
| 3383 | Result += "\t, 0\n"; |
| 3384 | if (IDecl->classmeth_begin() != IDecl->classmeth_end()) { |
| 3385 | Result += "\t, (struct _objc_method_list *)" |
| 3386 | "&_OBJC_CATEGORY_CLASS_METHODS_"; |
| 3387 | Result += FullCategoryName; |
| 3388 | Result += "\n"; |
| 3389 | } |
| 3390 | else |
| 3391 | Result += "\t, 0\n"; |
| 3392 | |
| 3393 | if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) { |
| 3394 | Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_"; |
| 3395 | Result += FullCategoryName; |
| 3396 | Result += "\n"; |
| 3397 | } |
| 3398 | else |
| 3399 | Result += "\t, 0\n"; |
| 3400 | Result += "\t, sizeof(struct _objc_category), 0\n};\n"; |
| 3401 | } |
| 3402 | |
| 3403 | /// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of |
| 3404 | /// ivar offset. |
| 3405 | void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl, |
| 3406 | ObjCIvarDecl *ivar, |
| 3407 | std::string &Result) { |
| 3408 | if (ivar->isBitField()) { |
| 3409 | // FIXME: The hack below doesn't work for bitfields. For now, we simply |
| 3410 | // place all bitfields at offset 0. |
| 3411 | Result += "0"; |
| 3412 | } else { |
| 3413 | Result += "__OFFSETOFIVAR__(struct "; |
| 3414 | Result += IDecl->getNameAsString(); |
| 3415 | if (LangOpts.Microsoft) |
| 3416 | Result += "_IMPL"; |
| 3417 | Result += ", "; |
| 3418 | Result += ivar->getNameAsString(); |
| 3419 | Result += ")"; |
| 3420 | } |
| 3421 | } |
| 3422 | |
| 3423 | //===----------------------------------------------------------------------===// |
| 3424 | // Meta Data Emission |
| 3425 | //===----------------------------------------------------------------------===// |
| 3426 | |
| 3427 | void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl, |
| 3428 | std::string &Result) { |
| 3429 | ObjCInterfaceDecl *CDecl = IDecl->getClassInterface(); |
| 3430 | |
| 3431 | // Explictly declared @interface's are already synthesized. |
| 3432 | if (CDecl->isImplicitInterfaceDecl()) { |
| 3433 | // FIXME: Implementation of a class with no @interface (legacy) doese not |
| 3434 | // produce correct synthesis as yet. |
| 3435 | SynthesizeObjCInternalStruct(CDecl, Result); |
| 3436 | } |
| 3437 | |
| 3438 | // Build _objc_ivar_list metadata for classes ivars if needed |
| 3439 | unsigned NumIvars = !IDecl->ivar_empty() |
| 3440 | ? IDecl->ivar_size() |
| 3441 | : (CDecl ? CDecl->ivar_size() : 0); |
| 3442 | if (NumIvars > 0) { |
| 3443 | static bool objc_ivar = false; |
| 3444 | if (!objc_ivar) { |
| 3445 | /* struct _objc_ivar { |
| 3446 | char *ivar_name; |
| 3447 | char *ivar_type; |
| 3448 | int ivar_offset; |
| 3449 | }; |
| 3450 | */ |
| 3451 | Result += "\nstruct _objc_ivar {\n"; |
| 3452 | Result += "\tchar *ivar_name;\n"; |
| 3453 | Result += "\tchar *ivar_type;\n"; |
| 3454 | Result += "\tint ivar_offset;\n"; |
| 3455 | Result += "};\n"; |
| 3456 | |
| 3457 | objc_ivar = true; |
| 3458 | } |
| 3459 | |
| 3460 | /* struct { |
| 3461 | int ivar_count; |
| 3462 | struct _objc_ivar ivar_list[nIvars]; |
| 3463 | }; |
| 3464 | */ |
| 3465 | Result += "\nstatic struct {\n"; |
| 3466 | Result += "\tint ivar_count;\n"; |
| 3467 | Result += "\tstruct _objc_ivar ivar_list["; |
| 3468 | Result += utostr(NumIvars); |
| 3469 | Result += "];\n} _OBJC_INSTANCE_VARIABLES_"; |
| 3470 | Result += IDecl->getNameAsString(); |
| 3471 | Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= " |
| 3472 | "{\n\t"; |
| 3473 | Result += utostr(NumIvars); |
| 3474 | Result += "\n"; |
| 3475 | |
| 3476 | ObjCInterfaceDecl::ivar_iterator IVI, IVE; |
| 3477 | llvm::SmallVector<ObjCIvarDecl *, 8> IVars; |
| 3478 | if (!IDecl->ivar_empty()) { |
| 3479 | for (ObjCImplementationDecl::ivar_iterator |
| 3480 | IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end(); |
| 3481 | IV != IVEnd; ++IV) |
| 3482 | IVars.push_back(*IV); |
| 3483 | IVI = IVars.begin(); |
| 3484 | IVE = IVars.end(); |
| 3485 | } else { |
| 3486 | IVI = CDecl->ivar_begin(); |
| 3487 | IVE = CDecl->ivar_end(); |
| 3488 | } |
| 3489 | Result += "\t,{{\""; |
| 3490 | Result += (*IVI)->getNameAsString(); |
| 3491 | Result += "\", \""; |
| 3492 | std::string TmpString, StrEncoding; |
| 3493 | Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI); |
| 3494 | QuoteDoublequotes(TmpString, StrEncoding); |
| 3495 | Result += StrEncoding; |
| 3496 | Result += "\", "; |
| 3497 | SynthesizeIvarOffsetComputation(IDecl, *IVI, Result); |
| 3498 | Result += "}\n"; |
| 3499 | for (++IVI; IVI != IVE; ++IVI) { |
| 3500 | Result += "\t ,{\""; |
| 3501 | Result += (*IVI)->getNameAsString(); |
| 3502 | Result += "\", \""; |
| 3503 | std::string TmpString, StrEncoding; |
| 3504 | Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI); |
| 3505 | QuoteDoublequotes(TmpString, StrEncoding); |
| 3506 | Result += StrEncoding; |
| 3507 | Result += "\", "; |
| 3508 | SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result); |
| 3509 | Result += "}\n"; |
| 3510 | } |
| 3511 | |
| 3512 | Result += "\t }\n};\n"; |
| 3513 | } |
| 3514 | |
| 3515 | // Build _objc_method_list for class's instance methods if needed |
| 3516 | llvm::SmallVector<ObjCMethodDecl *, 32> |
| 3517 | InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end()); |
| 3518 | |
| 3519 | // If any of our property implementations have associated getters or |
| 3520 | // setters, produce metadata for them as well. |
| 3521 | for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(), |
| 3522 | PropEnd = IDecl->propimpl_end(); |
| 3523 | Prop != PropEnd; ++Prop) { |
| 3524 | if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic) |
| 3525 | continue; |
| 3526 | if (!(*Prop)->getPropertyIvarDecl()) |
| 3527 | continue; |
| 3528 | ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl(); |
| 3529 | if (!PD) |
| 3530 | continue; |
| 3531 | if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl()) |
| 3532 | InstanceMethods.push_back(Getter); |
| 3533 | if (PD->isReadOnly()) |
| 3534 | continue; |
| 3535 | if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl()) |
| 3536 | InstanceMethods.push_back(Setter); |
| 3537 | } |
| 3538 | RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(), |
| 3539 | true, "", IDecl->getNameAsCString(), Result); |
| 3540 | |
| 3541 | // Build _objc_method_list for class's class methods if needed |
| 3542 | RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(), |
| 3543 | false, "", IDecl->getNameAsCString(), Result); |
| 3544 | |
| 3545 | // Protocols referenced in class declaration? |
| 3546 | RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), |
| 3547 | "CLASS", CDecl->getNameAsCString(), Result); |
| 3548 | |
| 3549 | // Declaration of class/meta-class metadata |
| 3550 | /* struct _objc_class { |
| 3551 | struct _objc_class *isa; // or const char *root_class_name when metadata |
| 3552 | const char *super_class_name; |
| 3553 | char *name; |
| 3554 | long version; |
| 3555 | long info; |
| 3556 | long instance_size; |
| 3557 | struct _objc_ivar_list *ivars; |
| 3558 | struct _objc_method_list *methods; |
| 3559 | struct objc_cache *cache; |
| 3560 | struct objc_protocol_list *protocols; |
| 3561 | const char *ivar_layout; |
| 3562 | struct _objc_class_ext *ext; |
| 3563 | }; |
| 3564 | */ |
| 3565 | static bool objc_class = false; |
| 3566 | if (!objc_class) { |
| 3567 | Result += "\nstruct _objc_class {\n"; |
| 3568 | Result += "\tstruct _objc_class *isa;\n"; |
| 3569 | Result += "\tconst char *super_class_name;\n"; |
| 3570 | Result += "\tchar *name;\n"; |
| 3571 | Result += "\tlong version;\n"; |
| 3572 | Result += "\tlong info;\n"; |
| 3573 | Result += "\tlong instance_size;\n"; |
| 3574 | Result += "\tstruct _objc_ivar_list *ivars;\n"; |
| 3575 | Result += "\tstruct _objc_method_list *methods;\n"; |
| 3576 | Result += "\tstruct objc_cache *cache;\n"; |
| 3577 | Result += "\tstruct _objc_protocol_list *protocols;\n"; |
| 3578 | Result += "\tconst char *ivar_layout;\n"; |
| 3579 | Result += "\tstruct _objc_class_ext *ext;\n"; |
| 3580 | Result += "};\n"; |
| 3581 | objc_class = true; |
| 3582 | } |
| 3583 | |
| 3584 | // Meta-class metadata generation. |
| 3585 | ObjCInterfaceDecl *RootClass = 0; |
| 3586 | ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass(); |
| 3587 | while (SuperClass) { |
| 3588 | RootClass = SuperClass; |
| 3589 | SuperClass = SuperClass->getSuperClass(); |
| 3590 | } |
| 3591 | SuperClass = CDecl->getSuperClass(); |
| 3592 | |
| 3593 | Result += "\nstatic struct _objc_class _OBJC_METACLASS_"; |
| 3594 | Result += CDecl->getNameAsString(); |
| 3595 | Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= " |
| 3596 | "{\n\t(struct _objc_class *)\""; |
| 3597 | Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString()); |
| 3598 | Result += "\""; |
| 3599 | |
| 3600 | if (SuperClass) { |
| 3601 | Result += ", \""; |
| 3602 | Result += SuperClass->getNameAsString(); |
| 3603 | Result += "\", \""; |
| 3604 | Result += CDecl->getNameAsString(); |
| 3605 | Result += "\""; |
| 3606 | } |
| 3607 | else { |
| 3608 | Result += ", 0, \""; |
| 3609 | Result += CDecl->getNameAsString(); |
| 3610 | Result += "\""; |
| 3611 | } |
| 3612 | // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it. |
| 3613 | // 'info' field is initialized to CLS_META(2) for metaclass |
| 3614 | Result += ", 0,2, sizeof(struct _objc_class), 0"; |
| 3615 | if (IDecl->classmeth_begin() != IDecl->classmeth_end()) { |
| 3616 | Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_"; |
| 3617 | Result += IDecl->getNameAsString(); |
| 3618 | Result += "\n"; |
| 3619 | } |
| 3620 | else |
| 3621 | Result += ", 0\n"; |
| 3622 | if (CDecl->protocol_begin() != CDecl->protocol_end()) { |
| 3623 | Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_"; |
| 3624 | Result += CDecl->getNameAsString(); |
| 3625 | Result += ",0,0\n"; |
| 3626 | } |
| 3627 | else |
| 3628 | Result += "\t,0,0,0,0\n"; |
| 3629 | Result += "};\n"; |
| 3630 | |
| 3631 | // class metadata generation. |
| 3632 | Result += "\nstatic struct _objc_class _OBJC_CLASS_"; |
| 3633 | Result += CDecl->getNameAsString(); |
| 3634 | Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= " |
| 3635 | "{\n\t&_OBJC_METACLASS_"; |
| 3636 | Result += CDecl->getNameAsString(); |
| 3637 | if (SuperClass) { |
| 3638 | Result += ", \""; |
| 3639 | Result += SuperClass->getNameAsString(); |
| 3640 | Result += "\", \""; |
| 3641 | Result += CDecl->getNameAsString(); |
| 3642 | Result += "\""; |
| 3643 | } |
| 3644 | else { |
| 3645 | Result += ", 0, \""; |
| 3646 | Result += CDecl->getNameAsString(); |
| 3647 | Result += "\""; |
| 3648 | } |
| 3649 | // 'info' field is initialized to CLS_CLASS(1) for class |
| 3650 | Result += ", 0,1"; |
| 3651 | if (!ObjCSynthesizedStructs.count(CDecl)) |
| 3652 | Result += ",0"; |
| 3653 | else { |
| 3654 | // class has size. Must synthesize its size. |
| 3655 | Result += ",sizeof(struct "; |
| 3656 | Result += CDecl->getNameAsString(); |
| 3657 | if (LangOpts.Microsoft) |
| 3658 | Result += "_IMPL"; |
| 3659 | Result += ")"; |
| 3660 | } |
| 3661 | if (NumIvars > 0) { |
| 3662 | Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_"; |
| 3663 | Result += CDecl->getNameAsString(); |
| 3664 | Result += "\n\t"; |
| 3665 | } |
| 3666 | else |
| 3667 | Result += ",0"; |
| 3668 | if (IDecl->instmeth_begin() != IDecl->instmeth_end()) { |
| 3669 | Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_"; |
| 3670 | Result += CDecl->getNameAsString(); |
| 3671 | Result += ", 0\n\t"; |
| 3672 | } |
| 3673 | else |
| 3674 | Result += ",0,0"; |
| 3675 | if (CDecl->protocol_begin() != CDecl->protocol_end()) { |
| 3676 | Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_"; |
| 3677 | Result += CDecl->getNameAsString(); |
| 3678 | Result += ", 0,0\n"; |
| 3679 | } |
| 3680 | else |
| 3681 | Result += ",0,0,0\n"; |
| 3682 | Result += "};\n"; |
| 3683 | } |
| 3684 | |
| 3685 | /// RewriteImplementations - This routine rewrites all method implementations |
| 3686 | /// and emits meta-data. |
| 3687 | |
| 3688 | void RewriteObjC::RewriteImplementations() { |
| 3689 | int ClsDefCount = ClassImplementation.size(); |
| 3690 | int CatDefCount = CategoryImplementation.size(); |
| 3691 | |
| 3692 | // Rewrite implemented methods |
| 3693 | for (int i = 0; i < ClsDefCount; i++) |
| 3694 | RewriteImplementationDecl(ClassImplementation[i]); |
| 3695 | |
| 3696 | for (int i = 0; i < CatDefCount; i++) |
| 3697 | RewriteImplementationDecl(CategoryImplementation[i]); |
| 3698 | } |
| 3699 | |
| 3700 | void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) { |
| 3701 | int ClsDefCount = ClassImplementation.size(); |
| 3702 | int CatDefCount = CategoryImplementation.size(); |
| 3703 | |
| 3704 | // This is needed for determining instance variable offsets. |
| 3705 | Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long) &((TYPE *)0)->MEMBER)\n"; |
| 3706 | // For each implemented class, write out all its meta data. |
| 3707 | for (int i = 0; i < ClsDefCount; i++) |
| 3708 | RewriteObjCClassMetaData(ClassImplementation[i], Result); |
| 3709 | |
| 3710 | // For each implemented category, write out all its meta data. |
| 3711 | for (int i = 0; i < CatDefCount; i++) |
| 3712 | RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result); |
| 3713 | |
| 3714 | // Write objc_symtab metadata |
| 3715 | /* |
| 3716 | struct _objc_symtab |
| 3717 | { |
| 3718 | long sel_ref_cnt; |
| 3719 | SEL *refs; |
| 3720 | short cls_def_cnt; |
| 3721 | short cat_def_cnt; |
| 3722 | void *defs[cls_def_cnt + cat_def_cnt]; |
| 3723 | }; |
| 3724 | */ |
| 3725 | |
| 3726 | Result += "\nstruct _objc_symtab {\n"; |
| 3727 | Result += "\tlong sel_ref_cnt;\n"; |
| 3728 | Result += "\tSEL *refs;\n"; |
| 3729 | Result += "\tshort cls_def_cnt;\n"; |
| 3730 | Result += "\tshort cat_def_cnt;\n"; |
| 3731 | Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n"; |
| 3732 | Result += "};\n\n"; |
| 3733 | |
| 3734 | Result += "static struct _objc_symtab " |
| 3735 | "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n"; |
| 3736 | Result += "\t0, 0, " + utostr(ClsDefCount) |
| 3737 | + ", " + utostr(CatDefCount) + "\n"; |
| 3738 | for (int i = 0; i < ClsDefCount; i++) { |
| 3739 | Result += "\t,&_OBJC_CLASS_"; |
| 3740 | Result += ClassImplementation[i]->getNameAsString(); |
| 3741 | Result += "\n"; |
| 3742 | } |
| 3743 | |
| 3744 | for (int i = 0; i < CatDefCount; i++) { |
| 3745 | Result += "\t,&_OBJC_CATEGORY_"; |
| 3746 | Result += CategoryImplementation[i]->getClassInterface()->getNameAsString(); |
| 3747 | Result += "_"; |
| 3748 | Result += CategoryImplementation[i]->getNameAsString(); |
| 3749 | Result += "\n"; |
| 3750 | } |
| 3751 | |
| 3752 | Result += "};\n\n"; |
| 3753 | |
| 3754 | // Write objc_module metadata |
| 3755 | |
| 3756 | /* |
| 3757 | struct _objc_module { |
| 3758 | long version; |
| 3759 | long size; |
| 3760 | const char *name; |
| 3761 | struct _objc_symtab *symtab; |
| 3762 | } |
| 3763 | */ |
| 3764 | |
| 3765 | Result += "\nstruct _objc_module {\n"; |
| 3766 | Result += "\tlong version;\n"; |
| 3767 | Result += "\tlong size;\n"; |
| 3768 | Result += "\tconst char *name;\n"; |
| 3769 | Result += "\tstruct _objc_symtab *symtab;\n"; |
| 3770 | Result += "};\n\n"; |
| 3771 | Result += "static struct _objc_module " |
| 3772 | "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n"; |
| 3773 | Result += "\t" + utostr(OBJC_ABI_VERSION) + |
| 3774 | ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n"; |
| 3775 | Result += "};\n\n"; |
| 3776 | |
| 3777 | if (LangOpts.Microsoft) { |
| 3778 | if (ProtocolExprDecls.size()) { |
| 3779 | Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n"; |
| 3780 | Result += "#pragma data_seg(push, \".objc_protocol$B\")\n"; |
| 3781 | for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(), |
| 3782 | E = ProtocolExprDecls.end(); I != E; ++I) { |
| 3783 | Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_"; |
| 3784 | Result += (*I)->getNameAsString(); |
| 3785 | Result += " = &_OBJC_PROTOCOL_"; |
| 3786 | Result += (*I)->getNameAsString(); |
| 3787 | Result += ";\n"; |
| 3788 | } |
| 3789 | Result += "#pragma data_seg(pop)\n\n"; |
| 3790 | } |
| 3791 | Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n"; |
| 3792 | Result += "#pragma data_seg(push, \".objc_module_info$B\")\n"; |
| 3793 | Result += "static struct _objc_module *_POINTER_OBJC_MODULES = "; |
| 3794 | Result += "&_OBJC_MODULES;\n"; |
| 3795 | Result += "#pragma data_seg(pop)\n\n"; |
| 3796 | } |
| 3797 | } |
| 3798 | |
| 3799 | void RewriteObjC::RewriteByRefString(std::string &ResultStr, |
| 3800 | const std::string &Name, |
| 3801 | ValueDecl *VD) { |
| 3802 | assert(BlockByRefDeclNo.count(VD) && |
| 3803 | "RewriteByRefString: ByRef decl missing"); |
| 3804 | ResultStr += "struct __Block_byref_" + Name + |
| 3805 | "_" + utostr(BlockByRefDeclNo[VD]) ; |
| 3806 | } |
| 3807 | |
| 3808 | std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i, |
| 3809 | const char *funcName, |
| 3810 | std::string Tag) { |
| 3811 | const FunctionType *AFT = CE->getFunctionType(); |
| 3812 | QualType RT = AFT->getResultType(); |
| 3813 | std::string StructRef = "struct " + Tag; |
| 3814 | std::string S = "static " + RT.getAsString() + " __" + |
| 3815 | funcName + "_" + "block_func_" + utostr(i); |
| 3816 | |
| 3817 | BlockDecl *BD = CE->getBlockDecl(); |
| 3818 | |
| 3819 | if (isa<FunctionNoProtoType>(AFT)) { |
| 3820 | // No user-supplied arguments. Still need to pass in a pointer to the |
| 3821 | // block (to reference imported block decl refs). |
| 3822 | S += "(" + StructRef + " *__cself)"; |
| 3823 | } else if (BD->param_empty()) { |
| 3824 | S += "(" + StructRef + " *__cself)"; |
| 3825 | } else { |
| 3826 | const FunctionProtoType *FT = cast<FunctionProtoType>(AFT); |
| 3827 | assert(FT && "SynthesizeBlockFunc: No function proto"); |
| 3828 | S += '('; |
| 3829 | // first add the implicit argument. |
| 3830 | S += StructRef + " *__cself, "; |
| 3831 | std::string ParamStr; |
| 3832 | for (BlockDecl::param_iterator AI = BD->param_begin(), |
| 3833 | E = BD->param_end(); AI != E; ++AI) { |
| 3834 | if (AI != BD->param_begin()) S += ", "; |
| 3835 | ParamStr = (*AI)->getNameAsString(); |
| 3836 | (*AI)->getType().getAsStringInternal(ParamStr, Context->PrintingPolicy); |
| 3837 | S += ParamStr; |
| 3838 | } |
| 3839 | if (FT->isVariadic()) { |
| 3840 | if (!BD->param_empty()) S += ", "; |
| 3841 | S += "..."; |
| 3842 | } |
| 3843 | S += ')'; |
| 3844 | } |
| 3845 | S += " {\n"; |
| 3846 | |
| 3847 | // Create local declarations to avoid rewriting all closure decl ref exprs. |
| 3848 | // First, emit a declaration for all "by ref" decls. |
| 3849 | for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(), |
| 3850 | E = BlockByRefDecls.end(); I != E; ++I) { |
| 3851 | S += " "; |
| 3852 | std::string Name = (*I)->getNameAsString(); |
| 3853 | std::string TypeString; |
| 3854 | RewriteByRefString(TypeString, Name, (*I)); |
| 3855 | TypeString += " *"; |
| 3856 | Name = TypeString + Name; |
| 3857 | S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n"; |
| 3858 | } |
| 3859 | // Next, emit a declaration for all "by copy" declarations. |
| 3860 | for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(), |
| 3861 | E = BlockByCopyDecls.end(); I != E; ++I) { |
| 3862 | S += " "; |
| 3863 | std::string Name = (*I)->getNameAsString(); |
| 3864 | // Handle nested closure invocation. For example: |
| 3865 | // |
| 3866 | // void (^myImportedClosure)(void); |
| 3867 | // myImportedClosure = ^(void) { setGlobalInt(x + y); }; |
| 3868 | // |
| 3869 | // void (^anotherClosure)(void); |
| 3870 | // anotherClosure = ^(void) { |
| 3871 | // myImportedClosure(); // import and invoke the closure |
| 3872 | // }; |
| 3873 | // |
| 3874 | if (isTopLevelBlockPointerType((*I)->getType())) |
| 3875 | S += "struct __block_impl *"; |
| 3876 | else |
| 3877 | (*I)->getType().getAsStringInternal(Name, Context->PrintingPolicy); |
| 3878 | S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n"; |
| 3879 | } |
| 3880 | std::string RewrittenStr = RewrittenBlockExprs[CE]; |
| 3881 | const char *cstr = RewrittenStr.c_str(); |
| 3882 | while (*cstr++ != '{') ; |
| 3883 | S += cstr; |
| 3884 | S += "\n"; |
| 3885 | return S; |
| 3886 | } |
| 3887 | |
| 3888 | std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i, |
| 3889 | const char *funcName, |
| 3890 | std::string Tag) { |
| 3891 | std::string StructRef = "struct " + Tag; |
| 3892 | std::string S = "static void __"; |
| 3893 | |
| 3894 | S += funcName; |
| 3895 | S += "_block_copy_" + utostr(i); |
| 3896 | S += "(" + StructRef; |
| 3897 | S += "*dst, " + StructRef; |
| 3898 | S += "*src) {"; |
| 3899 | for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(), |
| 3900 | E = ImportedBlockDecls.end(); I != E; ++I) { |
| 3901 | S += "_Block_object_assign((void*)&dst->"; |
| 3902 | S += (*I)->getNameAsString(); |
| 3903 | S += ", (void*)src->"; |
| 3904 | S += (*I)->getNameAsString(); |
| 3905 | if (BlockByRefDecls.count((*I))) |
| 3906 | S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);"; |
| 3907 | else |
| 3908 | S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);"; |
| 3909 | } |
| 3910 | S += "}\n"; |
| 3911 | |
| 3912 | S += "\nstatic void __"; |
| 3913 | S += funcName; |
| 3914 | S += "_block_dispose_" + utostr(i); |
| 3915 | S += "(" + StructRef; |
| 3916 | S += "*src) {"; |
| 3917 | for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(), |
| 3918 | E = ImportedBlockDecls.end(); I != E; ++I) { |
| 3919 | S += "_Block_object_dispose((void*)src->"; |
| 3920 | S += (*I)->getNameAsString(); |
| 3921 | if (BlockByRefDecls.count((*I))) |
| 3922 | S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);"; |
| 3923 | else |
| 3924 | S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);"; |
| 3925 | } |
| 3926 | S += "}\n"; |
| 3927 | return S; |
| 3928 | } |
| 3929 | |
| 3930 | std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag, |
| 3931 | std::string Desc) { |
| 3932 | std::string S = "\nstruct " + Tag; |
| 3933 | std::string Constructor = " " + Tag; |
| 3934 | |
| 3935 | S += " {\n struct __block_impl impl;\n"; |
| 3936 | S += " struct " + Desc; |
| 3937 | S += "* Desc;\n"; |
| 3938 | |
| 3939 | Constructor += "(void *fp, "; // Invoke function pointer. |
| 3940 | Constructor += "struct " + Desc; // Descriptor pointer. |
| 3941 | Constructor += " *desc"; |
| 3942 | |
| 3943 | if (BlockDeclRefs.size()) { |
| 3944 | // Output all "by copy" declarations. |
| 3945 | for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(), |
| 3946 | E = BlockByCopyDecls.end(); I != E; ++I) { |
| 3947 | S += " "; |
| 3948 | std::string FieldName = (*I)->getNameAsString(); |
| 3949 | std::string ArgName = "_" + FieldName; |
| 3950 | // Handle nested closure invocation. For example: |
| 3951 | // |
| 3952 | // void (^myImportedBlock)(void); |
| 3953 | // myImportedBlock = ^(void) { setGlobalInt(x + y); }; |
| 3954 | // |
| 3955 | // void (^anotherBlock)(void); |
| 3956 | // anotherBlock = ^(void) { |
| 3957 | // myImportedBlock(); // import and invoke the closure |
| 3958 | // }; |
| 3959 | // |
| 3960 | if (isTopLevelBlockPointerType((*I)->getType())) { |
| 3961 | S += "struct __block_impl *"; |
| 3962 | Constructor += ", void *" + ArgName; |
| 3963 | } else { |
| 3964 | (*I)->getType().getAsStringInternal(FieldName, Context->PrintingPolicy); |
| 3965 | (*I)->getType().getAsStringInternal(ArgName, Context->PrintingPolicy); |
| 3966 | Constructor += ", " + ArgName; |
| 3967 | } |
| 3968 | S += FieldName + ";\n"; |
| 3969 | } |
| 3970 | // Output all "by ref" declarations. |
| 3971 | for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(), |
| 3972 | E = BlockByRefDecls.end(); I != E; ++I) { |
| 3973 | S += " "; |
| 3974 | std::string FieldName = (*I)->getNameAsString(); |
| 3975 | std::string ArgName = "_" + FieldName; |
| 3976 | // Handle nested closure invocation. For example: |
| 3977 | // |
| 3978 | // void (^myImportedBlock)(void); |
| 3979 | // myImportedBlock = ^(void) { setGlobalInt(x + y); }; |
| 3980 | // |
| 3981 | // void (^anotherBlock)(void); |
| 3982 | // anotherBlock = ^(void) { |
| 3983 | // myImportedBlock(); // import and invoke the closure |
| 3984 | // }; |
| 3985 | // |
| 3986 | if (isTopLevelBlockPointerType((*I)->getType())) { |
| 3987 | S += "struct __block_impl *"; |
| 3988 | Constructor += ", void *" + ArgName; |
| 3989 | } else { |
| 3990 | std::string TypeString; |
| 3991 | RewriteByRefString(TypeString, FieldName, (*I)); |
| 3992 | TypeString += " *"; |
| 3993 | FieldName = TypeString + FieldName; |
| 3994 | ArgName = TypeString + ArgName; |
| 3995 | Constructor += ", " + ArgName; |
| 3996 | } |
| 3997 | S += FieldName + "; // by ref\n"; |
| 3998 | } |
| 3999 | // Finish writing the constructor. |
| 4000 | Constructor += ", int flags=0) {\n"; |
| 4001 | if (GlobalVarDecl) |
| 4002 | Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n"; |
| 4003 | else |
| 4004 | Constructor += " impl.isa = &_NSConcreteStackBlock;\n"; |
| 4005 | Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n"; |
| 4006 | |
| 4007 | Constructor += " Desc = desc;\n"; |
| 4008 | |
| 4009 | // Initialize all "by copy" arguments. |
| 4010 | for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(), |
| 4011 | E = BlockByCopyDecls.end(); I != E; ++I) { |
| 4012 | std::string Name = (*I)->getNameAsString(); |
| 4013 | Constructor += " "; |
| 4014 | if (isTopLevelBlockPointerType((*I)->getType())) |
| 4015 | Constructor += Name + " = (struct __block_impl *)_"; |
| 4016 | else |
| 4017 | Constructor += Name + " = _"; |
| 4018 | Constructor += Name + ";\n"; |
| 4019 | } |
| 4020 | // Initialize all "by ref" arguments. |
| 4021 | for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(), |
| 4022 | E = BlockByRefDecls.end(); I != E; ++I) { |
| 4023 | std::string Name = (*I)->getNameAsString(); |
| 4024 | Constructor += " "; |
| 4025 | if (isTopLevelBlockPointerType((*I)->getType())) |
| 4026 | Constructor += Name + " = (struct __block_impl *)_"; |
| 4027 | else |
| 4028 | Constructor += Name + " = _"; |
| 4029 | Constructor += Name + "->__forwarding;\n"; |
| 4030 | } |
| 4031 | } else { |
| 4032 | // Finish writing the constructor. |
| 4033 | Constructor += ", int flags=0) {\n"; |
| 4034 | if (GlobalVarDecl) |
| 4035 | Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n"; |
| 4036 | else |
| 4037 | Constructor += " impl.isa = &_NSConcreteStackBlock;\n"; |
| 4038 | Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n"; |
| 4039 | Constructor += " Desc = desc;\n"; |
| 4040 | } |
| 4041 | Constructor += " "; |
| 4042 | Constructor += "}\n"; |
| 4043 | S += Constructor; |
| 4044 | S += "};\n"; |
| 4045 | return S; |
| 4046 | } |
| 4047 | |
| 4048 | std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag, |
| 4049 | std::string ImplTag, int i, |
| 4050 | const char *FunName, |
| 4051 | unsigned hasCopy) { |
| 4052 | std::string S = "\nstatic struct " + DescTag; |
| 4053 | |
| 4054 | S += " {\n unsigned long reserved;\n"; |
| 4055 | S += " unsigned long Block_size;\n"; |
| 4056 | if (hasCopy) { |
| 4057 | S += " void (*copy)(struct "; |
| 4058 | S += ImplTag; S += "*, struct "; |
| 4059 | S += ImplTag; S += "*);\n"; |
| 4060 | |
| 4061 | S += " void (*dispose)(struct "; |
| 4062 | S += ImplTag; S += "*);\n"; |
| 4063 | } |
| 4064 | S += "} "; |
| 4065 | |
| 4066 | S += DescTag + "_DATA = { 0, sizeof(struct "; |
| 4067 | S += ImplTag + ")"; |
| 4068 | if (hasCopy) { |
| 4069 | S += ", __" + std::string(FunName) + "_block_copy_" + utostr(i); |
| 4070 | S += ", __" + std::string(FunName) + "_block_dispose_" + utostr(i); |
| 4071 | } |
| 4072 | S += "};\n"; |
| 4073 | return S; |
| 4074 | } |
| 4075 | |
| 4076 | void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart, |
| 4077 | const char *FunName) { |
| 4078 | // Insert declaration for the function in which block literal is used. |
| 4079 | if (CurFunctionDeclToDeclareForBlock && !Blocks.empty()) |
| 4080 | RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock); |
| 4081 | // Insert closures that were part of the function. |
| 4082 | for (unsigned i = 0; i < Blocks.size(); i++) { |
| 4083 | |
| 4084 | CollectBlockDeclRefInfo(Blocks[i]); |
| 4085 | |
| 4086 | std::string ImplTag = "__" + std::string(FunName) + "_block_impl_" + utostr(i); |
| 4087 | std::string DescTag = "__" + std::string(FunName) + "_block_desc_" + utostr(i); |
| 4088 | |
| 4089 | std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag); |
| 4090 | |
| 4091 | InsertText(FunLocStart, CI.c_str(), CI.size()); |
| 4092 | |
| 4093 | std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag); |
| 4094 | |
| 4095 | InsertText(FunLocStart, CF.c_str(), CF.size()); |
| 4096 | |
| 4097 | if (ImportedBlockDecls.size()) { |
| 4098 | std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag); |
| 4099 | InsertText(FunLocStart, HF.c_str(), HF.size()); |
| 4100 | } |
| 4101 | std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName, |
| 4102 | ImportedBlockDecls.size() > 0); |
| 4103 | InsertText(FunLocStart, BD.c_str(), BD.size()); |
| 4104 | |
| 4105 | BlockDeclRefs.clear(); |
| 4106 | BlockByRefDecls.clear(); |
| 4107 | BlockByCopyDecls.clear(); |
| 4108 | BlockCallExprs.clear(); |
| 4109 | ImportedBlockDecls.clear(); |
| 4110 | } |
| 4111 | Blocks.clear(); |
| 4112 | RewrittenBlockExprs.clear(); |
| 4113 | } |
| 4114 | |
| 4115 | void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) { |
| 4116 | SourceLocation FunLocStart = FD->getTypeSpecStartLoc(); |
| 4117 | const char *FuncName = FD->getNameAsCString(); |
| 4118 | |
| 4119 | SynthesizeBlockLiterals(FunLocStart, FuncName); |
| 4120 | } |
| 4121 | |
| 4122 | void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) { |
| 4123 | //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n"); |
| 4124 | //SourceLocation FunLocStart = MD->getLocStart(); |
| 4125 | SourceLocation FunLocStart = MD->getLocStart(); |
| 4126 | std::string FuncName = MD->getSelector().getAsString(); |
| 4127 | // Convert colons to underscores. |
| 4128 | std::string::size_type loc = 0; |
| 4129 | while ((loc = FuncName.find(":", loc)) != std::string::npos) |
| 4130 | FuncName.replace(loc, 1, "_"); |
| 4131 | |
| 4132 | SynthesizeBlockLiterals(FunLocStart, FuncName.c_str()); |
| 4133 | } |
| 4134 | |
| 4135 | void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) { |
| 4136 | for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); |
| 4137 | CI != E; ++CI) |
| 4138 | if (*CI) { |
| 4139 | if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) |
| 4140 | GetBlockDeclRefExprs(CBE->getBody()); |
| 4141 | else |
| 4142 | GetBlockDeclRefExprs(*CI); |
| 4143 | } |
| 4144 | // Handle specific things. |
| 4145 | if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) |
| 4146 | // FIXME: Handle enums. |
| 4147 | if (!isa<FunctionDecl>(CDRE->getDecl())) |
| 4148 | BlockDeclRefs.push_back(CDRE); |
| 4149 | return; |
| 4150 | } |
| 4151 | |
| 4152 | void RewriteObjC::GetBlockCallExprs(Stmt *S) { |
| 4153 | for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); |
| 4154 | CI != E; ++CI) |
| 4155 | if (*CI) { |
| 4156 | if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) |
| 4157 | GetBlockCallExprs(CBE->getBody()); |
| 4158 | else |
| 4159 | GetBlockCallExprs(*CI); |
| 4160 | } |
| 4161 | |
| 4162 | if (CallExpr *CE = dyn_cast<CallExpr>(S)) { |
| 4163 | if (CE->getCallee()->getType()->isBlockPointerType()) { |
| 4164 | BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE; |
| 4165 | } |
| 4166 | } |
| 4167 | return; |
| 4168 | } |
| 4169 | |
| 4170 | Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) { |
| 4171 | // Navigate to relevant type information. |
| 4172 | const BlockPointerType *CPT = 0; |
| 4173 | |
| 4174 | if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) { |
| 4175 | CPT = DRE->getType()->getAs<BlockPointerType>(); |
| 4176 | } else if (const BlockDeclRefExpr *CDRE = |
| 4177 | dyn_cast<BlockDeclRefExpr>(BlockExp)) { |
| 4178 | CPT = CDRE->getType()->getAs<BlockPointerType>(); |
| 4179 | } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) { |
| 4180 | CPT = MExpr->getType()->getAs<BlockPointerType>(); |
| 4181 | } |
| 4182 | else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) { |
| 4183 | return SynthesizeBlockCall(Exp, PRE->getSubExpr()); |
| 4184 | } |
| 4185 | else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp)) |
| 4186 | CPT = IEXPR->getType()->getAs<BlockPointerType>(); |
| 4187 | else if (const ConditionalOperator *CEXPR = |
| 4188 | dyn_cast<ConditionalOperator>(BlockExp)) { |
| 4189 | Expr *LHSExp = CEXPR->getLHS(); |
| 4190 | Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp); |
| 4191 | Expr *RHSExp = CEXPR->getRHS(); |
| 4192 | Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp); |
| 4193 | Expr *CONDExp = CEXPR->getCond(); |
| 4194 | ConditionalOperator *CondExpr = |
| 4195 | new (Context) ConditionalOperator(CONDExp, |
| 4196 | SourceLocation(), cast<Expr>(LHSStmt), |
| 4197 | SourceLocation(), cast<Expr>(RHSStmt), |
| 4198 | Exp->getType()); |
| 4199 | return CondExpr; |
| 4200 | } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) { |
| 4201 | CPT = IRE->getType()->getAs<BlockPointerType>(); |
| 4202 | } else { |
| 4203 | assert(1 && "RewriteBlockClass: Bad type"); |
| 4204 | } |
| 4205 | assert(CPT && "RewriteBlockClass: Bad type"); |
| 4206 | const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>(); |
| 4207 | assert(FT && "RewriteBlockClass: Bad type"); |
| 4208 | const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT); |
| 4209 | // FTP will be null for closures that don't take arguments. |
| 4210 | |
| 4211 | RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl, |
| 4212 | SourceLocation(), |
| 4213 | &Context->Idents.get("__block_impl")); |
| 4214 | QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD)); |
| 4215 | |
| 4216 | // Generate a funky cast. |
| 4217 | llvm::SmallVector<QualType, 8> ArgTypes; |
| 4218 | |
| 4219 | // Push the block argument type. |
| 4220 | ArgTypes.push_back(PtrBlock); |
| 4221 | if (FTP) { |
| 4222 | for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(), |
| 4223 | E = FTP->arg_type_end(); I && (I != E); ++I) { |
| 4224 | QualType t = *I; |
| 4225 | // Make sure we convert "t (^)(...)" to "t (*)(...)". |
| 4226 | if (isTopLevelBlockPointerType(t)) { |
| 4227 | const BlockPointerType *BPT = t->getAs<BlockPointerType>(); |
| 4228 | t = Context->getPointerType(BPT->getPointeeType()); |
| 4229 | } |
| 4230 | ArgTypes.push_back(t); |
| 4231 | } |
| 4232 | } |
| 4233 | // Now do the pointer to function cast. |
| 4234 | QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(), |
| 4235 | &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0); |
| 4236 | |
| 4237 | PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType); |
| 4238 | |
| 4239 | CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock, |
| 4240 | CastExpr::CK_Unknown, |
| 4241 | const_cast<Expr*>(BlockExp)); |
| 4242 | // Don't forget the parens to enforce the proper binding. |
| 4243 | ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), |
| 4244 | BlkCast); |
| 4245 | //PE->dump(); |
| 4246 | |
| 4247 | FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(), |
| 4248 | &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0, |
| 4249 | /*BitWidth=*/0, /*Mutable=*/true); |
| 4250 | MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(), |
| 4251 | FD->getType()); |
| 4252 | |
| 4253 | CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType, |
| 4254 | CastExpr::CK_Unknown, ME); |
| 4255 | PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast); |
| 4256 | |
| 4257 | llvm::SmallVector<Expr*, 8> BlkExprs; |
| 4258 | // Add the implicit argument. |
| 4259 | BlkExprs.push_back(BlkCast); |
| 4260 | // Add the user arguments. |
| 4261 | for (CallExpr::arg_iterator I = Exp->arg_begin(), |
| 4262 | E = Exp->arg_end(); I != E; ++I) { |
| 4263 | BlkExprs.push_back(*I); |
| 4264 | } |
| 4265 | CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0], |
| 4266 | BlkExprs.size(), |
| 4267 | Exp->getType(), SourceLocation()); |
| 4268 | return CE; |
| 4269 | } |
| 4270 | |
| 4271 | void RewriteObjC::RewriteBlockCall(CallExpr *Exp) { |
| 4272 | Stmt *BlockCall = SynthesizeBlockCall(Exp, Exp->getCallee()); |
| 4273 | ReplaceStmt(Exp, BlockCall); |
| 4274 | } |
| 4275 | |
| 4276 | // We need to return the rewritten expression to handle cases where the |
| 4277 | // BlockDeclRefExpr is embedded in another expression being rewritten. |
| 4278 | // For example: |
| 4279 | // |
| 4280 | // int main() { |
| 4281 | // __block Foo *f; |
| 4282 | // __block int i; |
| 4283 | // |
| 4284 | // void (^myblock)() = ^() { |
| 4285 | // [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten). |
| 4286 | // i = 77; |
| 4287 | // }; |
| 4288 | //} |
| 4289 | Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) { |
| 4290 | // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR |
| 4291 | // for each DeclRefExp where BYREFVAR is name of the variable. |
| 4292 | ValueDecl *VD; |
| 4293 | bool isArrow = true; |
| 4294 | if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp)) |
| 4295 | VD = BDRE->getDecl(); |
| 4296 | else { |
| 4297 | VD = cast<DeclRefExpr>(DeclRefExp)->getDecl(); |
| 4298 | isArrow = false; |
| 4299 | } |
| 4300 | |
| 4301 | FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(), |
| 4302 | &Context->Idents.get("__forwarding"), |
| 4303 | Context->VoidPtrTy, 0, |
| 4304 | /*BitWidth=*/0, /*Mutable=*/true); |
| 4305 | MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow, |
| 4306 | FD, SourceLocation(), |
| 4307 | FD->getType()); |
| 4308 | |
| 4309 | const char *Name = VD->getNameAsCString(); |
| 4310 | FD = FieldDecl::Create(*Context, 0, SourceLocation(), |
| 4311 | &Context->Idents.get(Name), |
| 4312 | Context->VoidPtrTy, 0, |
| 4313 | /*BitWidth=*/0, /*Mutable=*/true); |
| 4314 | ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(), |
| 4315 | DeclRefExp->getType()); |
| 4316 | |
| 4317 | |
| 4318 | |
| 4319 | // Need parens to enforce precedence. |
| 4320 | ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), |
| 4321 | ME); |
| 4322 | ReplaceStmt(DeclRefExp, PE); |
| 4323 | return PE; |
| 4324 | } |
| 4325 | |
| 4326 | void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) { |
| 4327 | SourceLocation LocStart = CE->getLParenLoc(); |
| 4328 | SourceLocation LocEnd = CE->getRParenLoc(); |
| 4329 | |
| 4330 | // Need to avoid trying to rewrite synthesized casts. |
| 4331 | if (LocStart.isInvalid()) |
| 4332 | return; |
| 4333 | // Need to avoid trying to rewrite casts contained in macros. |
| 4334 | if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd)) |
| 4335 | return; |
| 4336 | |
| 4337 | const char *startBuf = SM->getCharacterData(LocStart); |
| 4338 | const char *endBuf = SM->getCharacterData(LocEnd); |
| 4339 | QualType QT = CE->getType(); |
| 4340 | const Type* TypePtr = QT->getAs<Type>(); |
| 4341 | if (isa<TypeOfExprType>(TypePtr)) { |
| 4342 | const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr); |
| 4343 | QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType(); |
| 4344 | std::string TypeAsString = "("; |
| 4345 | TypeAsString += QT.getAsString(); |
| 4346 | TypeAsString += ")"; |
| 4347 | ReplaceText(LocStart, endBuf-startBuf+1, |
| 4348 | TypeAsString.c_str(), TypeAsString.size()); |
| 4349 | return; |
| 4350 | } |
| 4351 | // advance the location to startArgList. |
| 4352 | const char *argPtr = startBuf; |
| 4353 | |
| 4354 | while (*argPtr++ && (argPtr < endBuf)) { |
| 4355 | switch (*argPtr) { |
| 4356 | case '^': |
| 4357 | // Replace the '^' with '*'. |
| 4358 | LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf); |
| 4359 | ReplaceText(LocStart, 1, "*", 1); |
| 4360 | break; |
| 4361 | } |
| 4362 | } |
| 4363 | return; |
| 4364 | } |
| 4365 | |
| 4366 | void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) { |
| 4367 | SourceLocation DeclLoc = FD->getLocation(); |
| 4368 | unsigned parenCount = 0; |
| 4369 | |
| 4370 | // We have 1 or more arguments that have closure pointers. |
| 4371 | const char *startBuf = SM->getCharacterData(DeclLoc); |
| 4372 | const char *startArgList = strchr(startBuf, '('); |
| 4373 | |
| 4374 | assert((*startArgList == '(') && "Rewriter fuzzy parser confused"); |
| 4375 | |
| 4376 | parenCount++; |
| 4377 | // advance the location to startArgList. |
| 4378 | DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf); |
| 4379 | assert((DeclLoc.isValid()) && "Invalid DeclLoc"); |
| 4380 | |
| 4381 | const char *argPtr = startArgList; |
| 4382 | |
| 4383 | while (*argPtr++ && parenCount) { |
| 4384 | switch (*argPtr) { |
| 4385 | case '^': |
| 4386 | // Replace the '^' with '*'. |
| 4387 | DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList); |
| 4388 | ReplaceText(DeclLoc, 1, "*", 1); |
| 4389 | break; |
| 4390 | case '(': |
| 4391 | parenCount++; |
| 4392 | break; |
| 4393 | case ')': |
| 4394 | parenCount--; |
| 4395 | break; |
| 4396 | } |
| 4397 | } |
| 4398 | return; |
| 4399 | } |
| 4400 | |
| 4401 | bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) { |
| 4402 | const FunctionProtoType *FTP; |
| 4403 | const PointerType *PT = QT->getAs<PointerType>(); |
| 4404 | if (PT) { |
| 4405 | FTP = PT->getPointeeType()->getAs<FunctionProtoType>(); |
| 4406 | } else { |
| 4407 | const BlockPointerType *BPT = QT->getAs<BlockPointerType>(); |
| 4408 | assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type"); |
| 4409 | FTP = BPT->getPointeeType()->getAs<FunctionProtoType>(); |
| 4410 | } |
| 4411 | if (FTP) { |
| 4412 | for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(), |
| 4413 | E = FTP->arg_type_end(); I != E; ++I) |
| 4414 | if (isTopLevelBlockPointerType(*I)) |
| 4415 | return true; |
| 4416 | } |
| 4417 | return false; |
| 4418 | } |
| 4419 | |
| 4420 | void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen, |
| 4421 | const char *&RParen) { |
| 4422 | const char *argPtr = strchr(Name, '('); |
| 4423 | assert((*argPtr == '(') && "Rewriter fuzzy parser confused"); |
| 4424 | |
| 4425 | LParen = argPtr; // output the start. |
| 4426 | argPtr++; // skip past the left paren. |
| 4427 | unsigned parenCount = 1; |
| 4428 | |
| 4429 | while (*argPtr && parenCount) { |
| 4430 | switch (*argPtr) { |
| 4431 | case '(': parenCount++; break; |
| 4432 | case ')': parenCount--; break; |
| 4433 | default: break; |
| 4434 | } |
| 4435 | if (parenCount) argPtr++; |
| 4436 | } |
| 4437 | assert((*argPtr == ')') && "Rewriter fuzzy parser confused"); |
| 4438 | RParen = argPtr; // output the end |
| 4439 | } |
| 4440 | |
| 4441 | void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) { |
| 4442 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { |
| 4443 | RewriteBlockPointerFunctionArgs(FD); |
| 4444 | return; |
| 4445 | } |
| 4446 | // Handle Variables and Typedefs. |
| 4447 | SourceLocation DeclLoc = ND->getLocation(); |
| 4448 | QualType DeclT; |
| 4449 | if (VarDecl *VD = dyn_cast<VarDecl>(ND)) |
| 4450 | DeclT = VD->getType(); |
| 4451 | else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND)) |
| 4452 | DeclT = TDD->getUnderlyingType(); |
| 4453 | else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND)) |
| 4454 | DeclT = FD->getType(); |
| 4455 | else |
| 4456 | assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled"); |
| 4457 | |
| 4458 | const char *startBuf = SM->getCharacterData(DeclLoc); |
| 4459 | const char *endBuf = startBuf; |
| 4460 | // scan backward (from the decl location) for the end of the previous decl. |
| 4461 | while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart) |
| 4462 | startBuf--; |
| 4463 | |
| 4464 | // *startBuf != '^' if we are dealing with a pointer to function that |
| 4465 | // may take block argument types (which will be handled below). |
| 4466 | if (*startBuf == '^') { |
| 4467 | // Replace the '^' with '*', computing a negative offset. |
| 4468 | DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf); |
| 4469 | ReplaceText(DeclLoc, 1, "*", 1); |
| 4470 | } |
| 4471 | if (PointerTypeTakesAnyBlockArguments(DeclT)) { |
| 4472 | // Replace the '^' with '*' for arguments. |
| 4473 | DeclLoc = ND->getLocation(); |
| 4474 | startBuf = SM->getCharacterData(DeclLoc); |
| 4475 | const char *argListBegin, *argListEnd; |
| 4476 | GetExtentOfArgList(startBuf, argListBegin, argListEnd); |
| 4477 | while (argListBegin < argListEnd) { |
| 4478 | if (*argListBegin == '^') { |
| 4479 | SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf); |
| 4480 | ReplaceText(CaretLoc, 1, "*", 1); |
| 4481 | } |
| 4482 | argListBegin++; |
| 4483 | } |
| 4484 | } |
| 4485 | return; |
| 4486 | } |
| 4487 | |
| 4488 | |
| 4489 | /// SynthesizeByrefCopyDestroyHelper - This routine synthesizes: |
| 4490 | /// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst, |
| 4491 | /// struct Block_byref_id_object *src) { |
| 4492 | /// _Block_object_assign (&_dest->object, _src->object, |
| 4493 | /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT |
| 4494 | /// [|BLOCK_FIELD_IS_WEAK]) // object |
| 4495 | /// _Block_object_assign(&_dest->object, _src->object, |
| 4496 | /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK |
| 4497 | /// [|BLOCK_FIELD_IS_WEAK]) // block |
| 4498 | /// } |
| 4499 | /// And: |
| 4500 | /// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) { |
| 4501 | /// _Block_object_dispose(_src->object, |
| 4502 | /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT |
| 4503 | /// [|BLOCK_FIELD_IS_WEAK]) // object |
| 4504 | /// _Block_object_dispose(_src->object, |
| 4505 | /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK |
| 4506 | /// [|BLOCK_FIELD_IS_WEAK]) // block |
| 4507 | /// } |
| 4508 | |
| 4509 | std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD, |
| 4510 | int flag) { |
| 4511 | std::string S; |
| 4512 | if (CopyDestroyCache.count(flag)) |
| 4513 | return S; |
| 4514 | CopyDestroyCache.insert(flag); |
| 4515 | S = "static void __Block_byref_id_object_copy_"; |
| 4516 | S += utostr(flag); |
| 4517 | S += "(void *dst, void *src) {\n"; |
| 4518 | |
| 4519 | // offset into the object pointer is computed as: |
| 4520 | // void * + void* + int + int + void* + void * |
| 4521 | unsigned IntSize = |
| 4522 | static_cast<unsigned>(Context->getTypeSize(Context->IntTy)); |
| 4523 | unsigned VoidPtrSize = |
| 4524 | static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy)); |
| 4525 | |
| 4526 | unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8; |
| 4527 | S += " _Block_object_assign((char*)dst + "; |
| 4528 | S += utostr(offset); |
| 4529 | S += ", *(void * *) ((char*)src + "; |
| 4530 | S += utostr(offset); |
| 4531 | S += "), "; |
| 4532 | S += utostr(flag); |
| 4533 | S += ");\n}\n"; |
| 4534 | |
| 4535 | S += "static void __Block_byref_id_object_dispose_"; |
| 4536 | S += utostr(flag); |
| 4537 | S += "(void *src) {\n"; |
| 4538 | S += " _Block_object_dispose(*(void * *) ((char*)src + "; |
| 4539 | S += utostr(offset); |
| 4540 | S += "), "; |
| 4541 | S += utostr(flag); |
| 4542 | S += ");\n}\n"; |
| 4543 | return S; |
| 4544 | } |
| 4545 | |
| 4546 | /// RewriteByRefVar - For each __block typex ND variable this routine transforms |
| 4547 | /// the declaration into: |
| 4548 | /// struct __Block_byref_ND { |
| 4549 | /// void *__isa; // NULL for everything except __weak pointers |
| 4550 | /// struct __Block_byref_ND *__forwarding; |
| 4551 | /// int32_t __flags; |
| 4552 | /// int32_t __size; |
| 4553 | /// void *__Block_byref_id_object_copy; // If variable is __block ObjC object |
| 4554 | /// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object |
| 4555 | /// typex ND; |
| 4556 | /// }; |
| 4557 | /// |
| 4558 | /// It then replaces declaration of ND variable with: |
| 4559 | /// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag, |
| 4560 | /// __size=sizeof(struct __Block_byref_ND), |
| 4561 | /// ND=initializer-if-any}; |
| 4562 | /// |
| 4563 | /// |
| 4564 | void RewriteObjC::RewriteByRefVar(VarDecl *ND) { |
| 4565 | // Insert declaration for the function in which block literal is |
| 4566 | // used. |
| 4567 | if (CurFunctionDeclToDeclareForBlock) |
| 4568 | RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock); |
| 4569 | int flag = 0; |
| 4570 | int isa = 0; |
| 4571 | SourceLocation DeclLoc = ND->getTypeSpecStartLoc(); |
| 4572 | const char *startBuf = SM->getCharacterData(DeclLoc); |
| 4573 | SourceLocation X = ND->getLocEnd(); |
| 4574 | X = SM->getInstantiationLoc(X); |
| 4575 | const char *endBuf = SM->getCharacterData(X); |
| 4576 | std::string Name(ND->getNameAsString()); |
| 4577 | std::string ByrefType; |
| 4578 | RewriteByRefString(ByrefType, Name, ND); |
| 4579 | ByrefType += " {\n"; |
| 4580 | ByrefType += " void *__isa;\n"; |
| 4581 | RewriteByRefString(ByrefType, Name, ND); |
| 4582 | ByrefType += " *__forwarding;\n"; |
| 4583 | ByrefType += " int __flags;\n"; |
| 4584 | ByrefType += " int __size;\n"; |
| 4585 | // Add void *__Block_byref_id_object_copy; |
| 4586 | // void *__Block_byref_id_object_dispose; if needed. |
| 4587 | QualType Ty = ND->getType(); |
| 4588 | bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty); |
| 4589 | if (HasCopyAndDispose) { |
| 4590 | ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n"; |
| 4591 | ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n"; |
| 4592 | } |
| 4593 | |
| 4594 | Ty.getAsStringInternal(Name, Context->PrintingPolicy); |
| 4595 | ByrefType += " " + Name + ";\n"; |
| 4596 | ByrefType += "};\n"; |
| 4597 | // Insert this type in global scope. It is needed by helper function. |
| 4598 | SourceLocation FunLocStart; |
| 4599 | if (CurFunctionDef) |
| 4600 | FunLocStart = CurFunctionDef->getTypeSpecStartLoc(); |
| 4601 | else { |
| 4602 | assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null"); |
| 4603 | FunLocStart = CurMethodDef->getLocStart(); |
| 4604 | } |
| 4605 | InsertText(FunLocStart, ByrefType.c_str(), ByrefType.size()); |
| 4606 | if (Ty.isObjCGCWeak()) { |
| 4607 | flag |= BLOCK_FIELD_IS_WEAK; |
| 4608 | isa = 1; |
| 4609 | } |
| 4610 | |
| 4611 | if (HasCopyAndDispose) { |
| 4612 | flag = BLOCK_BYREF_CALLER; |
| 4613 | QualType Ty = ND->getType(); |
| 4614 | // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well. |
| 4615 | if (Ty->isBlockPointerType()) |
| 4616 | flag |= BLOCK_FIELD_IS_BLOCK; |
| 4617 | else |
| 4618 | flag |= BLOCK_FIELD_IS_OBJECT; |
| 4619 | std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag); |
| 4620 | if (!HF.empty()) |
| 4621 | InsertText(FunLocStart, HF.c_str(), HF.size()); |
| 4622 | } |
| 4623 | |
| 4624 | // struct __Block_byref_ND ND = |
| 4625 | // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND), |
| 4626 | // initializer-if-any}; |
| 4627 | bool hasInit = (ND->getInit() != 0); |
| 4628 | unsigned flags = 0; |
| 4629 | if (HasCopyAndDispose) |
| 4630 | flags |= BLOCK_HAS_COPY_DISPOSE; |
| 4631 | Name = ND->getNameAsString(); |
| 4632 | ByrefType.clear(); |
| 4633 | RewriteByRefString(ByrefType, Name, ND); |
| 4634 | std::string ForwardingCastType("("); |
| 4635 | ForwardingCastType += ByrefType + " *)"; |
| 4636 | if (!hasInit) { |
| 4637 | ByrefType += " " + Name + " = {(void*)"; |
| 4638 | ByrefType += utostr(isa); |
| 4639 | ByrefType += "," + ForwardingCastType + "&" + Name + ", "; |
| 4640 | ByrefType += utostr(flags); |
| 4641 | ByrefType += ", "; |
| 4642 | ByrefType += "sizeof("; |
| 4643 | RewriteByRefString(ByrefType, Name, ND); |
| 4644 | ByrefType += ")"; |
| 4645 | if (HasCopyAndDispose) { |
| 4646 | ByrefType += ", __Block_byref_id_object_copy_"; |
| 4647 | ByrefType += utostr(flag); |
| 4648 | ByrefType += ", __Block_byref_id_object_dispose_"; |
| 4649 | ByrefType += utostr(flag); |
| 4650 | } |
| 4651 | ByrefType += "};\n"; |
| 4652 | ReplaceText(DeclLoc, endBuf-startBuf+Name.size(), |
| 4653 | ByrefType.c_str(), ByrefType.size()); |
| 4654 | } |
| 4655 | else { |
| 4656 | SourceLocation startLoc; |
| 4657 | Expr *E = ND->getInit(); |
| 4658 | if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) |
| 4659 | startLoc = ECE->getLParenLoc(); |
| 4660 | else |
| 4661 | startLoc = E->getLocStart(); |
| 4662 | startLoc = SM->getInstantiationLoc(startLoc); |
| 4663 | endBuf = SM->getCharacterData(startLoc); |
| 4664 | |
| 4665 | ByrefType += " " + Name; |
| 4666 | ByrefType += " = {(void*)"; |
| 4667 | ByrefType += utostr(isa); |
| 4668 | ByrefType += "," + ForwardingCastType + "&" + Name + ", "; |
| 4669 | ByrefType += utostr(flags); |
| 4670 | ByrefType += ", "; |
| 4671 | ByrefType += "sizeof("; |
| 4672 | RewriteByRefString(ByrefType, Name, ND); |
| 4673 | ByrefType += "), "; |
| 4674 | if (HasCopyAndDispose) { |
| 4675 | ByrefType += "__Block_byref_id_object_copy_"; |
| 4676 | ByrefType += utostr(flag); |
| 4677 | ByrefType += ", __Block_byref_id_object_dispose_"; |
| 4678 | ByrefType += utostr(flag); |
| 4679 | ByrefType += ", "; |
| 4680 | } |
| 4681 | ReplaceText(DeclLoc, endBuf-startBuf, |
| 4682 | ByrefType.c_str(), ByrefType.size()); |
| 4683 | |
| 4684 | // Complete the newly synthesized compound expression by inserting a right |
| 4685 | // curly brace before the end of the declaration. |
| 4686 | // FIXME: This approach avoids rewriting the initializer expression. It |
| 4687 | // also assumes there is only one declarator. For example, the following |
| 4688 | // isn't currently supported by this routine (in general): |
| 4689 | // |
| 4690 | // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37; |
| 4691 | // |
| 4692 | const char *startBuf = SM->getCharacterData(startLoc); |
| 4693 | const char *semiBuf = strchr(startBuf, ';'); |
| 4694 | assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'"); |
| 4695 | SourceLocation semiLoc = |
| 4696 | startLoc.getFileLocWithOffset(semiBuf-startBuf); |
| 4697 | |
| 4698 | InsertText(semiLoc, "}", 1); |
| 4699 | } |
| 4700 | return; |
| 4701 | } |
| 4702 | |
| 4703 | void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) { |
| 4704 | // Add initializers for any closure decl refs. |
| 4705 | GetBlockDeclRefExprs(Exp->getBody()); |
| 4706 | if (BlockDeclRefs.size()) { |
| 4707 | // Unique all "by copy" declarations. |
| 4708 | for (unsigned i = 0; i < BlockDeclRefs.size(); i++) |
| 4709 | if (!BlockDeclRefs[i]->isByRef()) |
| 4710 | BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl()); |
| 4711 | // Unique all "by ref" declarations. |
| 4712 | for (unsigned i = 0; i < BlockDeclRefs.size(); i++) |
| 4713 | if (BlockDeclRefs[i]->isByRef()) { |
| 4714 | BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl()); |
| 4715 | } |
| 4716 | // Find any imported blocks...they will need special attention. |
| 4717 | for (unsigned i = 0; i < BlockDeclRefs.size(); i++) |
| 4718 | if (BlockDeclRefs[i]->isByRef() || |
| 4719 | BlockDeclRefs[i]->getType()->isObjCObjectPointerType() || |
| 4720 | BlockDeclRefs[i]->getType()->isBlockPointerType()) { |
| 4721 | GetBlockCallExprs(BlockDeclRefs[i]); |
| 4722 | ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl()); |
| 4723 | } |
| 4724 | } |
| 4725 | } |
| 4726 | |
| 4727 | FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) { |
| 4728 | IdentifierInfo *ID = &Context->Idents.get(name); |
| 4729 | QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy); |
| 4730 | return FunctionDecl::Create(*Context, TUDecl,SourceLocation(), |
| 4731 | ID, FType, 0, FunctionDecl::Extern, false, |
| 4732 | false); |
| 4733 | } |
| 4734 | |
| 4735 | Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) { |
| 4736 | Blocks.push_back(Exp); |
| 4737 | |
| 4738 | CollectBlockDeclRefInfo(Exp); |
| 4739 | std::string FuncName; |
| 4740 | |
| 4741 | if (CurFunctionDef) |
| 4742 | FuncName = CurFunctionDef->getNameAsString(); |
| 4743 | else if (CurMethodDef) { |
| 4744 | FuncName = CurMethodDef->getSelector().getAsString(); |
| 4745 | // Convert colons to underscores. |
| 4746 | std::string::size_type loc = 0; |
| 4747 | while ((loc = FuncName.find(":", loc)) != std::string::npos) |
| 4748 | FuncName.replace(loc, 1, "_"); |
| 4749 | } else if (GlobalVarDecl) |
| 4750 | FuncName = std::string(GlobalVarDecl->getNameAsString()); |
| 4751 | |
| 4752 | std::string BlockNumber = utostr(Blocks.size()-1); |
| 4753 | |
| 4754 | std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber; |
| 4755 | std::string Func = "__" + FuncName + "_block_func_" + BlockNumber; |
| 4756 | |
| 4757 | // Get a pointer to the function type so we can cast appropriately. |
| 4758 | QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0)); |
| 4759 | |
| 4760 | FunctionDecl *FD; |
| 4761 | Expr *NewRep; |
| 4762 | |
| 4763 | // Simulate a contructor call... |
| 4764 | FD = SynthBlockInitFunctionDecl(Tag.c_str()); |
| 4765 | DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation()); |
| 4766 | |
| 4767 | llvm::SmallVector<Expr*, 4> InitExprs; |
| 4768 | |
| 4769 | // Initialize the block function. |
| 4770 | FD = SynthBlockInitFunctionDecl(Func.c_str()); |
| 4771 | DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(), |
| 4772 | SourceLocation()); |
| 4773 | CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy, |
| 4774 | CastExpr::CK_Unknown, Arg); |
| 4775 | InitExprs.push_back(castExpr); |
| 4776 | |
| 4777 | // Initialize the block descriptor. |
| 4778 | std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA"; |
| 4779 | |
| 4780 | VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(), |
| 4781 | &Context->Idents.get(DescData.c_str()), |
| 4782 | Context->VoidPtrTy, 0, |
| 4783 | VarDecl::Static); |
| 4784 | UnaryOperator *DescRefExpr = new (Context) UnaryOperator( |
| 4785 | new (Context) DeclRefExpr(NewVD, |
| 4786 | Context->VoidPtrTy, SourceLocation()), |
| 4787 | UnaryOperator::AddrOf, |
| 4788 | Context->getPointerType(Context->VoidPtrTy), |
| 4789 | SourceLocation()); |
| 4790 | InitExprs.push_back(DescRefExpr); |
| 4791 | |
| 4792 | // Add initializers for any closure decl refs. |
| 4793 | if (BlockDeclRefs.size()) { |
| 4794 | Expr *Exp; |
| 4795 | // Output all "by copy" declarations. |
| 4796 | for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(), |
| 4797 | E = BlockByCopyDecls.end(); I != E; ++I) { |
| 4798 | if (isObjCType((*I)->getType())) { |
| 4799 | // FIXME: Conform to ABI ([[obj retain] autorelease]). |
| 4800 | FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString()); |
| 4801 | Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation()); |
| 4802 | } else if (isTopLevelBlockPointerType((*I)->getType())) { |
| 4803 | FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString()); |
| 4804 | Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation()); |
| 4805 | Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy, |
| 4806 | CastExpr::CK_Unknown, Arg); |
| 4807 | } else { |
| 4808 | FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString()); |
| 4809 | Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation()); |
| 4810 | } |
| 4811 | InitExprs.push_back(Exp); |
| 4812 | } |
| 4813 | // Output all "by ref" declarations. |
| 4814 | for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(), |
| 4815 | E = BlockByRefDecls.end(); I != E; ++I) { |
| 4816 | ValueDecl *ND = (*I); |
| 4817 | std::string Name(ND->getNameAsString()); |
| 4818 | std::string RecName; |
| 4819 | RewriteByRefString(RecName, Name, ND); |
| 4820 | IdentifierInfo *II = &Context->Idents.get(RecName.c_str() |
| 4821 | + sizeof("struct")); |
| 4822 | RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl, |
| 4823 | SourceLocation(), II); |
| 4824 | assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl"); |
| 4825 | QualType castT = Context->getPointerType(Context->getTagDeclType(RD)); |
| 4826 | |
| 4827 | FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString()); |
| 4828 | Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation()); |
| 4829 | Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf, |
| 4830 | Context->getPointerType(Exp->getType()), |
| 4831 | SourceLocation()); |
| 4832 | Exp = NoTypeInfoCStyleCastExpr(Context, castT, CastExpr::CK_Unknown, Exp); |
| 4833 | InitExprs.push_back(Exp); |
| 4834 | } |
| 4835 | } |
| 4836 | if (ImportedBlockDecls.size()) { |
| 4837 | // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR |
| 4838 | int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR); |
| 4839 | unsigned IntSize = |
| 4840 | static_cast<unsigned>(Context->getTypeSize(Context->IntTy)); |
| 4841 | Expr *FlagExp = new (Context) IntegerLiteral(llvm::APInt(IntSize, flag), |
| 4842 | Context->IntTy, SourceLocation()); |
| 4843 | InitExprs.push_back(FlagExp); |
| 4844 | } |
| 4845 | NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(), |
| 4846 | FType, SourceLocation()); |
| 4847 | NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf, |
| 4848 | Context->getPointerType(NewRep->getType()), |
| 4849 | SourceLocation()); |
| 4850 | NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CastExpr::CK_Unknown, |
| 4851 | NewRep); |
| 4852 | BlockDeclRefs.clear(); |
| 4853 | BlockByRefDecls.clear(); |
| 4854 | BlockByCopyDecls.clear(); |
| 4855 | ImportedBlockDecls.clear(); |
| 4856 | return NewRep; |
| 4857 | } |
| 4858 | |
| 4859 | //===----------------------------------------------------------------------===// |
| 4860 | // Function Body / Expression rewriting |
| 4861 | //===----------------------------------------------------------------------===// |
| 4862 | |
| 4863 | // This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer(). |
| 4864 | // The allows the main rewrite loop to associate all ObjCPropertyRefExprs with |
| 4865 | // their respective BinaryOperator. Without this knowledge, we'd need to rewrite |
| 4866 | // the ObjCPropertyRefExpr twice (once as a getter, and later as a setter). |
| 4867 | // Since the rewriter isn't capable of rewriting rewritten code, it's important |
| 4868 | // we get this right. |
| 4869 | void RewriteObjC::CollectPropertySetters(Stmt *S) { |
| 4870 | // Perform a bottom up traversal of all children. |
| 4871 | for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); |
| 4872 | CI != E; ++CI) |
| 4873 | if (*CI) |
| 4874 | CollectPropertySetters(*CI); |
| 4875 | |
| 4876 | if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) { |
| 4877 | if (BinOp->isAssignmentOp()) { |
| 4878 | if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS())) |
| 4879 | PropSetters[PRE] = BinOp; |
| 4880 | } |
| 4881 | } |
| 4882 | } |
| 4883 | |
| 4884 | Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) { |
| 4885 | if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || |
| 4886 | isa<DoStmt>(S) || isa<ForStmt>(S)) |
| 4887 | Stmts.push_back(S); |
| 4888 | else if (isa<ObjCForCollectionStmt>(S)) { |
| 4889 | Stmts.push_back(S); |
| 4890 | ObjCBcLabelNo.push_back(++BcLabelCount); |
| 4891 | } |
| 4892 | |
| 4893 | SourceRange OrigStmtRange = S->getSourceRange(); |
| 4894 | |
| 4895 | // Perform a bottom up rewrite of all children. |
| 4896 | for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); |
| 4897 | CI != E; ++CI) |
| 4898 | if (*CI) { |
| 4899 | Stmt *newStmt; |
| 4900 | Stmt *S = (*CI); |
| 4901 | if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) { |
| 4902 | Expr *OldBase = IvarRefExpr->getBase(); |
| 4903 | bool replaced = false; |
| 4904 | newStmt = RewriteObjCNestedIvarRefExpr(S, replaced); |
| 4905 | if (replaced) { |
| 4906 | if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt)) |
| 4907 | ReplaceStmt(OldBase, IRE->getBase()); |
| 4908 | else |
| 4909 | ReplaceStmt(S, newStmt); |
| 4910 | } |
| 4911 | } |
| 4912 | else |
| 4913 | newStmt = RewriteFunctionBodyOrGlobalInitializer(S); |
| 4914 | if (newStmt) |
| 4915 | *CI = newStmt; |
| 4916 | } |
| 4917 | |
| 4918 | if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) { |
| 4919 | // Rewrite the block body in place. |
| 4920 | RewriteFunctionBodyOrGlobalInitializer(BE->getBody()); |
| 4921 | |
| 4922 | // Now we snarf the rewritten text and stash it away for later use. |
| 4923 | std::string Str = Rewrite.getRewrittenText(BE->getSourceRange()); |
| 4924 | RewrittenBlockExprs[BE] = Str; |
| 4925 | |
| 4926 | Stmt *blockTranscribed = SynthBlockInitExpr(BE); |
| 4927 | //blockTranscribed->dump(); |
| 4928 | ReplaceStmt(S, blockTranscribed); |
| 4929 | return blockTranscribed; |
| 4930 | } |
| 4931 | // Handle specific things. |
| 4932 | if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S)) |
| 4933 | return RewriteAtEncode(AtEncode); |
| 4934 | |
| 4935 | if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) { |
| 4936 | BinaryOperator *BinOp = PropSetters[PropRefExpr]; |
| 4937 | if (BinOp) { |
| 4938 | // Because the rewriter doesn't allow us to rewrite rewritten code, |
| 4939 | // we need to rewrite the right hand side prior to rewriting the setter. |
| 4940 | DisableReplaceStmt = true; |
| 4941 | // Save the source range. Even if we disable the replacement, the |
| 4942 | // rewritten node will have been inserted into the tree. If the synthesized |
| 4943 | // node is at the 'end', the rewriter will fail. Consider this: |
| 4944 | // self.errorHandler = handler ? handler : |
| 4945 | // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; }; |
| 4946 | SourceRange SrcRange = BinOp->getSourceRange(); |
| 4947 | Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS()); |
| 4948 | DisableReplaceStmt = false; |
| 4949 | // |
| 4950 | // Unlike the main iterator, we explicily avoid changing 'BinOp'. If |
| 4951 | // we changed the RHS of BinOp, the rewriter would fail (since it needs |
| 4952 | // to see the original expression). Consider this example: |
| 4953 | // |
| 4954 | // Foo *obj1, *obj2; |
| 4955 | // |
| 4956 | // obj1.i = [obj2 rrrr]; |
| 4957 | // |
| 4958 | // 'BinOp' for the previous expression looks like: |
| 4959 | // |
| 4960 | // (BinaryOperator 0x231ccf0 'int' '=' |
| 4961 | // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i" |
| 4962 | // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0)) |
| 4963 | // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr |
| 4964 | // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0))) |
| 4965 | // |
| 4966 | // 'newStmt' represents the rewritten message expression. For example: |
| 4967 | // |
| 4968 | // (CallExpr 0x231d300 'id':'struct objc_object *' |
| 4969 | // (ParenExpr 0x231d2e0 'int (*)(id, SEL)' |
| 4970 | // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)' |
| 4971 | // (CStyleCastExpr 0x231d220 'void *' |
| 4972 | // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0)))) |
| 4973 | // |
| 4974 | // Note that 'newStmt' is passed to RewritePropertySetter so that it |
| 4975 | // can be used as the setter argument. ReplaceStmt() will still 'see' |
| 4976 | // the original RHS (since we haven't altered BinOp). |
| 4977 | // |
| 4978 | // This implies the Rewrite* routines can no longer delete the original |
| 4979 | // node. As a result, we now leak the original AST nodes. |
| 4980 | // |
| 4981 | return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange); |
| 4982 | } else { |
| 4983 | return RewritePropertyGetter(PropRefExpr); |
| 4984 | } |
| 4985 | } |
| 4986 | if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S)) |
| 4987 | return RewriteAtSelector(AtSelector); |
| 4988 | |
| 4989 | if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S)) |
| 4990 | return RewriteObjCStringLiteral(AtString); |
| 4991 | |
| 4992 | if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) { |
| 4993 | #if 0 |
| 4994 | // Before we rewrite it, put the original message expression in a comment. |
| 4995 | SourceLocation startLoc = MessExpr->getLocStart(); |
| 4996 | SourceLocation endLoc = MessExpr->getLocEnd(); |
| 4997 | |
| 4998 | const char *startBuf = SM->getCharacterData(startLoc); |
| 4999 | const char *endBuf = SM->getCharacterData(endLoc); |
| 5000 | |
| 5001 | std::string messString; |
| 5002 | messString += "// "; |
| 5003 | messString.append(startBuf, endBuf-startBuf+1); |
| 5004 | messString += "\n"; |
| 5005 | |
| 5006 | // FIXME: Missing definition of |
| 5007 | // InsertText(clang::SourceLocation, char const*, unsigned int). |
| 5008 | // InsertText(startLoc, messString.c_str(), messString.size()); |
| 5009 | // Tried this, but it didn't work either... |
| 5010 | // ReplaceText(startLoc, 0, messString.c_str(), messString.size()); |
| 5011 | #endif |
| 5012 | return RewriteMessageExpr(MessExpr); |
| 5013 | } |
| 5014 | |
| 5015 | if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S)) |
| 5016 | return RewriteObjCTryStmt(StmtTry); |
| 5017 | |
| 5018 | if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S)) |
| 5019 | return RewriteObjCSynchronizedStmt(StmtTry); |
| 5020 | |
| 5021 | if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S)) |
| 5022 | return RewriteObjCThrowStmt(StmtThrow); |
| 5023 | |
| 5024 | if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S)) |
| 5025 | return RewriteObjCProtocolExpr(ProtocolExp); |
| 5026 | |
| 5027 | if (ObjCForCollectionStmt *StmtForCollection = |
| 5028 | dyn_cast<ObjCForCollectionStmt>(S)) |
| 5029 | return RewriteObjCForCollectionStmt(StmtForCollection, |
| 5030 | OrigStmtRange.getEnd()); |
| 5031 | if (BreakStmt *StmtBreakStmt = |
| 5032 | dyn_cast<BreakStmt>(S)) |
| 5033 | return RewriteBreakStmt(StmtBreakStmt); |
| 5034 | if (ContinueStmt *StmtContinueStmt = |
| 5035 | dyn_cast<ContinueStmt>(S)) |
| 5036 | return RewriteContinueStmt(StmtContinueStmt); |
| 5037 | |
| 5038 | // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls |
| 5039 | // and cast exprs. |
| 5040 | if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) { |
| 5041 | // FIXME: What we're doing here is modifying the type-specifier that |
| 5042 | // precedes the first Decl. In the future the DeclGroup should have |
| 5043 | // a separate type-specifier that we can rewrite. |
| 5044 | // NOTE: We need to avoid rewriting the DeclStmt if it is within |
| 5045 | // the context of an ObjCForCollectionStmt. For example: |
| 5046 | // NSArray *someArray; |
| 5047 | // for (id <FooProtocol> index in someArray) ; |
| 5048 | // This is because RewriteObjCForCollectionStmt() does textual rewriting |
| 5049 | // and it depends on the original text locations/positions. |
| 5050 | if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back())) |
| 5051 | RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin()); |
| 5052 | |
| 5053 | // Blocks rewrite rules. |
| 5054 | for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end(); |
| 5055 | DI != DE; ++DI) { |
| 5056 | Decl *SD = *DI; |
| 5057 | if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) { |
| 5058 | if (isTopLevelBlockPointerType(ND->getType())) |
| 5059 | RewriteBlockPointerDecl(ND); |
| 5060 | else if (ND->getType()->isFunctionPointerType()) |
| 5061 | CheckFunctionPointerDecl(ND->getType(), ND); |
| 5062 | if (VarDecl *VD = dyn_cast<VarDecl>(SD)) |
| 5063 | if (VD->hasAttr<BlocksAttr>()) { |
| 5064 | static unsigned uniqueByrefDeclCount = 0; |
| 5065 | assert(!BlockByRefDeclNo.count(ND) && |
| 5066 | "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl"); |
| 5067 | BlockByRefDeclNo[ND] = uniqueByrefDeclCount++; |
| 5068 | RewriteByRefVar(VD); |
| 5069 | } |
| 5070 | } |
| 5071 | if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) { |
| 5072 | if (isTopLevelBlockPointerType(TD->getUnderlyingType())) |
| 5073 | RewriteBlockPointerDecl(TD); |
| 5074 | else if (TD->getUnderlyingType()->isFunctionPointerType()) |
| 5075 | CheckFunctionPointerDecl(TD->getUnderlyingType(), TD); |
| 5076 | } |
| 5077 | } |
| 5078 | } |
| 5079 | |
| 5080 | if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) |
| 5081 | RewriteObjCQualifiedInterfaceTypes(CE); |
| 5082 | |
| 5083 | if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || |
| 5084 | isa<DoStmt>(S) || isa<ForStmt>(S)) { |
| 5085 | assert(!Stmts.empty() && "Statement stack is empty"); |
| 5086 | assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) || |
| 5087 | isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back())) |
| 5088 | && "Statement stack mismatch"); |
| 5089 | Stmts.pop_back(); |
| 5090 | } |
| 5091 | // Handle blocks rewriting. |
| 5092 | if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) { |
| 5093 | if (BDRE->isByRef()) |
| 5094 | return RewriteBlockDeclRefExpr(BDRE); |
| 5095 | } |
| 5096 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) { |
| 5097 | ValueDecl *VD = DRE->getDecl(); |
| 5098 | if (VD->hasAttr<BlocksAttr>()) |
| 5099 | return RewriteBlockDeclRefExpr(DRE); |
| 5100 | } |
| 5101 | |
| 5102 | if (CallExpr *CE = dyn_cast<CallExpr>(S)) { |
| 5103 | if (CE->getCallee()->getType()->isBlockPointerType()) { |
| 5104 | Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee()); |
| 5105 | ReplaceStmt(S, BlockCall); |
| 5106 | return BlockCall; |
| 5107 | } |
| 5108 | } |
| 5109 | if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) { |
| 5110 | RewriteCastExpr(CE); |
| 5111 | } |
| 5112 | #if 0 |
| 5113 | if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) { |
| 5114 | CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation()); |
| 5115 | // Get the new text. |
| 5116 | std::string SStr; |
| 5117 | llvm::raw_string_ostream Buf(SStr); |
| 5118 | Replacement->printPretty(Buf, *Context); |
| 5119 | const std::string &Str = Buf.str(); |
| 5120 | |
| 5121 | printf("CAST = %s\n", &Str[0]); |
| 5122 | InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size()); |
| 5123 | delete S; |
| 5124 | return Replacement; |
| 5125 | } |
| 5126 | #endif |
| 5127 | // Return this stmt unmodified. |
| 5128 | return S; |
| 5129 | } |
| 5130 | |
| 5131 | void RewriteObjC::RewriteRecordBody(RecordDecl *RD) { |
| 5132 | for (RecordDecl::field_iterator i = RD->field_begin(), |
| 5133 | e = RD->field_end(); i != e; ++i) { |
| 5134 | FieldDecl *FD = *i; |
| 5135 | if (isTopLevelBlockPointerType(FD->getType())) |
| 5136 | RewriteBlockPointerDecl(FD); |
| 5137 | if (FD->getType()->isObjCQualifiedIdType() || |
| 5138 | FD->getType()->isObjCQualifiedInterfaceType()) |
| 5139 | RewriteObjCQualifiedInterfaceTypes(FD); |
| 5140 | } |
| 5141 | } |
| 5142 | |
| 5143 | /// HandleDeclInMainFile - This is called for each top-level decl defined in the |
| 5144 | /// main file of the input. |
| 5145 | void RewriteObjC::HandleDeclInMainFile(Decl *D) { |
| 5146 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { |
| 5147 | if (FD->isOverloadedOperator()) |
| 5148 | return; |
| 5149 | |
| 5150 | // Since function prototypes don't have ParmDecl's, we check the function |
| 5151 | // prototype. This enables us to rewrite function declarations and |
| 5152 | // definitions using the same code. |
| 5153 | RewriteBlocksInFunctionProtoType(FD->getType(), FD); |
| 5154 | |
| 5155 | // FIXME: If this should support Obj-C++, support CXXTryStmt |
| 5156 | if (CompoundStmt *Body = FD->getCompoundBody()) { |
| 5157 | CurFunctionDef = FD; |
| 5158 | CurFunctionDeclToDeclareForBlock = FD; |
| 5159 | CollectPropertySetters(Body); |
| 5160 | CurrentBody = Body; |
| 5161 | Body = |
| 5162 | cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body)); |
| 5163 | FD->setBody(Body); |
| 5164 | CurrentBody = 0; |
| 5165 | if (PropParentMap) { |
| 5166 | delete PropParentMap; |
| 5167 | PropParentMap = 0; |
| 5168 | } |
| 5169 | // This synthesizes and inserts the block "impl" struct, invoke function, |
| 5170 | // and any copy/dispose helper functions. |
| 5171 | InsertBlockLiteralsWithinFunction(FD); |
| 5172 | CurFunctionDef = 0; |
| 5173 | CurFunctionDeclToDeclareForBlock = 0; |
| 5174 | } |
| 5175 | return; |
| 5176 | } |
| 5177 | if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { |
| 5178 | if (CompoundStmt *Body = MD->getCompoundBody()) { |
| 5179 | CurMethodDef = MD; |
| 5180 | CollectPropertySetters(Body); |
| 5181 | CurrentBody = Body; |
| 5182 | Body = |
| 5183 | cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body)); |
| 5184 | MD->setBody(Body); |
| 5185 | CurrentBody = 0; |
| 5186 | if (PropParentMap) { |
| 5187 | delete PropParentMap; |
| 5188 | PropParentMap = 0; |
| 5189 | } |
| 5190 | InsertBlockLiteralsWithinMethod(MD); |
| 5191 | CurMethodDef = 0; |
| 5192 | } |
| 5193 | } |
| 5194 | if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D)) |
| 5195 | ClassImplementation.push_back(CI); |
| 5196 | else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D)) |
| 5197 | CategoryImplementation.push_back(CI); |
| 5198 | else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D)) |
| 5199 | RewriteForwardClassDecl(CD); |
| 5200 | else if (VarDecl *VD = dyn_cast<VarDecl>(D)) { |
| 5201 | RewriteObjCQualifiedInterfaceTypes(VD); |
| 5202 | if (isTopLevelBlockPointerType(VD->getType())) |
| 5203 | RewriteBlockPointerDecl(VD); |
| 5204 | else if (VD->getType()->isFunctionPointerType()) { |
| 5205 | CheckFunctionPointerDecl(VD->getType(), VD); |
| 5206 | if (VD->getInit()) { |
| 5207 | if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) { |
| 5208 | RewriteCastExpr(CE); |
| 5209 | } |
| 5210 | } |
| 5211 | } else if (VD->getType()->isRecordType()) { |
| 5212 | RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl(); |
| 5213 | if (RD->isDefinition()) |
| 5214 | RewriteRecordBody(RD); |
| 5215 | } |
| 5216 | if (VD->getInit()) { |
| 5217 | GlobalVarDecl = VD; |
| 5218 | CollectPropertySetters(VD->getInit()); |
| 5219 | CurrentBody = VD->getInit(); |
| 5220 | RewriteFunctionBodyOrGlobalInitializer(VD->getInit()); |
| 5221 | CurrentBody = 0; |
| 5222 | if (PropParentMap) { |
| 5223 | delete PropParentMap; |
| 5224 | PropParentMap = 0; |
| 5225 | } |
| 5226 | SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), |
| 5227 | VD->getNameAsCString()); |
| 5228 | GlobalVarDecl = 0; |
| 5229 | |
| 5230 | // This is needed for blocks. |
| 5231 | if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) { |
| 5232 | RewriteCastExpr(CE); |
| 5233 | } |
| 5234 | } |
| 5235 | return; |
| 5236 | } |
| 5237 | if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) { |
| 5238 | if (isTopLevelBlockPointerType(TD->getUnderlyingType())) |
| 5239 | RewriteBlockPointerDecl(TD); |
| 5240 | else if (TD->getUnderlyingType()->isFunctionPointerType()) |
| 5241 | CheckFunctionPointerDecl(TD->getUnderlyingType(), TD); |
| 5242 | else if (TD->getUnderlyingType()->isRecordType()) { |
| 5243 | RecordDecl *RD = TD->getUnderlyingType()->getAs<RecordType>()->getDecl(); |
| 5244 | if (RD->isDefinition()) |
| 5245 | RewriteRecordBody(RD); |
| 5246 | } |
| 5247 | return; |
| 5248 | } |
| 5249 | if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) { |
| 5250 | if (RD->isDefinition()) |
| 5251 | RewriteRecordBody(RD); |
| 5252 | return; |
| 5253 | } |
| 5254 | // Nothing yet. |
| 5255 | } |
| 5256 | |
| 5257 | void RewriteObjC::HandleTranslationUnit(ASTContext &C) { |
| 5258 | if (Diags.hasErrorOccurred()) |
| 5259 | return; |
| 5260 | |
| 5261 | RewriteInclude(); |
| 5262 | |
| 5263 | // Here's a great place to add any extra declarations that may be needed. |
| 5264 | // Write out meta data for each @protocol(<expr>). |
| 5265 | for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(), |
| 5266 | E = ProtocolExprDecls.end(); I != E; ++I) |
| 5267 | RewriteObjCProtocolMetaData(*I, "", "", Preamble); |
| 5268 | |
| 5269 | InsertText(SM->getLocForStartOfFile(MainFileID), |
| 5270 | Preamble.c_str(), Preamble.size(), false); |
| 5271 | if (ClassImplementation.size() || CategoryImplementation.size()) |
| 5272 | RewriteImplementations(); |
| 5273 | |
| 5274 | // Get the buffer corresponding to MainFileID. If we haven't changed it, then |
| 5275 | // we are done. |
| 5276 | if (const RewriteBuffer *RewriteBuf = |
| 5277 | Rewrite.getRewriteBufferFor(MainFileID)) { |
| 5278 | //printf("Changed:\n"); |
| 5279 | *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end()); |
| 5280 | } else { |
| 5281 | fprintf(stderr, "No changes\n"); |
| 5282 | } |
| 5283 | |
| 5284 | if (ClassImplementation.size() || CategoryImplementation.size() || |
| 5285 | ProtocolExprDecls.size()) { |
| 5286 | // Rewrite Objective-c meta data* |
| 5287 | std::string ResultStr; |
| 5288 | SynthesizeMetaDataIntoBuffer(ResultStr); |
| 5289 | // Emit metadata. |
| 5290 | *OutFile << ResultStr; |
| 5291 | } |
| 5292 | OutFile->flush(); |
| 5293 | } |
| 5294 | |