blob: 3d54816c4c0654dd90ab11eb39cfaf6b95bccc60 [file] [log] [blame]
Steve Naroffb29b4272008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattner77cd2a02007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner77cd2a02007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Daniel Dunbar9b414d32010-06-15 17:48:49 +000014#include "clang/Rewrite/ASTConsumers.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Steve Naroff8599e7a2008-12-08 16:43:47 +000018#include "clang/AST/ParentMap.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner07506182007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner26de4652007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +000023#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000025#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000026#include "llvm/ADT/SmallPtrSet.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000027#include "llvm/ADT/OwningPtr.h"
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +000028#include "llvm/ADT/DenseSet.h"
Fariborz Jahanian72952fc2010-03-01 23:36:21 +000029
Chris Lattner77cd2a02007-10-11 00:43:27 +000030using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000031using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000032
Chris Lattner77cd2a02007-10-11 00:43:27 +000033namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000034 class RewriteObjC : public ASTConsumer {
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000035 enum {
36 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
37 block, ... */
38 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
39 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
40 __block variable */
41 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
42 helpers */
43 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
44 support routines */
45 BLOCK_BYREF_CURRENT_MAX = 256
46 };
47
48 enum {
49 BLOCK_NEEDS_FREE = (1 << 24),
50 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
51 BLOCK_HAS_CXX_OBJ = (1 << 26),
52 BLOCK_IS_GC = (1 << 27),
53 BLOCK_IS_GLOBAL = (1 << 28),
54 BLOCK_HAS_DESCRIPTOR = (1 << 29)
55 };
56
Chris Lattner2c64b7b2007-10-16 21:07:07 +000057 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000058 Diagnostic &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000059 const LangOptions &LangOpts;
Steve Narofff69cc5d2008-01-30 19:17:43 +000060 unsigned RewriteFailedDiag;
Steve Naroff8c565152008-12-05 17:03:39 +000061 unsigned TryFinallyContainsReturnDiag;
Mike Stump1eb44332009-09-09 15:08:12 +000062
Chris Lattner01c57482007-10-17 22:35:30 +000063 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000064 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000065 TranslationUnitDecl *TUDecl;
Chris Lattner2b2453a2009-01-17 06:22:33 +000066 FileID MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000067 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000068 SourceLocation LastIncLoc;
Mike Stump1eb44332009-09-09 15:08:12 +000069
Ted Kremeneka526c5c2008-01-07 19:49:32 +000070 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
71 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
72 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +000073 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000074 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
75 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000076 llvm::SmallVector<Stmt *, 32> Stmts;
77 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroff621edce2009-04-29 16:37:50 +000078 // Remember all the @protocol(<expr>) expressions.
79 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +000080
81 llvm::DenseSet<uint64_t> CopyDestroyCache;
82
Steve Naroffd82a9ab2008-03-15 00:55:56 +000083 unsigned NumObjCStringLiterals;
Mike Stump1eb44332009-09-09 15:08:12 +000084
Steve Naroffebf2b562007-10-23 23:50:29 +000085 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000086 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000087 FunctionDecl *MsgSendStretFunctionDecl;
88 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000089 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000090 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000091 FunctionDecl *GetMetaClassFunctionDecl;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +000092 FunctionDecl *GetSuperClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000093 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000094 FunctionDecl *CFStringFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000095 FunctionDecl *SuperContructorFunctionDecl;
Mike Stump1eb44332009-09-09 15:08:12 +000096
Steve Naroffbeaf2992007-11-03 11:27:19 +000097 // ObjC string constant support.
Steve Naroff248a7532008-04-15 22:42:06 +000098 VarDecl *ConstantStringClassReference;
Steve Naroffbeaf2992007-11-03 11:27:19 +000099 RecordDecl *NSStringRecord;
Mike Stump1eb44332009-09-09 15:08:12 +0000100
Fariborz Jahanianb586cce2008-01-16 00:09:11 +0000101 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000102 int BcLabelCount;
Mike Stump1eb44332009-09-09 15:08:12 +0000103
Steve Naroff874e2322007-11-15 10:28:18 +0000104 // Needed for super.
Steve Naroff54055232008-10-27 17:20:55 +0000105 ObjCMethodDecl *CurMethodDef;
Steve Naroff874e2322007-11-15 10:28:18 +0000106 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000107 RecordDecl *ConstantStringDecl;
Mike Stump1eb44332009-09-09 15:08:12 +0000108
Steve Naroff621edce2009-04-29 16:37:50 +0000109 TypeDecl *ProtocolTypeDecl;
110 QualType getProtocolType();
Mike Stump1eb44332009-09-09 15:08:12 +0000111
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000112 // Needed for header files being rewritten
113 bool IsHeader;
Mike Stump1eb44332009-09-09 15:08:12 +0000114
Steve Naroffa7b402d2008-03-28 22:26:09 +0000115 std::string InFileName;
Eli Friedman66d6f042009-05-18 22:20:00 +0000116 llvm::raw_ostream* OutFile;
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000117
118 bool SilenceRewriteMacroWarning;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000119 bool objc_impl_method;
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000120
Steve Naroffba92b2e2008-03-27 22:29:16 +0000121 std::string Preamble;
Steve Naroff54055232008-10-27 17:20:55 +0000122
123 // Block expressions.
124 llvm::SmallVector<BlockExpr *, 32> Blocks;
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000125 llvm::SmallVector<int, 32> InnerDeclRefsCount;
126 llvm::SmallVector<BlockDeclRefExpr *, 32> InnerDeclRefs;
127
Steve Naroff54055232008-10-27 17:20:55 +0000128 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
Mike Stump1eb44332009-09-09 15:08:12 +0000129
Steve Naroff54055232008-10-27 17:20:55 +0000130 // Block related declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +0000131 llvm::SmallVector<ValueDecl *, 8> BlockByCopyDecls;
132 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
133 llvm::SmallVector<ValueDecl *, 8> BlockByRefDecls;
134 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000135 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff54055232008-10-27 17:20:55 +0000136 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000137 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
138
Steve Naroff54055232008-10-27 17:20:55 +0000139 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
140
Steve Naroffc77a6362008-12-04 16:24:46 +0000141 // This maps a property to it's assignment statement.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +0000142 llvm::DenseMap<Expr *, BinaryOperator *> PropSetters;
Steve Naroff8599e7a2008-12-08 16:43:47 +0000143 // This maps a property to it's synthesied message expression.
144 // This allows us to rewrite chained getters (e.g. o.a.b.c).
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +0000145 llvm::DenseMap<Expr *, Stmt *> PropGetters;
Mike Stump1eb44332009-09-09 15:08:12 +0000146
Steve Naroff4c3580e2008-12-04 23:50:32 +0000147 // This maps an original source AST to it's rewritten form. This allows
148 // us to avoid rewriting the same node twice (which is very uncommon).
149 // This is needed to support some of the exotic property rewriting.
150 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Naroff15f081d2008-12-03 00:56:33 +0000151
Steve Naroff54055232008-10-27 17:20:55 +0000152 FunctionDecl *CurFunctionDef;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000153 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000154 VarDecl *GlobalVarDecl;
Mike Stump1eb44332009-09-09 15:08:12 +0000155
Steve Naroffb619d952008-12-09 12:56:34 +0000156 bool DisableReplaceStmt;
Mike Stump1eb44332009-09-09 15:08:12 +0000157
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000158 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000159 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000160 virtual void Initialize(ASTContext &context);
161
Chris Lattnerf04da132007-10-24 17:06:59 +0000162 // Top Level Driver code.
Chris Lattner682bf922009-03-29 16:50:03 +0000163 virtual void HandleTopLevelDecl(DeclGroupRef D) {
164 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
165 HandleTopLevelSingleDecl(*I);
166 }
167 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000168 void HandleDeclInMainFile(Decl *D);
Eli Friedman66d6f042009-05-18 22:20:00 +0000169 RewriteObjC(std::string inFile, llvm::raw_ostream *OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000170 Diagnostic &D, const LangOptions &LOpts,
171 bool silenceMacroWarn);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000172
173 ~RewriteObjC() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000174
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000175 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump1eb44332009-09-09 15:08:12 +0000176
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000177 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000178 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump1eb44332009-09-09 15:08:12 +0000179
Steve Naroff4c3580e2008-12-04 23:50:32 +0000180 if (ReplacingStmt)
181 return; // We can't rewrite the same node twice.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000182
Steve Naroffb619d952008-12-09 12:56:34 +0000183 if (DisableReplaceStmt)
184 return; // Used when rewriting the assignment of a property setter.
185
Steve Naroff4c3580e2008-12-04 23:50:32 +0000186 // If replacement succeeded or warning disabled return with no warning.
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000187 if (!Rewrite.ReplaceStmt(Old, New)) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000188 ReplacedNodes[Old] = New;
189 return;
190 }
191 if (SilenceRewriteMacroWarning)
192 return;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000193 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
194 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000195 }
Steve Naroffb619d952008-12-09 12:56:34 +0000196
197 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
198 // Measaure the old text.
199 int Size = Rewrite.getRangeSize(SrcRange);
200 if (Size == -1) {
201 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
202 << Old->getSourceRange();
203 return;
204 }
205 // Get the new text.
206 std::string SStr;
207 llvm::raw_string_ostream S(SStr);
Chris Lattnere4f21422009-06-30 01:26:17 +0000208 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroffb619d952008-12-09 12:56:34 +0000209 const std::string &Str = S.str();
210
211 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000212 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroffb619d952008-12-09 12:56:34 +0000213 ReplacedNodes[Old] = New;
214 return;
215 }
216 if (SilenceRewriteMacroWarning)
217 return;
218 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
219 << Old->getSourceRange();
220 }
221
Benjamin Kramerd999b372010-02-14 14:14:16 +0000222 void InsertText(SourceLocation Loc, llvm::StringRef Str,
Steve Naroffba92b2e2008-03-27 22:29:16 +0000223 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000224 // If insertion succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000225 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000226 SilenceRewriteMacroWarning)
227 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000228
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000229 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
230 }
Mike Stump1eb44332009-09-09 15:08:12 +0000231
Chris Lattneraadaf782008-01-31 19:51:04 +0000232 void ReplaceText(SourceLocation Start, unsigned OrigLength,
Benjamin Kramerd999b372010-02-14 14:14:16 +0000233 llvm::StringRef Str) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000234 // If removal succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000235 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
Chris Lattneraadaf782008-01-31 19:51:04 +0000236 SilenceRewriteMacroWarning)
237 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000238
Chris Lattneraadaf782008-01-31 19:51:04 +0000239 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
240 }
Mike Stump1eb44332009-09-09 15:08:12 +0000241
Chris Lattnerf04da132007-10-24 17:06:59 +0000242 // Syntactic Rewriting.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000243 void RewriteInclude();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000244 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffa0876e82008-12-02 17:36:43 +0000245 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
246 ObjCImplementationDecl *IMD,
247 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000248 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000249 void RewriteImplementationDecl(Decl *Dcl);
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000250 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
251 ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000252 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
253 const FunctionType *&FPRetType);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000254 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
255 ValueDecl *VD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000256 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
257 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
258 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
259 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000260 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff09b266e2007-10-30 23:14:51 +0000261 void RewriteFunctionDecl(FunctionDecl *FD);
Daniel Dunbarfa297fb2010-06-30 19:16:53 +0000262 void RewriteBlockPointerType(std::string& Str, QualType Type);
263 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000264 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000265 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +0000266 void RewriteTypeOfDecl(VarDecl *VD);
Steve Naroff4f95b752008-07-29 18:15:38 +0000267 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000268 bool needToScanForQualifiers(QualType T);
Steve Naroff874e2322007-11-15 10:28:18 +0000269 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000270 QualType getConstantStringStructType();
Fariborz Jahanian1f906222010-05-25 15:56:08 +0000271 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
Steve Naroffbaf58c32008-05-31 14:15:04 +0000272 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump1eb44332009-09-09 15:08:12 +0000273
Chris Lattnerf04da132007-10-24 17:06:59 +0000274 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000275 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroffc77a6362008-12-04 16:24:46 +0000276 void CollectPropertySetters(Stmt *S);
Mike Stump1eb44332009-09-09 15:08:12 +0000277
Steve Naroff8599e7a2008-12-08 16:43:47 +0000278 Stmt *CurrentBody;
279 ParentMap *PropParentMap; // created lazily.
Mike Stump1eb44332009-09-09 15:08:12 +0000280
Chris Lattnere64b7772007-10-24 16:57:36 +0000281 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +0000282 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart,
283 bool &replaced);
284 Stmt *RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +0000285 Stmt *RewritePropertyOrImplicitGetter(Expr *PropOrGetterRefExpr);
286 Stmt *RewritePropertyOrImplicitSetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroffb619d952008-12-09 12:56:34 +0000287 SourceRange SrcRange);
Steve Naroffb42f8412007-11-05 14:50:49 +0000288 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000289 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000290 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000291 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffb85e77a2009-12-05 21:43:12 +0000292 void WarnAboutReturnGotoStmts(Stmt *S);
293 void HasReturnStmts(Stmt *S, bool &hasReturns);
294 void RewriteTryReturnStmts(Stmt *S);
295 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000296 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000297 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000298 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000299 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
300 SourceLocation OrigEnd);
Mike Stump1eb44332009-09-09 15:08:12 +0000301 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +0000302 Expr **args, unsigned nargs,
303 SourceLocation StartLoc=SourceLocation(),
304 SourceLocation EndLoc=SourceLocation());
305 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
306 SourceLocation StartLoc=SourceLocation(),
307 SourceLocation EndLoc=SourceLocation());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000308 Stmt *RewriteBreakStmt(BreakStmt *S);
309 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000310 void SynthCountByEnumWithState(std::string &buf);
Mike Stump1eb44332009-09-09 15:08:12 +0000311
Steve Naroff09b266e2007-10-30 23:14:51 +0000312 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000313 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000314 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000315 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000316 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000317 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000318 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000319 void SynthGetSuperClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000320 void SynthSelGetUidFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000321 void SynthSuperContructorFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000322
Chris Lattnerf04da132007-10-24 17:06:59 +0000323 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000324 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000325 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000326
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000327 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000328 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000329
Douglas Gregor653f1b12009-04-23 01:02:12 +0000330 template<typename MethodIterator>
331 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
332 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000333 bool IsInstanceMethod,
Daniel Dunbar4087f272010-08-17 22:39:59 +0000334 llvm::StringRef prefix,
335 llvm::StringRef ClassName,
Chris Lattner158ecb92007-10-25 17:07:24 +0000336 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000337
Steve Naroff621edce2009-04-29 16:37:50 +0000338 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
Daniel Dunbar4087f272010-08-17 22:39:59 +0000339 llvm::StringRef prefix,
340 llvm::StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +0000341 std::string &Result);
342 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Daniel Dunbar4087f272010-08-17 22:39:59 +0000343 llvm::StringRef prefix,
344 llvm::StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +0000345 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000346 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000347 std::string &Result);
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000348 void SynthesizeIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000349 std::string &Result);
Steve Narofface66252008-11-13 20:07:04 +0000350 void RewriteImplementations();
351 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000352
Steve Naroff54055232008-10-27 17:20:55 +0000353 // Block rewriting.
Mike Stump1eb44332009-09-09 15:08:12 +0000354 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff54055232008-10-27 17:20:55 +0000355 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump1eb44332009-09-09 15:08:12 +0000356
Steve Naroff54055232008-10-27 17:20:55 +0000357 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
358 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump1eb44332009-09-09 15:08:12 +0000359
360 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000361 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000362 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +0000363 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +0000364 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000365 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
Steve Naroff54055232008-10-27 17:20:55 +0000366 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000367
368 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Daniel Dunbar4087f272010-08-17 22:39:59 +0000369 llvm::StringRef funcName, std::string Tag);
Mike Stump1eb44332009-09-09 15:08:12 +0000370 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Daniel Dunbar4087f272010-08-17 22:39:59 +0000371 llvm::StringRef funcName, std::string Tag);
Steve Naroff01aec112009-12-06 21:14:13 +0000372 std::string SynthesizeBlockImpl(BlockExpr *CE,
373 std::string Tag, std::string Desc);
374 std::string SynthesizeBlockDescriptor(std::string DescTag,
375 std::string ImplTag,
Daniel Dunbar4087f272010-08-17 22:39:59 +0000376 int i, llvm::StringRef funcName,
Steve Naroff01aec112009-12-06 21:14:13 +0000377 unsigned hasCopy);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +0000378 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff54055232008-10-27 17:20:55 +0000379 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Daniel Dunbar4087f272010-08-17 22:39:59 +0000380 llvm::StringRef FunName);
Steve Naroff3d7e7862009-12-05 15:55:59 +0000381 void RewriteRecordBody(RecordDecl *RD);
Mike Stump1eb44332009-09-09 15:08:12 +0000382
Steve Naroff54055232008-10-27 17:20:55 +0000383 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000384 void GetBlockDeclRefExprs(Stmt *S);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000385 void GetInnerBlockDeclRefExprs(Stmt *S,
386 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +0000387 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
Mike Stump1eb44332009-09-09 15:08:12 +0000388
Steve Naroff54055232008-10-27 17:20:55 +0000389 // We avoid calling Type::isBlockPointerType(), since it operates on the
390 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000391 bool isTopLevelBlockPointerType(QualType T) {
392 return isa<BlockPointerType>(T);
393 }
Mike Stump1eb44332009-09-09 15:08:12 +0000394
Fariborz Jahanian4fc84532010-05-25 17:12:52 +0000395 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
396 /// to a function pointer type and upon success, returns true; false
397 /// otherwise.
398 bool convertBlockPointerToFunctionPointer(QualType &T) {
399 if (isTopLevelBlockPointerType(T)) {
400 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
401 T = Context->getPointerType(BPT->getPointeeType());
402 return true;
403 }
404 return false;
405 }
406
Steve Naroff54055232008-10-27 17:20:55 +0000407 // FIXME: This predicate seems like it would be useful to add to ASTContext.
408 bool isObjCType(QualType T) {
409 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
410 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000411
Steve Naroff54055232008-10-27 17:20:55 +0000412 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000413
Steve Naroff54055232008-10-27 17:20:55 +0000414 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
415 OCT == Context->getCanonicalType(Context->getObjCClassType()))
416 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000417
Ted Kremenek6217b802009-07-29 21:53:49 +0000418 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000419 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000420 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff54055232008-10-27 17:20:55 +0000421 return true;
422 }
423 return false;
424 }
425 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000426 void GetExtentOfArgList(const char *Name, const char *&LParen,
427 const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000428 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump1eb44332009-09-09 15:08:12 +0000429
Daniel Dunbar4087f272010-08-17 22:39:59 +0000430 FunctionDecl *SynthBlockInitFunctionDecl(llvm::StringRef name);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000431 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
432 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs);
Mike Stump1eb44332009-09-09 15:08:12 +0000433
Steve Naroff621edce2009-04-29 16:37:50 +0000434 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump1eb44332009-09-09 15:08:12 +0000435 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroff621edce2009-04-29 16:37:50 +0000436 if (From[i] == '"')
437 To += "\\\"";
438 else
439 To += From[i];
440 }
441 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000442 };
John McCall9d125032010-01-15 18:39:57 +0000443
444 // Helper function: create a CStyleCastExpr with trivial type source info.
445 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +0000446 CastKind Kind, Expr *E) {
John McCall9d125032010-01-15 18:39:57 +0000447 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
John McCallf871d0c2010-08-07 06:22:56 +0000448 return CStyleCastExpr::Create(*Ctx, Ty, Kind, E, 0, TInfo,
449 SourceLocation(), SourceLocation());
John McCall9d125032010-01-15 18:39:57 +0000450 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000451}
452
Mike Stump1eb44332009-09-09 15:08:12 +0000453void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
454 NamedDecl *D) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000455 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000456 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000457 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000458 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000459 // All the args are checked/rewritten. Don't call twice!
460 RewriteBlockPointerDecl(D);
461 break;
462 }
463 }
464}
465
466void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000467 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +0000468 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000469 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000470}
471
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000472static bool IsHeaderFile(const std::string &Filename) {
473 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump1eb44332009-09-09 15:08:12 +0000474
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000475 if (DotPos == std::string::npos) {
476 // no file extension
Mike Stump1eb44332009-09-09 15:08:12 +0000477 return false;
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000478 }
Mike Stump1eb44332009-09-09 15:08:12 +0000479
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000480 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
481 // C header: .h
482 // C++ header: .hh or .H;
483 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump1eb44332009-09-09 15:08:12 +0000484}
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000485
Eli Friedman66d6f042009-05-18 22:20:00 +0000486RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000487 Diagnostic &D, const LangOptions &LOpts,
488 bool silenceMacroWarn)
489 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
490 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000491 IsHeader = IsHeaderFile(inFile);
Mike Stump1eb44332009-09-09 15:08:12 +0000492 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000493 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump1eb44332009-09-09 15:08:12 +0000494 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000495 "rewriter doesn't support user-specified control flow semantics "
496 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000497}
498
Eli Friedmanbce831b2009-05-18 22:29:17 +0000499ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
500 llvm::raw_ostream* OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000501 Diagnostic &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000502 const LangOptions &LOpts,
503 bool SilenceRewriteMacroWarning) {
504 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere365c502007-11-30 22:25:36 +0000505}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000506
Steve Naroffb29b4272008-04-14 22:03:09 +0000507void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000508 Context = &context;
509 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000510 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000511 MsgSendFunctionDecl = 0;
512 MsgSendSuperFunctionDecl = 0;
513 MsgSendStretFunctionDecl = 0;
514 MsgSendSuperStretFunctionDecl = 0;
515 MsgSendFpretFunctionDecl = 0;
516 GetClassFunctionDecl = 0;
517 GetMetaClassFunctionDecl = 0;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000518 GetSuperClassFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000519 SelGetUidFunctionDecl = 0;
520 CFStringFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000521 ConstantStringClassReference = 0;
522 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000523 CurMethodDef = 0;
524 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000525 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000526 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000527 SuperStructDecl = 0;
Steve Naroff621edce2009-04-29 16:37:50 +0000528 ProtocolTypeDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000529 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000530 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000531 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000532 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000533 PropParentMap = 0;
534 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000535 DisableReplaceStmt = false;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000536 objc_impl_method = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000537
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000538 // Get the ID and start/end of the main file.
539 MainFileID = SM->getMainFileID();
540 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
541 MainFileStart = MainBuf->getBufferStart();
542 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000543
Chris Lattner2c78b872009-04-14 23:22:57 +0000544 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump1eb44332009-09-09 15:08:12 +0000545
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000546 // declaring objc_selector outside the parameter list removes a silly
547 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000548 if (IsHeader)
Steve Naroff62c26322009-02-03 20:39:18 +0000549 Preamble = "#pragma once\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000550 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff46a98a72008-12-23 20:11:22 +0000551 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000552 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000553 if (LangOpts.Microsoft) {
554 // Add a constructor for creating temporary objects.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000555 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
556 ": ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000557 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000558 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000559 Preamble += "};\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000560 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
561 Preamble += "typedef struct objc_object Protocol;\n";
562 Preamble += "#define _REWRITER_typedef_Protocol\n";
563 Preamble += "#endif\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000564 if (LangOpts.Microsoft) {
565 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
566 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
567 } else
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000568 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000569 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000570 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000571 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000572 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000573 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000574 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000575 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000576 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000577 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000578 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000579 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000580 Preamble += "(const char *);\n";
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000581 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
582 Preamble += "(struct objc_class *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000583 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000584 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000585 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
586 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
587 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
588 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
589 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000590 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000591 // @synchronized hooks.
Steve Naroff4ebd7162008-12-08 17:30:33 +0000592 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
593 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
594 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000595 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
596 Preamble += "struct __objcFastEnumerationState {\n\t";
597 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000598 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000599 Preamble += "unsigned long *mutationsPtr;\n\t";
600 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000601 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000602 Preamble += "#define __FASTENUMERATIONSTATE\n";
603 Preamble += "#endif\n";
604 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
605 Preamble += "struct __NSConstantStringImpl {\n";
606 Preamble += " int *isa;\n";
607 Preamble += " int flags;\n";
608 Preamble += " char *str;\n";
609 Preamble += " long length;\n";
610 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000611 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
612 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
613 Preamble += "#else\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000614 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000615 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000616 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
617 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000618 // Blocks preamble.
619 Preamble += "#ifndef BLOCK_IMPL\n";
620 Preamble += "#define BLOCK_IMPL\n";
621 Preamble += "struct __block_impl {\n";
622 Preamble += " void *isa;\n";
623 Preamble += " int Flags;\n";
Steve Naroff01aec112009-12-06 21:14:13 +0000624 Preamble += " int Reserved;\n";
Steve Naroff54055232008-10-27 17:20:55 +0000625 Preamble += " void *FuncPtr;\n";
626 Preamble += "};\n";
Steve Naroff5bc60d02008-12-16 15:50:30 +0000627 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroffc9c1e9c2009-12-06 01:52:22 +0000628 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000629 Preamble += "extern \"C\" __declspec(dllexport) "
630 "void _Block_object_assign(void *, const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000631 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
632 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
633 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
634 Preamble += "#else\n";
Steve Naroffcd826372010-01-05 18:09:31 +0000635 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
636 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000637 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
638 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
639 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000640 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000641 if (LangOpts.Microsoft) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000642 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
643 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Chris Lattner553e5832010-04-13 17:33:56 +0000644 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
Steve Naroffa48396e2008-10-27 18:50:14 +0000645 Preamble += "#define __attribute__(X)\n";
Chris Lattner553e5832010-04-13 17:33:56 +0000646 Preamble += "#endif\n";
Fariborz Jahanian34204192010-01-15 22:29:39 +0000647 Preamble += "#define __weak\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000648 }
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000649 else {
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000650 Preamble += "#define __block\n";
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000651 Preamble += "#define __weak\n";
652 }
Fariborz Jahaniandf496522010-03-02 01:19:04 +0000653 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
654 // as this avoids warning in any 64bit/32bit compilation model.
655 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000656}
657
658
Chris Lattnerf04da132007-10-24 17:06:59 +0000659//===----------------------------------------------------------------------===//
660// Top Level Driver Code
661//===----------------------------------------------------------------------===//
662
Chris Lattner682bf922009-03-29 16:50:03 +0000663void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremeneke50187a2010-02-05 21:28:51 +0000664 if (Diags.hasErrorOccurred())
665 return;
666
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000667 // Two cases: either the decl could be in the main file, or it could be in a
668 // #included file. If the former, rewrite it now. If the later, check to see
669 // if we rewrote the #include/#import.
670 SourceLocation Loc = D->getLocation();
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000671 Loc = SM->getInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000672
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000673 // If this is for a builtin, ignore it.
674 if (Loc.isInvalid()) return;
675
Steve Naroffebf2b562007-10-23 23:50:29 +0000676 // Look for built-in declarations that we need to refer during the rewrite.
677 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000678 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000679 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000680 // declared in <Foundation/NSString.h>
Daniel Dunbar4087f272010-08-17 22:39:59 +0000681 if (FVD->getName() == "_NSConstantStringClassReference") {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000682 ConstantStringClassReference = FVD;
683 return;
684 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000685 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000686 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000687 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000688 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000689 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000690 RewriteProtocolDecl(PD);
Mike Stump1eb44332009-09-09 15:08:12 +0000691 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000692 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000693 RewriteForwardProtocolDecl(FP);
Douglas Gregord0434102009-01-09 00:49:46 +0000694 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
695 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000696 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
697 DIEnd = LSD->decls_end();
Douglas Gregord0434102009-01-09 00:49:46 +0000698 DI != DIEnd; ++DI)
Chris Lattner682bf922009-03-29 16:50:03 +0000699 HandleTopLevelSingleDecl(*DI);
Steve Naroffebf2b562007-10-23 23:50:29 +0000700 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000701 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000702 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000703 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000704}
705
Chris Lattnerf04da132007-10-24 17:06:59 +0000706//===----------------------------------------------------------------------===//
707// Syntactic (non-AST) Rewriting Code
708//===----------------------------------------------------------------------===//
709
Steve Naroffb29b4272008-04-14 22:03:09 +0000710void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000711 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000712 llvm::StringRef MainBuf = SM->getBufferData(MainFileID);
713 const char *MainBufStart = MainBuf.begin();
714 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000715 size_t ImportLen = strlen("import");
Mike Stump1eb44332009-09-09 15:08:12 +0000716
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000717 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000718 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
719 if (*BufPtr == '#') {
720 if (++BufPtr == MainBufEnd)
721 return;
722 while (*BufPtr == ' ' || *BufPtr == '\t')
723 if (++BufPtr == MainBufEnd)
724 return;
725 if (!strncmp(BufPtr, "import", ImportLen)) {
726 // replace import with include
Mike Stump1eb44332009-09-09 15:08:12 +0000727 SourceLocation ImportLoc =
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000728 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000729 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000730 BufPtr += ImportLen;
731 }
732 }
733 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000734}
735
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000736static std::string getIvarAccessString(ObjCIvarDecl *OID) {
737 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000738 std::string S;
739 S = "((struct ";
740 S += ClassDecl->getIdentifier()->getName();
741 S += "_IMPL *)self)->";
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +0000742 S += OID->getName();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000743 return S;
744}
745
Steve Naroffa0876e82008-12-02 17:36:43 +0000746void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
747 ObjCImplementationDecl *IMD,
748 ObjCCategoryImplDecl *CID) {
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000749 static bool objcGetPropertyDefined = false;
750 static bool objcSetPropertyDefined = false;
Steve Naroffd40910b2008-12-01 20:33:01 +0000751 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramerd999b372010-02-14 14:14:16 +0000752 InsertText(startLoc, "// ");
Steve Naroffeb0646c2008-12-02 15:48:25 +0000753 const char *startBuf = SM->getCharacterData(startLoc);
754 assert((*startBuf == '@') && "bogus @synthesize location");
755 const char *semiBuf = strchr(startBuf, ';');
756 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000757 SourceLocation onePastSemiLoc =
758 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000759
760 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
761 return; // FIXME: is this correct?
Mike Stump1eb44332009-09-09 15:08:12 +0000762
Steve Naroffeb0646c2008-12-02 15:48:25 +0000763 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000764 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000765 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000766
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000767 if (!OID)
768 return;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000769 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000770 if (!PD->getGetterMethodDecl()->isDefined()) {
771 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
772 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
773 ObjCPropertyDecl::OBJC_PR_copy));
774 std::string Getr;
775 if (GenGetProperty && !objcGetPropertyDefined) {
776 objcGetPropertyDefined = true;
777 // FIXME. Is this attribute correct in all cases?
778 Getr = "\nextern \"C\" __declspec(dllimport) "
779 "id objc_getProperty(id, SEL, long, bool);\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000780 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000781 RewriteObjCMethodDecl(OID->getContainingInterface(),
782 PD->getGetterMethodDecl(), Getr);
783 Getr += "{ ";
784 // Synthesize an explicit cast to gain access to the ivar.
785 // See objc-act.c:objc_synthesize_new_getter() for details.
786 if (GenGetProperty) {
787 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
788 Getr += "typedef ";
789 const FunctionType *FPRetType = 0;
790 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
791 FPRetType);
792 Getr += " _TYPE";
793 if (FPRetType) {
794 Getr += ")"; // close the precedence "scope" for "*".
795
796 // Now, emit the argument types (if any).
797 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
798 Getr += "(";
799 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
800 if (i) Getr += ", ";
801 std::string ParamStr = FT->getArgType(i).getAsString(
802 Context->PrintingPolicy);
803 Getr += ParamStr;
804 }
805 if (FT->isVariadic()) {
806 if (FT->getNumArgs()) Getr += ", ";
807 Getr += "...";
808 }
809 Getr += ")";
810 } else
811 Getr += "()";
812 }
813 Getr += ";\n";
814 Getr += "return (_TYPE)";
815 Getr += "objc_getProperty(self, _cmd, ";
816 SynthesizeIvarOffsetComputation(OID, Getr);
817 Getr += ", 1)";
818 }
819 else
820 Getr += "return " + getIvarAccessString(OID);
821 Getr += "; }";
822 InsertText(onePastSemiLoc, Getr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000823 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000824
825 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
Steve Naroffeb0646c2008-12-02 15:48:25 +0000826 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000827
Steve Naroffeb0646c2008-12-02 15:48:25 +0000828 // Generate the 'setter' function.
829 std::string Setr;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000830 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
831 ObjCPropertyDecl::OBJC_PR_copy);
832 if (GenSetProperty && !objcSetPropertyDefined) {
833 objcSetPropertyDefined = true;
834 // FIXME. Is this attribute correct in all cases?
835 Setr = "\nextern \"C\" __declspec(dllimport) "
836 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
837 }
838
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000839 RewriteObjCMethodDecl(OID->getContainingInterface(),
840 PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000841 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000842 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff15f081d2008-12-03 00:56:33 +0000843 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000844 if (GenSetProperty) {
845 Setr += "objc_setProperty (self, _cmd, ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000846 SynthesizeIvarOffsetComputation(OID, Setr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000847 Setr += ", (id)";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000848 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000849 Setr += ", ";
850 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
851 Setr += "0, ";
852 else
853 Setr += "1, ";
854 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
855 Setr += "1)";
856 else
857 Setr += "0)";
858 }
859 else {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000860 Setr += getIvarAccessString(OID) + " = ";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000861 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000862 }
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000863 Setr += "; }";
Benjamin Kramerd999b372010-02-14 14:14:16 +0000864 InsertText(onePastSemiLoc, Setr);
Steve Naroffd40910b2008-12-01 20:33:01 +0000865}
Chris Lattner8a12c272007-10-11 18:38:32 +0000866
Steve Naroffb29b4272008-04-14 22:03:09 +0000867void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000868 // Get the start location and compute the semi location.
869 SourceLocation startLoc = ClassDecl->getLocation();
870 const char *startBuf = SM->getCharacterData(startLoc);
871 const char *semiPtr = strchr(startBuf, ';');
Mike Stump1eb44332009-09-09 15:08:12 +0000872
Chris Lattnerf04da132007-10-24 17:06:59 +0000873 // Translate to typedef's that forward reference structs with the same name
874 // as the class. As a convenience, we include the original declaration
875 // as a comment.
876 std::string typedefString;
Fariborz Jahanian91fbd122010-01-11 22:48:40 +0000877 typedefString += "// @class ";
878 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
879 I != E; ++I) {
880 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
881 typedefString += ForwardDecl->getNameAsString();
882 if (I+1 != E)
883 typedefString += ", ";
884 else
885 typedefString += ";\n";
886 }
887
Chris Lattner67956052009-02-20 18:04:31 +0000888 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
889 I != E; ++I) {
Ted Kremenek321c22f2009-11-18 00:28:11 +0000890 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff32174822007-11-09 12:50:28 +0000891 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000892 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000893 typedefString += "\n";
894 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000895 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000896 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000897 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000898 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000899 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000900 }
Mike Stump1eb44332009-09-09 15:08:12 +0000901
Steve Naroff934f2762007-10-24 22:48:43 +0000902 // Replace the @class with typedefs corresponding to the classes.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000903 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
Chris Lattnerf04da132007-10-24 17:06:59 +0000904}
905
Steve Naroffb29b4272008-04-14 22:03:09 +0000906void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000907 // When method is a synthesized one, such as a getter/setter there is
908 // nothing to rewrite.
909 if (Method->isSynthesized())
910 return;
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000911 SourceLocation LocStart = Method->getLocStart();
912 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000913
Chris Lattner30fc9332009-02-04 01:06:56 +0000914 if (SM->getInstantiationLineNumber(LocEnd) >
915 SM->getInstantiationLineNumber(LocStart)) {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000916 InsertText(LocStart, "#if 0\n");
917 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000918 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000919 InsertText(LocStart, "// ");
Steve Naroff423cb562007-10-30 13:30:57 +0000920 }
921}
922
Mike Stump1eb44332009-09-09 15:08:12 +0000923void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000924 SourceLocation Loc = prop->getAtLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000925
Benjamin Kramerd999b372010-02-14 14:14:16 +0000926 ReplaceText(Loc, 0, "// ");
Steve Naroff6327e0d2009-01-11 01:06:09 +0000927 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000928}
929
Steve Naroffb29b4272008-04-14 22:03:09 +0000930void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000931 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000932
Steve Naroff423cb562007-10-30 13:30:57 +0000933 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000934 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000935
Fariborz Jahanian13751e32010-02-10 01:15:09 +0000936 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
937 E = CatDecl->prop_end(); I != E; ++I)
938 RewriteProperty(*I);
939
Mike Stump1eb44332009-09-09 15:08:12 +0000940 for (ObjCCategoryDecl::instmeth_iterator
941 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000942 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000943 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +0000944 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000945 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000946 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000947 RewriteMethodDeclaration(*I);
948
Steve Naroff423cb562007-10-30 13:30:57 +0000949 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +0000950 ReplaceText(CatDecl->getAtEndRange().getBegin(),
951 strlen("@end"), "/* @end */");
Steve Naroff423cb562007-10-30 13:30:57 +0000952}
953
Steve Naroffb29b4272008-04-14 22:03:09 +0000954void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000955 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000956
Steve Naroff752d6ef2007-10-30 16:42:30 +0000957 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000958 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000959
960 for (ObjCProtocolDecl::instmeth_iterator
961 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000962 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000963 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000964 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000965 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000966 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000967 RewriteMethodDeclaration(*I);
968
Fariborz Jahanian07acdf42010-09-24 18:36:58 +0000969 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
970 E = PDecl->prop_end(); I != E; ++I)
971 RewriteProperty(*I);
972
Steve Naroff752d6ef2007-10-30 16:42:30 +0000973 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +0000974 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +0000975 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroff8cc764c2007-11-14 15:03:57 +0000976
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000977 // Must comment out @optional/@required
978 const char *startBuf = SM->getCharacterData(LocStart);
979 const char *endBuf = SM->getCharacterData(LocEnd);
980 for (const char *p = startBuf; p < endBuf; p++) {
981 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Steve Naroff8cc764c2007-11-14 15:03:57 +0000982 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000983 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump1eb44332009-09-09 15:08:12 +0000984
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000985 }
986 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Steve Naroff8cc764c2007-11-14 15:03:57 +0000987 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000988 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump1eb44332009-09-09 15:08:12 +0000989
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000990 }
991 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000992}
993
Steve Naroffb29b4272008-04-14 22:03:09 +0000994void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000995 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000996 if (LocStart.isInvalid())
997 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000998 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000999 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001000}
1001
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001002void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1003 const FunctionType *&FPRetType) {
1004 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001005 ResultStr += "id";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001006 else if (T->isFunctionPointerType() ||
1007 T->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001008 // needs special handling, since pointer-to-functions have special
1009 // syntax (where a decaration models use).
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001010 QualType retType = T;
Steve Narofff4312dc2008-12-11 19:29:16 +00001011 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001012 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001013 PointeeTy = PT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001014 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001015 PointeeTy = BPT->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001016 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001017 ResultStr += FPRetType->getResultType().getAsString(
1018 Context->PrintingPolicy);
Steve Narofff4312dc2008-12-11 19:29:16 +00001019 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +00001020 }
1021 } else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001022 ResultStr += T.getAsString(Context->PrintingPolicy);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001023}
1024
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001025void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1026 ObjCMethodDecl *OMD,
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001027 std::string &ResultStr) {
1028 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1029 const FunctionType *FPRetType = 0;
1030 ResultStr += "\nstatic ";
1031 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001032 ResultStr += " ";
Mike Stump1eb44332009-09-09 15:08:12 +00001033
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001034 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001035 std::string NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001036
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001037 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001038 NameStr += "_I_";
1039 else
1040 NameStr += "_C_";
Mike Stump1eb44332009-09-09 15:08:12 +00001041
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001042 NameStr += IDecl->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001043 NameStr += "_";
Mike Stump1eb44332009-09-09 15:08:12 +00001044
1045 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +00001046 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001047 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001048 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001049 }
Mike Stump1eb44332009-09-09 15:08:12 +00001050 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +00001051 {
1052 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001053 int len = selString.size();
1054 for (int i = 0; i < len; i++)
1055 if (selString[i] == ':')
1056 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001057 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001058 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001059 // Remember this name for metadata emission
1060 MethodInternalNames[OMD] = NameStr;
1061 ResultStr += NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001062
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001063 // Rewrite arguments
1064 ResultStr += "(";
Mike Stump1eb44332009-09-09 15:08:12 +00001065
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001066 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001067 if (OMD->isInstanceMethod()) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001068 QualType selfTy = Context->getObjCInterfaceType(IDecl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001069 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +00001070 if (!LangOpts.Microsoft) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001071 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
Steve Naroff05b8c782008-03-12 00:25:36 +00001072 ResultStr += "struct ";
1073 }
1074 // When rewriting for Microsoft, explicitly omit the structure name.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001075 ResultStr += IDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001076 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001077 }
1078 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001079 ResultStr += Context->getObjCClassType().getAsString(
1080 Context->PrintingPolicy);
Mike Stump1eb44332009-09-09 15:08:12 +00001081
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001082 ResultStr += " self, ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001083 ResultStr += Context->getObjCSelType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001084 ResultStr += " _cmd";
Mike Stump1eb44332009-09-09 15:08:12 +00001085
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001086 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +00001087 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1088 E = OMD->param_end(); PI != E; ++PI) {
1089 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001090 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +00001091 if (PDecl->getType()->isObjCQualifiedIdType()) {
1092 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001093 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +00001094 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001095 std::string Name = PDecl->getNameAsString();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00001096 QualType QT = PDecl->getType();
1097 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1098 if (convertBlockPointerToFunctionPointer(QT))
1099 QT.getAsStringInternal(Name, Context->PrintingPolicy);
1100 else
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001101 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroff543409e2008-04-18 21:13:19 +00001102 ResultStr += Name;
1103 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001104 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +00001105 if (OMD->isVariadic())
1106 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001107 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +00001108
Steve Naroff76e429d2008-07-16 14:40:40 +00001109 if (FPRetType) {
1110 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +00001111
Steve Naroff76e429d2008-07-16 14:40:40 +00001112 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +00001113 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001114 ResultStr += "(";
1115 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1116 if (i) ResultStr += ", ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001117 std::string ParamStr = FT->getArgType(i).getAsString(
1118 Context->PrintingPolicy);
Steve Naroff76e429d2008-07-16 14:40:40 +00001119 ResultStr += ParamStr;
1120 }
1121 if (FT->isVariadic()) {
1122 if (FT->getNumArgs()) ResultStr += ", ";
1123 ResultStr += "...";
1124 }
1125 ResultStr += ")";
1126 } else {
1127 ResultStr += "()";
1128 }
1129 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001130}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001131void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001132 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1133 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001134
Fariborz Jahaniana1352162010-02-15 21:11:41 +00001135 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001136
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001137 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001138 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1139 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001140 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001141 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001142 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001143 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001144 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001145 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001146
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001147 const char *startBuf = SM->getCharacterData(LocStart);
1148 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001149 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001150 }
Mike Stump1eb44332009-09-09 15:08:12 +00001151
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001152 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001153 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1154 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001155 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001156 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001157 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001158 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001159 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001160 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001161
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001162 const char *startBuf = SM->getCharacterData(LocStart);
1163 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001164 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001165 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001166 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001167 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001168 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001169 I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001170 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001171 }
1172
Benjamin Kramerd999b372010-02-14 14:14:16 +00001173 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001174}
1175
Steve Naroffb29b4272008-04-14 22:03:09 +00001176void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001177 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001178 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001179 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001180 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001181 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001182 ResultStr += "\n";
1183 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001184 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001185 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001186 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001187 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001188 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001189 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001190 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001191 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001192 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001193
1194 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001195 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff6327e0d2009-01-11 01:06:09 +00001196 RewriteProperty(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001197 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001198 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001199 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001200 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001201 for (ObjCInterfaceDecl::classmeth_iterator
1202 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001203 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001204 RewriteMethodDeclaration(*I);
1205
Steve Naroff2feac5e2007-10-30 03:43:13 +00001206 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001207 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1208 "/* @end */");
Steve Naroffbef11852007-10-26 20:53:56 +00001209}
1210
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001211Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroffb619d952008-12-09 12:56:34 +00001212 SourceRange SrcRange) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001213 ObjCMethodDecl *OMD = 0;
1214 QualType Ty;
1215 Selector Sel;
Duncan Sands54bd4572010-10-20 08:21:16 +00001216 Stmt *Receiver = 0;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001217 bool Super = false;
1218 QualType SuperTy;
1219 SourceLocation SuperLocation;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001220 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ObjCImplicitSetterGetterRefExpr.
Steve Naroffc77a6362008-12-04 16:24:46 +00001221 // This allows us to reuse all the fun and games in SynthMessageExpr().
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001222 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS())) {
1223 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1224 OMD = PDecl->getSetterMethodDecl();
1225 Ty = PDecl->getType();
1226 Sel = PDecl->getSetterName();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001227 Super = PropRefExpr->isSuperReceiver();
1228 if (!Super)
1229 Receiver = PropRefExpr->getBase();
1230 else {
1231 SuperTy = PropRefExpr->getSuperType();
1232 SuperLocation = PropRefExpr->getSuperLocation();
1233 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001234 }
1235 else if (ObjCImplicitSetterGetterRefExpr *ImplicitRefExpr =
1236 dyn_cast<ObjCImplicitSetterGetterRefExpr>(BinOp->getLHS())) {
1237 OMD = ImplicitRefExpr->getSetterMethod();
1238 Sel = OMD->getSelector();
1239 Ty = ImplicitRefExpr->getType();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001240 Super = ImplicitRefExpr->isSuperReceiver();
1241 if (!Super)
1242 Receiver = ImplicitRefExpr->getBase();
1243 else {
1244 SuperTy = ImplicitRefExpr->getSuperType();
1245 SuperLocation = ImplicitRefExpr->getSuperLocation();
1246 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001247 }
1248
1249 assert(OMD && "RewritePropertyOrImplicitSetter - null OMD");
Steve Naroffc77a6362008-12-04 16:24:46 +00001250 llvm::SmallVector<Expr *, 1> ExprVec;
1251 ExprVec.push_back(newStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001252
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001253 ObjCMessageExpr *MsgExpr;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001254 if (Super)
Douglas Gregor04badcf2010-04-21 00:45:42 +00001255 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001256 Ty.getNonReferenceType(),
Douglas Gregor04badcf2010-04-21 00:45:42 +00001257 /*FIXME?*/SourceLocation(),
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001258 SuperLocation,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001259 /*IsInstanceSuper=*/true,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001260 SuperTy,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001261 Sel, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001262 &ExprVec[0], 1,
1263 /*FIXME:*/SourceLocation());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001264 else {
1265 // FIXME. Refactor this into common code with that in
1266 // RewritePropertyOrImplicitGetter
1267 assert(Receiver && "RewritePropertyOrImplicitSetter - null Receiver");
1268 if (Expr *Exp = dyn_cast<Expr>(Receiver))
1269 if (PropGetters[Exp])
1270 // This allows us to handle chain/nested property/implicit getters.
1271 Receiver = PropGetters[Exp];
1272
Douglas Gregor04badcf2010-04-21 00:45:42 +00001273 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001274 Ty.getNonReferenceType(),
Douglas Gregor04badcf2010-04-21 00:45:42 +00001275 /*FIXME: */SourceLocation(),
1276 cast<Expr>(Receiver),
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001277 Sel, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001278 &ExprVec[0], 1,
1279 /*FIXME:*/SourceLocation());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001280 }
Steve Naroffc77a6362008-12-04 16:24:46 +00001281 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001282
Steve Naroffc77a6362008-12-04 16:24:46 +00001283 // Now do the actual rewrite.
Steve Naroffb619d952008-12-09 12:56:34 +00001284 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffe58ee0c2008-12-10 14:53:27 +00001285 //delete BinOp;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001286 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1287 // to things that stay around.
1288 Context->Deallocate(MsgExpr);
Steve Naroffc77a6362008-12-04 16:24:46 +00001289 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001290}
1291
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001292Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(Expr *PropOrGetterRefExpr) {
1293 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ImplicitGetter.
Steve Naroff15f081d2008-12-03 00:56:33 +00001294 // This allows us to reuse all the fun and games in SynthMessageExpr().
Ted Kremenek3b562af2010-10-19 23:10:22 +00001295 Stmt *Receiver = 0;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001296 ObjCMethodDecl *OMD = 0;
1297 QualType Ty;
1298 Selector Sel;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001299 bool Super = false;
1300 QualType SuperTy;
1301 SourceLocation SuperLocation;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001302 if (ObjCPropertyRefExpr *PropRefExpr =
1303 dyn_cast<ObjCPropertyRefExpr>(PropOrGetterRefExpr)) {
1304 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1305 OMD = PDecl->getGetterMethodDecl();
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001306 Ty = PDecl->getType();
1307 Sel = PDecl->getGetterName();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001308 Super = PropRefExpr->isSuperReceiver();
1309 if (!Super)
1310 Receiver = PropRefExpr->getBase();
1311 else {
1312 SuperTy = PropRefExpr->getSuperType();
1313 SuperLocation = PropRefExpr->getSuperLocation();
1314 }
Steve Naroff8599e7a2008-12-08 16:43:47 +00001315 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001316 else if (ObjCImplicitSetterGetterRefExpr *ImplicitRefExpr =
1317 dyn_cast<ObjCImplicitSetterGetterRefExpr>(PropOrGetterRefExpr)) {
1318 OMD = ImplicitRefExpr->getGetterMethod();
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001319 Sel = OMD->getSelector();
1320 Ty = ImplicitRefExpr->getType();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001321 Super = ImplicitRefExpr->isSuperReceiver();
1322 if (!Super)
1323 Receiver = ImplicitRefExpr->getBase();
1324 else {
1325 SuperTy = ImplicitRefExpr->getSuperType();
1326 SuperLocation = ImplicitRefExpr->getSuperLocation();
1327 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001328 }
1329
1330 assert (OMD && "RewritePropertyOrImplicitGetter - OMD is null");
1331
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001332 ObjCMessageExpr *MsgExpr;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001333 if (Super)
Douglas Gregor04badcf2010-04-21 00:45:42 +00001334 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001335 Ty.getNonReferenceType(),
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001336 /*FIXME?*/SourceLocation(),
1337 SuperLocation,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001338 /*IsInstanceSuper=*/true,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001339 SuperTy,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001340 Sel, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001341 0, 0,
1342 /*FIXME:*/SourceLocation());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001343 else {
1344 assert (Receiver && "RewritePropertyOrImplicitGetter - Receiver is null");
1345 if (Expr *Exp = dyn_cast<Expr>(Receiver))
1346 if (PropGetters[Exp])
1347 // This allows us to handle chain/nested property/implicit getters.
1348 Receiver = PropGetters[Exp];
Douglas Gregor04badcf2010-04-21 00:45:42 +00001349 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001350 Ty.getNonReferenceType(),
Douglas Gregor04badcf2010-04-21 00:45:42 +00001351 /*FIXME:*/SourceLocation(),
1352 cast<Expr>(Receiver),
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001353 Sel, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001354 0, 0,
1355 /*FIXME:*/SourceLocation());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001356 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001357
Steve Naroff4c3580e2008-12-04 23:50:32 +00001358 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001359
1360 if (!PropParentMap)
1361 PropParentMap = new ParentMap(CurrentBody);
1362
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001363 Stmt *Parent = PropParentMap->getParent(PropOrGetterRefExpr);
1364 if (Parent && (isa<ObjCPropertyRefExpr>(Parent) ||
1365 isa<ObjCImplicitSetterGetterRefExpr>(Parent))) {
Steve Naroff8599e7a2008-12-08 16:43:47 +00001366 // We stash away the ReplacingStmt since actually doing the
1367 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001368 PropGetters[PropOrGetterRefExpr] = ReplacingStmt;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001369 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1370 // to things that stay around.
1371 Context->Deallocate(MsgExpr);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001372 return PropOrGetterRefExpr; // return the original...
Steve Naroff8599e7a2008-12-08 16:43:47 +00001373 } else {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001374 ReplaceStmt(PropOrGetterRefExpr, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001375 // delete PropRefExpr; elsewhere...
Ted Kremenek8189cde2009-02-07 01:47:29 +00001376 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1377 // to things that stay around.
1378 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001379 return ReplacingStmt;
1380 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001381}
1382
Mike Stump1eb44332009-09-09 15:08:12 +00001383Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001384 SourceLocation OrigStart,
1385 bool &replaced) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001386 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001387 const Expr *BaseExpr = IV->getBase();
Steve Naroff54055232008-10-27 17:20:55 +00001388 if (CurMethodDef) {
Fariborz Jahanian8f095432010-01-26 18:28:51 +00001389 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001390 ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001391 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianffbdead2010-01-26 20:37:44 +00001392 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Narofff0757612008-05-08 17:52:16 +00001393 // lookup which class implements the instance variable.
1394 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001395 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001396 clsDeclared);
Steve Narofff0757612008-05-08 17:52:16 +00001397 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001398
Steve Narofff0757612008-05-08 17:52:16 +00001399 // Synthesize an explicit cast to gain access to the ivar.
1400 std::string RecName = clsDeclared->getIdentifier()->getName();
1401 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001402 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001403 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001404 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +00001405 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1406 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001407 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCall2de56d12010-08-25 11:45:40 +00001408 CK_Unknown,
John McCall9d125032010-01-15 18:39:57 +00001409 IV->getBase());
Steve Narofff0757612008-05-08 17:52:16 +00001410 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001411 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1412 IV->getBase()->getLocEnd(),
1413 castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001414 replaced = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001415 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001416 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001417 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1418 IV->getLocation(),
1419 D->getType());
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001420 // delete IV; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001421 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001422 }
Fariborz Jahanian7e20ffe2010-01-28 01:41:20 +00001423 // Get the new text
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001424 // Cannot delete IV->getBase(), since PE points to it.
1425 // Replace the old base with the cast. This is important when doing
1426 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001427 IV->setBase(PE);
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001428 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001429 }
Steve Naroff84472a82008-04-18 21:55:08 +00001430 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001431 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump1eb44332009-09-09 15:08:12 +00001432
Steve Naroff9f525972008-05-06 23:20:07 +00001433 // Explicit ivar refs need to have a cast inserted.
1434 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian26337b22010-01-12 17:31:23 +00001435 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Fariborz Jahanianc374cd92010-01-11 17:50:35 +00001436 ObjCInterfaceType *iFaceDecl =
1437 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001438 // lookup which class implements the instance variable.
1439 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001440 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001441 clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001442 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001443
Steve Naroff9f525972008-05-06 23:20:07 +00001444 // Synthesize an explicit cast to gain access to the ivar.
1445 std::string RecName = clsDeclared->getIdentifier()->getName();
1446 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001447 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001448 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001449 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001450 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1451 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001452 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCall2de56d12010-08-25 11:45:40 +00001453 CK_Unknown,
John McCall9d125032010-01-15 18:39:57 +00001454 IV->getBase());
Steve Naroff9f525972008-05-06 23:20:07 +00001455 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001456 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner8d366162008-05-28 16:38:23 +00001457 IV->getBase()->getLocEnd(), castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001458 replaced = true;
Steve Naroff9f525972008-05-06 23:20:07 +00001459 // Cannot delete IV->getBase(), since PE points to it.
1460 // Replace the old base with the cast. This is important when doing
1461 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001462 IV->setBase(PE);
Steve Naroff9f525972008-05-06 23:20:07 +00001463 return IV;
1464 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001465 }
Steve Naroff84472a82008-04-18 21:55:08 +00001466 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001467}
1468
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001469Stmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) {
1470 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1471 CI != E; ++CI) {
1472 if (*CI) {
1473 Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced);
1474 if (newStmt)
1475 *CI = newStmt;
1476 }
1477 }
1478 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
1479 SourceRange OrigStmtRange = S->getSourceRange();
1480 Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(),
1481 replaced);
1482 return newStmt;
Fariborz Jahanian376338a2010-02-05 17:48:10 +00001483 }
1484 if (ObjCMessageExpr *MsgRefExpr = dyn_cast<ObjCMessageExpr>(S)) {
1485 Stmt *newStmt = SynthMessageExpr(MsgRefExpr);
1486 return newStmt;
1487 }
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001488 return S;
1489}
1490
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001491/// SynthCountByEnumWithState - To print:
1492/// ((unsigned int (*)
1493/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001494/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001495/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001496/// "countByEnumeratingWithState:objects:count:"),
1497/// &enumState,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001498/// (id *)items, (unsigned int)16)
1499///
Steve Naroffb29b4272008-04-14 22:03:09 +00001500void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001501 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1502 "id *, unsigned int))(void *)objc_msgSend)";
1503 buf += "\n\t\t";
1504 buf += "((id)l_collection,\n\t\t";
1505 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1506 buf += "\n\t\t";
1507 buf += "&enumState, "
1508 "(id *)items, (unsigned int)16)";
1509}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001510
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001511/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1512/// statement to exit to its outer synthesized loop.
1513///
Steve Naroffb29b4272008-04-14 22:03:09 +00001514Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001515 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1516 return S;
1517 // replace break with goto __break_label
1518 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001519
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001520 SourceLocation startLoc = S->getLocStart();
1521 buf = "goto __break_label_";
1522 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001523 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001524
1525 return 0;
1526}
1527
1528/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1529/// statement to continue with its inner synthesized loop.
1530///
Steve Naroffb29b4272008-04-14 22:03:09 +00001531Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001532 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1533 return S;
1534 // replace continue with goto __continue_label
1535 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001536
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001537 SourceLocation startLoc = S->getLocStart();
1538 buf = "goto __continue_label_";
1539 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001540 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001541
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001542 return 0;
1543}
1544
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001545/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001546/// It rewrites:
1547/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001548
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001549/// Into:
1550/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001551/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001552/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001553/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001554/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001555/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001556/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001557/// if (limit) {
1558/// unsigned long startMutations = *enumState.mutationsPtr;
1559/// do {
1560/// unsigned long counter = 0;
1561/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001562/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001563/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001564/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001565/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001566/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001567/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001568/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001569/// objects:items count:16]);
1570/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001571/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001572/// }
1573/// else
1574/// elem = nil;
1575/// }
1576///
Steve Naroffb29b4272008-04-14 22:03:09 +00001577Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001578 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001579 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001580 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001581 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001582 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001583 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001584
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001585 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001586 const char *startBuf = SM->getCharacterData(startLoc);
Daniel Dunbar4087f272010-08-17 22:39:59 +00001587 llvm::StringRef elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001588 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001589 std::string buf;
1590 buf = "\n{\n\t";
1591 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1592 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001593 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001594 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001595 if (ElementType->isObjCQualifiedIdType() ||
1596 ElementType->isObjCQualifiedInterfaceType())
1597 // Simply use 'id' for all qualified types.
1598 elementTypeAsString = "id";
1599 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001600 elementTypeAsString = ElementType.getAsString(Context->PrintingPolicy);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001601 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001602 buf += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00001603 elementName = D->getName();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001604 buf += elementName;
1605 buf += ";\n\t";
1606 }
Chris Lattner06767512008-04-08 05:52:18 +00001607 else {
1608 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar4087f272010-08-17 22:39:59 +00001609 elementName = DR->getDecl()->getName();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001610 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1611 if (VD->getType()->isObjCQualifiedIdType() ||
1612 VD->getType()->isObjCQualifiedInterfaceType())
1613 // Simply use 'id' for all qualified types.
1614 elementTypeAsString = "id";
1615 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001616 elementTypeAsString = VD->getType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001617 }
Mike Stump1eb44332009-09-09 15:08:12 +00001618
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001619 // struct __objcFastEnumerationState enumState = { 0 };
1620 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1621 // id items[16];
1622 buf += "id items[16];\n\t";
1623 // id l_collection = (id)
1624 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001625 // Find start location of 'collection' the hard way!
1626 const char *startCollectionBuf = startBuf;
1627 startCollectionBuf += 3; // skip 'for'
1628 startCollectionBuf = strchr(startCollectionBuf, '(');
1629 startCollectionBuf++; // skip '('
1630 // find 'in' and skip it.
1631 while (*startCollectionBuf != ' ' ||
1632 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1633 (*(startCollectionBuf+3) != ' ' &&
1634 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1635 startCollectionBuf++;
1636 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001637
1638 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001639 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001640 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001641 SourceLocation rightParenLoc = S->getRParenLoc();
1642 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1643 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001644 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001645
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001646 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1647 // objects:items count:16];
1648 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001649 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001650 // ((unsigned int (*)
1651 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001652 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001653 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001654 // "countByEnumeratingWithState:objects:count:"),
1655 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001656 // (id *)items, (unsigned int)16);
1657 buf += "unsigned long limit =\n\t\t";
1658 SynthCountByEnumWithState(buf);
1659 buf += ";\n\t";
1660 /// if (limit) {
1661 /// unsigned long startMutations = *enumState.mutationsPtr;
1662 /// do {
1663 /// unsigned long counter = 0;
1664 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001665 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001666 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001667 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001668 buf += "if (limit) {\n\t";
1669 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1670 buf += "do {\n\t\t";
1671 buf += "unsigned long counter = 0;\n\t\t";
1672 buf += "do {\n\t\t\t";
1673 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1674 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1675 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001676 buf += " = (";
1677 buf += elementTypeAsString;
1678 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001679 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001680 ReplaceText(lparenLoc, 1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001681
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001682 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001683 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001684 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001685 /// objects:items count:16]);
1686 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001687 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001688 /// }
1689 /// else
1690 /// elem = nil;
1691 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001692 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001693 buf = ";\n\t";
1694 buf += "__continue_label_";
1695 buf += utostr(ObjCBcLabelNo.back());
1696 buf += ": ;";
1697 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001698 buf += "} while (counter < limit);\n\t";
1699 buf += "} while (limit = ";
1700 SynthCountByEnumWithState(buf);
1701 buf += ");\n\t";
1702 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001703 buf += " = ((";
1704 buf += elementTypeAsString;
1705 buf += ")0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001706 buf += "__break_label_";
1707 buf += utostr(ObjCBcLabelNo.back());
1708 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001709 buf += "}\n\t";
1710 buf += "else\n\t\t";
1711 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001712 buf += " = ((";
1713 buf += elementTypeAsString;
1714 buf += ")0);\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001715 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001716
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001717 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001718 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001719 if (isa<CompoundStmt>(S->getBody())) {
1720 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001721 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001722 } else {
1723 /* Need to treat single statements specially. For example:
1724 *
1725 * for (A *a in b) if (stuff()) break;
1726 * for (A *a in b) xxxyy;
1727 *
1728 * The following code simply scans ahead to the semi to find the actual end.
1729 */
1730 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1731 const char *semiBuf = strchr(stmtBuf, ';');
1732 assert(semiBuf && "Can't find ';'");
1733 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001734 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001735 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001736 Stmts.pop_back();
1737 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001738 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001739}
1740
Mike Stump1eb44332009-09-09 15:08:12 +00001741/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001742/// This routine rewrites @synchronized(expr) stmt;
1743/// into:
1744/// objc_sync_enter(expr);
1745/// @try stmt @finally { objc_sync_exit(expr); }
1746///
Steve Naroffb29b4272008-04-14 22:03:09 +00001747Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001748 // Get the start location and compute the semi location.
1749 SourceLocation startLoc = S->getLocStart();
1750 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001751
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001752 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001753
1754 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001755 buf = "objc_sync_enter((id)";
1756 const char *lparenBuf = startBuf;
1757 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramerd999b372010-02-14 14:14:16 +00001758 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001759 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1760 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001761 // been rewritten! (which implies the SourceLocation's are invalid).
1762 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001763 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001764 while (*endBuf != ')') endBuf--;
1765 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001766 buf = ");\n";
1767 // declare a new scope with two variables, _stack and _rethrow.
1768 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1769 buf += "int buf[18/*32-bit i386*/];\n";
1770 buf += "char *pointers[4];} _stack;\n";
1771 buf += "id volatile _rethrow = 0;\n";
1772 buf += "objc_exception_try_enter(&_stack);\n";
1773 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001774 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001775 startLoc = S->getSynchBody()->getLocEnd();
1776 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001777
Steve Naroffc7089f12008-08-19 13:04:19 +00001778 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001779 SourceLocation lastCurlyLoc = startLoc;
1780 buf = "}\nelse {\n";
1781 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001782 buf += "}\n";
1783 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001784 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001785
1786 std::string syncBuf;
1787 syncBuf += " objc_sync_exit(";
John McCall9d125032010-01-15 18:39:57 +00001788 Expr *syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall2de56d12010-08-25 11:45:40 +00001789 CK_Unknown,
John McCall9d125032010-01-15 18:39:57 +00001790 S->getSynchExpr());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001791 std::string syncExprBufS;
1792 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00001793 syncExpr->printPretty(syncExprBuf, *Context, 0,
1794 PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001795 syncBuf += syncExprBuf.str();
1796 syncBuf += ");";
1797
1798 buf += syncBuf;
1799 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001800 buf += "}\n";
1801 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001802
Benjamin Kramerd999b372010-02-14 14:14:16 +00001803 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001804
1805 bool hasReturns = false;
1806 HasReturnStmts(S->getSynchBody(), hasReturns);
1807 if (hasReturns)
1808 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1809
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001810 return 0;
1811}
1812
Steve Naroffb85e77a2009-12-05 21:43:12 +00001813void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1814{
Steve Naroff8c565152008-12-05 17:03:39 +00001815 // Perform a bottom up traversal of all children.
1816 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1817 CI != E; ++CI)
1818 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001819 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001820
Steve Naroffb85e77a2009-12-05 21:43:12 +00001821 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001822 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001823 TryFinallyContainsReturnDiag);
1824 }
1825 return;
1826}
1827
Steve Naroffb85e77a2009-12-05 21:43:12 +00001828void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1829{
1830 // Perform a bottom up traversal of all children.
1831 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1832 CI != E; ++CI)
1833 if (*CI)
1834 HasReturnStmts(*CI, hasReturns);
1835
1836 if (isa<ReturnStmt>(S))
1837 hasReturns = true;
1838 return;
1839}
1840
1841void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1842 // Perform a bottom up traversal of all children.
1843 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1844 CI != E; ++CI)
1845 if (*CI) {
1846 RewriteTryReturnStmts(*CI);
1847 }
1848 if (isa<ReturnStmt>(S)) {
1849 SourceLocation startLoc = S->getLocStart();
1850 const char *startBuf = SM->getCharacterData(startLoc);
1851
1852 const char *semiBuf = strchr(startBuf, ';');
1853 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1854 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1855
1856 std::string buf;
1857 buf = "{ objc_exception_try_exit(&_stack); return";
1858
Benjamin Kramerd999b372010-02-14 14:14:16 +00001859 ReplaceText(startLoc, 6, buf);
1860 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001861 }
1862 return;
1863}
1864
1865void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1866 // Perform a bottom up traversal of all children.
1867 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1868 CI != E; ++CI)
1869 if (*CI) {
1870 RewriteSyncReturnStmts(*CI, syncExitBuf);
1871 }
1872 if (isa<ReturnStmt>(S)) {
1873 SourceLocation startLoc = S->getLocStart();
1874 const char *startBuf = SM->getCharacterData(startLoc);
1875
1876 const char *semiBuf = strchr(startBuf, ';');
1877 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1878 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1879
1880 std::string buf;
1881 buf = "{ objc_exception_try_exit(&_stack);";
1882 buf += syncExitBuf;
1883 buf += " return";
1884
Benjamin Kramerd999b372010-02-14 14:14:16 +00001885 ReplaceText(startLoc, 6, buf);
1886 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001887 }
1888 return;
1889}
1890
Steve Naroffb29b4272008-04-14 22:03:09 +00001891Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001892 // Get the start location and compute the semi location.
1893 SourceLocation startLoc = S->getLocStart();
1894 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001895
Steve Naroff75730982007-11-07 04:08:17 +00001896 assert((*startBuf == '@') && "bogus @try location");
1897
1898 std::string buf;
1899 // declare a new scope with two variables, _stack and _rethrow.
1900 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1901 buf += "int buf[18/*32-bit i386*/];\n";
1902 buf += "char *pointers[4];} _stack;\n";
1903 buf += "id volatile _rethrow = 0;\n";
1904 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001905 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001906
Benjamin Kramerd999b372010-02-14 14:14:16 +00001907 ReplaceText(startLoc, 4, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001908
Steve Naroff75730982007-11-07 04:08:17 +00001909 startLoc = S->getTryBody()->getLocEnd();
1910 startBuf = SM->getCharacterData(startLoc);
1911
1912 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001913
Steve Naroff75730982007-11-07 04:08:17 +00001914 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001915 if (S->getNumCatchStmts()) {
Steve Naroffc9ba1722008-07-16 15:31:30 +00001916 startLoc = startLoc.getFileLocWithOffset(1);
1917 buf = " /* @catch begin */ else {\n";
1918 buf += " id _caught = objc_exception_extract(&_stack);\n";
1919 buf += " objc_exception_try_enter (&_stack);\n";
1920 buf += " if (_setjmp(_stack.buf))\n";
1921 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1922 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00001923
Benjamin Kramerd999b372010-02-14 14:14:16 +00001924 InsertText(startLoc, buf);
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001925 } else { /* no catch list */
1926 buf = "}\nelse {\n";
1927 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1928 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001929 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001930 }
Steve Naroff75730982007-11-07 04:08:17 +00001931 bool sawIdTypedCatch = false;
1932 Stmt *lastCatchBody = 0;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001933 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1934 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregorc00d8e12010-04-26 16:46:50 +00001935 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00001936
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001937 if (I == 0)
Steve Naroff75730982007-11-07 04:08:17 +00001938 buf = "if ("; // we are generating code for the first catch clause
1939 else
1940 buf = "else if (";
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001941 startLoc = Catch->getLocStart();
Steve Naroff75730982007-11-07 04:08:17 +00001942 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001943
Steve Naroff75730982007-11-07 04:08:17 +00001944 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00001945
Steve Naroff75730982007-11-07 04:08:17 +00001946 const char *lParenLoc = strchr(startBuf, '(');
1947
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001948 if (Catch->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001949 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001950 lastCatchBody = Catch->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001951 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1952 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001953 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner06767512008-04-08 05:52:18 +00001954 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001955 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001956
Steve Naroffe12e6922008-02-01 20:02:07 +00001957 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00001958 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00001959 } else if (catchDecl) {
1960 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001961 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001962 buf += "1) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001963 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00001964 sawIdTypedCatch = true;
John McCall506b57e2010-05-17 21:00:27 +00001965 } else if (const ObjCObjectPointerType *Ptr =
1966 t->getAs<ObjCObjectPointerType>()) {
1967 // Should be a pointer to a class.
1968 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1969 if (IDecl) {
Steve Naroff21867b12007-11-07 18:43:40 +00001970 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall506b57e2010-05-17 21:00:27 +00001971 buf += IDecl->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001972 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001973 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00001974 }
1975 }
1976 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001977 lastCatchBody = Catch->getCatchBody();
1978 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroff75730982007-11-07 04:08:17 +00001979 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1980 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1981 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1982 assert((*rParenBuf == ')') && "bogus @catch paren location");
1983 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001984
Mike Stump1eb44332009-09-09 15:08:12 +00001985 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00001986 // declares the @catch parameter).
Benjamin Kramerd999b372010-02-14 14:14:16 +00001987 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff7ba138a2009-03-03 19:52:17 +00001988 } else {
Steve Naroff75730982007-11-07 04:08:17 +00001989 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001990 }
Steve Naroff75730982007-11-07 04:08:17 +00001991 }
1992 // Complete the catch list...
1993 if (lastCatchBody) {
1994 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001995 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1996 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001997
Steve Naroff378f47a2008-09-11 15:29:03 +00001998 // Insert the last (implicit) else clause *before* the right curly brace.
1999 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
2000 buf = "} /* last catch end */\n";
2001 buf += "else {\n";
2002 buf += " _rethrow = _caught;\n";
2003 buf += " objc_exception_try_exit(&_stack);\n";
2004 buf += "} } /* @catch end */\n";
2005 if (!S->getFinallyStmt())
2006 buf += "}\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002007 InsertText(bodyLoc, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002008
Steve Naroff75730982007-11-07 04:08:17 +00002009 // Set lastCurlyLoc
2010 lastCurlyLoc = lastCatchBody->getLocEnd();
2011 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002012 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00002013 startLoc = finalStmt->getLocStart();
2014 startBuf = SM->getCharacterData(startLoc);
2015 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00002016
Benjamin Kramerd999b372010-02-14 14:14:16 +00002017 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump1eb44332009-09-09 15:08:12 +00002018
Steve Naroff75730982007-11-07 04:08:17 +00002019 Stmt *body = finalStmt->getFinallyBody();
2020 SourceLocation startLoc = body->getLocStart();
2021 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00002022 assert(*SM->getCharacterData(startLoc) == '{' &&
2023 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002024 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00002025 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002026
Steve Naroff75730982007-11-07 04:08:17 +00002027 startLoc = startLoc.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002028 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Steve Naroff75730982007-11-07 04:08:17 +00002029 endLoc = endLoc.getFileLocWithOffset(-1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002030 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002031
Steve Naroff75730982007-11-07 04:08:17 +00002032 // Set lastCurlyLoc
2033 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00002034
Steve Naroff8c565152008-12-05 17:03:39 +00002035 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00002036 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00002037 } else { /* no finally clause - make sure we synthesize an implicit one */
2038 buf = "{ /* implicit finally clause */\n";
2039 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
2040 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
2041 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002042 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00002043
2044 // Now check for any return/continue/go statements within the @try.
2045 // The implicit finally clause won't called if the @try contains any
2046 // jump statements.
2047 bool hasReturns = false;
2048 HasReturnStmts(S->getTryBody(), hasReturns);
2049 if (hasReturns)
2050 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00002051 }
2052 // Now emit the final closing curly brace...
2053 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002054 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002055 return 0;
2056}
2057
Mike Stump1eb44332009-09-09 15:08:12 +00002058// This can't be done with ReplaceStmt(S, ThrowExpr), since
2059// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00002060// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00002061Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00002062 // Get the start location and compute the semi location.
2063 SourceLocation startLoc = S->getLocStart();
2064 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00002065
Steve Naroff2bd03922007-11-07 15:32:26 +00002066 assert((*startBuf == '@') && "bogus @throw location");
2067
2068 std::string buf;
2069 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00002070 if (S->getThrowExpr())
2071 buf = "objc_exception_throw(";
2072 else // add an implicit argument
2073 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00002074
Steve Naroff4ba0acb2008-07-25 15:41:30 +00002075 // handle "@ throw" correctly.
2076 const char *wBuf = strchr(startBuf, 'w');
2077 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramerd999b372010-02-14 14:14:16 +00002078 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002079
Steve Naroff2bd03922007-11-07 15:32:26 +00002080 const char *semiBuf = strchr(startBuf, ';');
2081 assert((*semiBuf == ';') && "@throw: can't find ';'");
2082 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002083 ReplaceText(semiLoc, 1, ");");
Steve Naroff2bd03922007-11-07 15:32:26 +00002084 return 0;
2085}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002086
Steve Naroffb29b4272008-04-14 22:03:09 +00002087Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00002088 // Create a new string expression.
2089 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002090 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002091 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattner2085fd62009-02-18 06:40:38 +00002092 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
2093 StrEncoding.length(), false,StrType,
2094 SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002095 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00002096
Chris Lattner07506182007-11-30 22:53:43 +00002097 // Replace this subexpr in the parent.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002098 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00002099 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00002100}
2101
Steve Naroffb29b4272008-04-14 22:03:09 +00002102Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00002103 if (!SelGetUidFunctionDecl)
2104 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00002105 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2106 // Create a call to sel_registerName("selName").
2107 llvm::SmallVector<Expr*, 8> SelExprs;
2108 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002109 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002110 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00002111 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00002112 false, argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00002113 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2114 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002115 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002116 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00002117 return SelExp;
2118}
2119
Steve Naroffb29b4272008-04-14 22:03:09 +00002120CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002121 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2122 SourceLocation EndLoc) {
Steve Naroffebf2b562007-10-23 23:50:29 +00002123 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00002124 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002125
Steve Naroffebf2b562007-10-23 23:50:29 +00002126 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002127 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002128
Steve Naroffebf2b562007-10-23 23:50:29 +00002129 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00002130 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson88465d32010-04-23 22:18:37 +00002131 ImplicitCastExpr *ICE =
John McCall2de56d12010-08-25 11:45:40 +00002132 ImplicitCastExpr::Create(*Context, pToFunc, CK_Unknown,
John McCall5baba9d2010-08-25 10:28:54 +00002133 DRE, 0, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00002134
John McCall183700f2009-09-21 23:43:11 +00002135 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002136
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002137 CallExpr *Exp =
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002138 new (Context) CallExpr(*Context, ICE, args, nargs,
2139 FT->getCallResultType(*Context), EndLoc);
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002140 return Exp;
Steve Naroff934f2762007-10-24 22:48:43 +00002141}
2142
Steve Naroffd5255f52007-11-01 13:24:47 +00002143static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2144 const char *&startRef, const char *&endRef) {
2145 while (startBuf < endBuf) {
2146 if (*startBuf == '<')
2147 startRef = startBuf; // mark the start.
2148 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00002149 if (startRef && *startRef == '<') {
2150 endRef = startBuf; // mark the end.
2151 return true;
2152 }
2153 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002154 }
2155 startBuf++;
2156 }
2157 return false;
2158}
2159
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002160static void scanToNextArgument(const char *&argRef) {
2161 int angle = 0;
2162 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2163 if (*argRef == '<')
2164 angle++;
2165 else if (*argRef == '>')
2166 angle--;
2167 argRef++;
2168 }
2169 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2170}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002171
Steve Naroffb29b4272008-04-14 22:03:09 +00002172bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian32132a02010-02-03 21:29:28 +00002173 if (T->isObjCQualifiedIdType())
2174 return true;
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002175 if (const PointerType *PT = T->getAs<PointerType>()) {
2176 if (PT->getPointeeType()->isObjCQualifiedIdType())
2177 return true;
2178 }
2179 if (T->isObjCObjectPointerType()) {
2180 T = T->getPointeeType();
2181 return T->isObjCQualifiedInterfaceType();
2182 }
Fariborz Jahanian24f9cab2010-09-30 20:41:32 +00002183 if (T->isArrayType()) {
2184 QualType ElemTy = Context->getBaseElementType(T);
2185 return needToScanForQualifiers(ElemTy);
2186 }
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002187 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002188}
2189
Steve Naroff4f95b752008-07-29 18:15:38 +00002190void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2191 QualType Type = E->getType();
2192 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00002193 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00002194
Steve Naroffcda658e2008-11-19 21:15:47 +00002195 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2196 Loc = ECE->getLParenLoc();
2197 EndLoc = ECE->getRParenLoc();
2198 } else {
2199 Loc = E->getLocStart();
2200 EndLoc = E->getLocEnd();
2201 }
2202 // This will defend against trying to rewrite synthesized expressions.
2203 if (Loc.isInvalid() || EndLoc.isInvalid())
2204 return;
2205
Steve Naroff4f95b752008-07-29 18:15:38 +00002206 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00002207 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00002208 const char *startRef = 0, *endRef = 0;
2209 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2210 // Get the locations of the startRef, endRef.
2211 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2212 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2213 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002214 InsertText(LessLoc, "/*");
2215 InsertText(GreaterLoc, "*/");
Steve Naroff4f95b752008-07-29 18:15:38 +00002216 }
2217 }
2218}
2219
Steve Naroffb29b4272008-04-14 22:03:09 +00002220void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002221 SourceLocation Loc;
2222 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00002223 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002224 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2225 Loc = VD->getLocation();
2226 Type = VD->getType();
2227 }
2228 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2229 Loc = FD->getLocation();
2230 // Check for ObjC 'id' and class types that have been adorned with protocol
2231 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002232 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002233 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002234 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002235 if (!proto)
2236 return;
2237 Type = proto->getResultType();
2238 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002239 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2240 Loc = FD->getLocation();
2241 Type = FD->getType();
2242 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002243 else
2244 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002245
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002246 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002247 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002248
Steve Naroffd5255f52007-11-01 13:24:47 +00002249 const char *endBuf = SM->getCharacterData(Loc);
2250 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002251 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002252 startBuf--; // scan backward (from the decl location) for return type.
2253 const char *startRef = 0, *endRef = 0;
2254 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2255 // Get the locations of the startRef, endRef.
2256 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2257 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2258 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002259 InsertText(LessLoc, "/*");
2260 InsertText(GreaterLoc, "*/");
Steve Naroff9165ad32007-10-31 04:38:33 +00002261 }
2262 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002263 if (!proto)
2264 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002265 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002266 const char *startBuf = SM->getCharacterData(Loc);
2267 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00002268 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2269 if (needToScanForQualifiers(proto->getArgType(i))) {
2270 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002271
Steve Naroffd5255f52007-11-01 13:24:47 +00002272 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002273 // scan forward (from the decl location) for argument types.
2274 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00002275 const char *startRef = 0, *endRef = 0;
2276 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2277 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002278 SourceLocation LessLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002279 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002280 SourceLocation GreaterLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002281 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002282 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002283 InsertText(LessLoc, "/*");
2284 InsertText(GreaterLoc, "*/");
Steve Naroffd5255f52007-11-01 13:24:47 +00002285 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002286 startBuf = ++endBuf;
2287 }
2288 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002289 // If the function name is derived from a macro expansion, then the
2290 // argument buffer will not follow the name. Need to speak with Chris.
2291 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002292 startBuf++; // scan forward (from the decl location) for argument types.
2293 startBuf++;
2294 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002295 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002296}
2297
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002298void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2299 QualType QT = ND->getType();
2300 const Type* TypePtr = QT->getAs<Type>();
2301 if (!isa<TypeOfExprType>(TypePtr))
2302 return;
2303 while (isa<TypeOfExprType>(TypePtr)) {
2304 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2305 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2306 TypePtr = QT->getAs<Type>();
2307 }
2308 // FIXME. This will not work for multiple declarators; as in:
2309 // __typeof__(a) b,c,d;
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002310 std::string TypeAsString(QT.getAsString(Context->PrintingPolicy));
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002311 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2312 const char *startBuf = SM->getCharacterData(DeclLoc);
2313 if (ND->getInit()) {
2314 std::string Name(ND->getNameAsString());
2315 TypeAsString += " " + Name + " = ";
2316 Expr *E = ND->getInit();
2317 SourceLocation startLoc;
2318 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2319 startLoc = ECE->getLParenLoc();
2320 else
2321 startLoc = E->getLocStart();
2322 startLoc = SM->getInstantiationLoc(startLoc);
2323 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002324 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002325 }
2326 else {
2327 SourceLocation X = ND->getLocEnd();
2328 X = SM->getInstantiationLoc(X);
2329 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002330 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002331 }
2332}
2333
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002334// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002335void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002336 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2337 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002338 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002339 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002340 &ArgTys[0], ArgTys.size(),
2341 false /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002342 false, false, 0, 0,
2343 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002344 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002345 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002346 SelGetUidIdent, getFuncType, 0,
John McCalld931b082010-08-26 03:08:43 +00002347 SC_Extern,
2348 SC_None, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002349}
2350
Steve Naroffb29b4272008-04-14 22:03:09 +00002351void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002352 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002353 if (FD->getIdentifier() &&
Daniel Dunbar4087f272010-08-17 22:39:59 +00002354 FD->getName() == "sel_registerName") {
Steve Naroff09b266e2007-10-30 23:14:51 +00002355 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002356 return;
2357 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002358 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002359}
2360
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002361void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2362 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002363 const char *argPtr = TypeString.c_str();
2364 if (!strchr(argPtr, '^')) {
2365 Str += TypeString;
2366 return;
2367 }
2368 while (*argPtr) {
2369 Str += (*argPtr == '^' ? '*' : *argPtr);
2370 argPtr++;
2371 }
2372}
2373
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002374// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002375void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2376 ValueDecl *VD) {
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002377 QualType Type = VD->getType();
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002378 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002379 const char *argPtr = TypeString.c_str();
2380 int paren = 0;
2381 while (*argPtr) {
2382 switch (*argPtr) {
2383 case '(':
2384 Str += *argPtr;
2385 paren++;
2386 break;
2387 case ')':
2388 Str += *argPtr;
2389 paren--;
2390 break;
2391 case '^':
2392 Str += '*';
2393 if (paren == 1)
2394 Str += VD->getNameAsString();
2395 break;
2396 default:
2397 Str += *argPtr;
2398 break;
2399 }
2400 argPtr++;
2401 }
2402}
2403
2404
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002405void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2406 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2407 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2408 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2409 if (!proto)
2410 return;
2411 QualType Type = proto->getResultType();
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002412 std::string FdStr = Type.getAsString(Context->PrintingPolicy);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002413 FdStr += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00002414 FdStr += FD->getName();
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002415 FdStr += "(";
2416 unsigned numArgs = proto->getNumArgs();
2417 for (unsigned i = 0; i < numArgs; i++) {
2418 QualType ArgType = proto->getArgType(i);
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002419 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002420 if (i+1 < numArgs)
2421 FdStr += ", ";
2422 }
2423 FdStr += ");\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002424 InsertText(FunLocStart, FdStr);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002425 CurFunctionDeclToDeclareForBlock = 0;
2426}
2427
Steve Naroffc0a123c2008-03-11 17:37:02 +00002428// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002429void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002430 if (SuperContructorFunctionDecl)
2431 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002432 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroffc0a123c2008-03-11 17:37:02 +00002433 llvm::SmallVector<QualType, 16> ArgTys;
2434 QualType argT = Context->getObjCIdType();
2435 assert(!argT.isNull() && "Can't find 'id' type");
2436 ArgTys.push_back(argT);
2437 ArgTys.push_back(argT);
2438 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2439 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002440 false, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002441 false, false, 0, 0,
2442 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002443 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002444 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002445 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002446 SC_Extern,
2447 SC_None, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002448}
2449
Steve Naroff09b266e2007-10-30 23:14:51 +00002450// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002451void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002452 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2453 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002454 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002455 assert(!argT.isNull() && "Can't find 'id' type");
2456 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002457 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002458 assert(!argT.isNull() && "Can't find 'SEL' type");
2459 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002460 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002461 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002462 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002463 false, false, 0, 0,
2464 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002465 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002466 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002467 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002468 SC_Extern,
2469 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002470}
2471
Steve Naroff874e2322007-11-15 10:28:18 +00002472// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002473void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002474 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2475 llvm::SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002476 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002477 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002478 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002479 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2480 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2481 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002482 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002483 assert(!argT.isNull() && "Can't find 'SEL' type");
2484 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002485 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00002486 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002487 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002488 false, false, 0, 0,
2489 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002490 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002491 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002492 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002493 SC_Extern,
2494 SC_None, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002495}
2496
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002497// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002498void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002499 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2500 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002501 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002502 assert(!argT.isNull() && "Can't find 'id' type");
2503 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002504 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002505 assert(!argT.isNull() && "Can't find 'SEL' type");
2506 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002507 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002508 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002509 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002510 false, false, 0, 0,
2511 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002512 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002513 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002514 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002515 SC_Extern,
2516 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002517}
2518
Mike Stump1eb44332009-09-09 15:08:12 +00002519// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002520// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002521void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002522 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002523 &Context->Idents.get("objc_msgSendSuper_stret");
2524 llvm::SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002525 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002526 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002527 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002528 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2529 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2530 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002531 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002532 assert(!argT.isNull() && "Can't find 'SEL' type");
2533 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002534 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002535 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002536 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002537 false, false, 0, 0,
2538 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002539 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002540 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002541 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002542 SC_Extern,
2543 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002544}
2545
Steve Naroff1284db82008-05-08 22:02:18 +00002546// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002547void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002548 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2549 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002550 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002551 assert(!argT.isNull() && "Can't find 'id' type");
2552 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002553 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002554 assert(!argT.isNull() && "Can't find 'SEL' type");
2555 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00002556 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002557 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002558 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002559 false, false, 0, 0,
2560 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002561 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002562 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002563 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002564 SC_Extern,
2565 SC_None, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002566}
2567
Steve Naroff09b266e2007-10-30 23:14:51 +00002568// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002569void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002570 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2571 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002572 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002573 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002574 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002575 false /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002576 false, false, 0, 0,
2577 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002578 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002579 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002580 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002581 SC_Extern,
2582 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002583}
2584
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002585// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2586void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2587 IdentifierInfo *getSuperClassIdent =
2588 &Context->Idents.get("class_getSuperclass");
2589 llvm::SmallVector<QualType, 16> ArgTys;
2590 ArgTys.push_back(Context->getObjCClassType());
2591 QualType getClassType = Context->getFunctionType(Context->getObjCClassType(),
2592 &ArgTys[0], ArgTys.size(),
2593 false /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002594 false, false, 0, 0,
2595 FunctionType::ExtInfo());
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002596 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002597 SourceLocation(),
2598 getSuperClassIdent,
2599 getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002600 SC_Extern,
2601 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002602 false);
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002603}
2604
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002605// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002606void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002607 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2608 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002609 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002610 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002611 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002612 false /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002613 false, false, 0, 0,
2614 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002615 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002616 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002617 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002618 SC_Extern,
2619 SC_None, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002620}
2621
Steve Naroffb29b4272008-04-14 22:03:09 +00002622Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002623 QualType strType = getConstantStringStructType();
2624
2625 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002626
2627 std::string tmpName = InFileName;
2628 unsigned i;
2629 for (i=0; i < tmpName.length(); i++) {
2630 char c = tmpName.at(i);
2631 // replace any non alphanumeric characters with '_'.
2632 if (!isalpha(c) && (c < '0' || c > '9'))
2633 tmpName[i] = '_';
2634 }
2635 S += tmpName;
2636 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002637 S += utostr(NumObjCStringLiterals++);
2638
Steve Naroffba92b2e2008-03-27 22:29:16 +00002639 Preamble += "static __NSConstantStringImpl " + S;
2640 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2641 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002642 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002643 std::string prettyBufS;
2644 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00002645 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2646 PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002647 Preamble += prettyBuf.str();
2648 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002649 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002650
2651 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Benjamin Kramerd999b372010-02-14 14:14:16 +00002652 &Context->Idents.get(S), strType, 0,
John McCalld931b082010-08-26 03:08:43 +00002653 SC_Static, SC_None);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002654 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00002655 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002656 Context->getPointerType(DRE->getType()),
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002657 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002658 // cast to NSConstantString *
John McCall9d125032010-01-15 18:39:57 +00002659 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCall2de56d12010-08-25 11:45:40 +00002660 CK_Unknown, Unop);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002661 ReplaceStmt(Exp, cast);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002662 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002663 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002664}
2665
Steve Naroff874e2322007-11-15 10:28:18 +00002666// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002667QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002668 if (!SuperStructDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002669 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002670 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002671 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002672 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002673
Steve Naroff874e2322007-11-15 10:28:18 +00002674 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002675 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002676 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002677 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002678
Steve Naroff874e2322007-11-15 10:28:18 +00002679 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002680 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002681 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2682 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002683 FieldTypes[i], 0,
2684 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002685 /*Mutable=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002686 }
Mike Stump1eb44332009-09-09 15:08:12 +00002687
Douglas Gregor838db382010-02-11 01:19:42 +00002688 SuperStructDecl->completeDefinition();
Steve Naroff874e2322007-11-15 10:28:18 +00002689 }
2690 return Context->getTagDeclType(SuperStructDecl);
2691}
2692
Steve Naroffb29b4272008-04-14 22:03:09 +00002693QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002694 if (!ConstantStringDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002695 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002696 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002697 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002698 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002699
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002700 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002701 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002702 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002703 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002704 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002705 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002706 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002707 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002708
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002709 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002710 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002711 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2712 ConstantStringDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002713 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002714 FieldTypes[i], 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00002715 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002716 /*Mutable=*/true));
Douglas Gregor44b43212008-12-11 16:49:14 +00002717 }
2718
Douglas Gregor838db382010-02-11 01:19:42 +00002719 ConstantStringDecl->completeDefinition();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002720 }
2721 return Context->getTagDeclType(ConstantStringDecl);
2722}
2723
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002724Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2725 SourceLocation StartLoc,
2726 SourceLocation EndLoc) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002727 if (!SelGetUidFunctionDecl)
2728 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002729 if (!MsgSendFunctionDecl)
2730 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002731 if (!MsgSendSuperFunctionDecl)
2732 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002733 if (!MsgSendStretFunctionDecl)
2734 SynthMsgSendStretFunctionDecl();
2735 if (!MsgSendSuperStretFunctionDecl)
2736 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002737 if (!MsgSendFpretFunctionDecl)
2738 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002739 if (!GetClassFunctionDecl)
2740 SynthGetClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002741 if (!GetSuperClassFunctionDecl)
2742 SynthGetSuperClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002743 if (!GetMetaClassFunctionDecl)
2744 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002745
Steve Naroff874e2322007-11-15 10:28:18 +00002746 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002747 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2748 // May need to use objc_msgSend_stret() as well.
2749 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002750 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2751 QualType resultType = mDecl->getResultType();
Douglas Gregorfb87b892010-04-26 21:31:17 +00002752 if (resultType->isRecordType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002753 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002754 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002755 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002756 }
Mike Stump1eb44332009-09-09 15:08:12 +00002757
Steve Naroff934f2762007-10-24 22:48:43 +00002758 // Synthesize a call to objc_msgSend().
2759 llvm::SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002760 switch (Exp->getReceiverKind()) {
2761 case ObjCMessageExpr::SuperClass: {
2762 MsgSendFlavor = MsgSendSuperFunctionDecl;
2763 if (MsgSendStretFlavor)
2764 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2765 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002766
Douglas Gregor04badcf2010-04-21 00:45:42 +00002767 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00002768
Douglas Gregor04badcf2010-04-21 00:45:42 +00002769 llvm::SmallVector<Expr*, 4> InitExprs;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002770
Douglas Gregor04badcf2010-04-21 00:45:42 +00002771 // set the receiver to self, the first argument to all methods.
2772 InitExprs.push_back(
2773 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall2de56d12010-08-25 11:45:40 +00002774 CK_Unknown,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002775 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2776 Context->getObjCIdType(),
2777 SourceLocation()))
2778 ); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002779
Douglas Gregor04badcf2010-04-21 00:45:42 +00002780 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2781 llvm::SmallVector<Expr*, 8> ClsExprs;
2782 QualType argType = Context->getPointerType(Context->CharTy);
2783 ClsExprs.push_back(StringLiteral::Create(*Context,
2784 ClassDecl->getIdentifier()->getNameStart(),
2785 ClassDecl->getIdentifier()->getLength(),
2786 false, argType, SourceLocation()));
2787 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2788 &ClsExprs[0],
2789 ClsExprs.size(),
2790 StartLoc,
2791 EndLoc);
2792 // (Class)objc_getClass("CurrentClass")
2793 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2794 Context->getObjCClassType(),
John McCall2de56d12010-08-25 11:45:40 +00002795 CK_Unknown, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002796 ClsExprs.clear();
2797 ClsExprs.push_back(ArgExpr);
2798 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2799 &ClsExprs[0], ClsExprs.size(),
2800 StartLoc, EndLoc);
2801
2802 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2803 // To turn off a warning, type-cast to 'id'
2804 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2805 NoTypeInfoCStyleCastExpr(Context,
2806 Context->getObjCIdType(),
John McCall2de56d12010-08-25 11:45:40 +00002807 CK_Unknown, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002808 // struct objc_super
2809 QualType superType = getSuperStructType();
2810 Expr *SuperRep;
Steve Naroff621edce2009-04-29 16:37:50 +00002811
Douglas Gregor04badcf2010-04-21 00:45:42 +00002812 if (LangOpts.Microsoft) {
2813 SynthSuperContructorFunctionDecl();
2814 // Simulate a contructor call...
2815 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
2816 superType, SourceLocation());
2817 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2818 InitExprs.size(),
2819 superType, SourceLocation());
2820 // The code for super is a little tricky to prevent collision with
2821 // the structure definition in the header. The rewriter has it's own
2822 // internal definition (__rw_objc_super) that is uses. This is why
2823 // we need the cast below. For example:
2824 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2825 //
John McCall2de56d12010-08-25 11:45:40 +00002826 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002827 Context->getPointerType(SuperRep->getType()),
2828 SourceLocation());
2829 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2830 Context->getPointerType(superType),
John McCall2de56d12010-08-25 11:45:40 +00002831 CK_Unknown, SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002832 } else {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002833 // (struct objc_super) { <exprs from above> }
2834 InitListExpr *ILE =
2835 new (Context) InitListExpr(*Context, SourceLocation(),
2836 &InitExprs[0], InitExprs.size(),
2837 SourceLocation());
2838 TypeSourceInfo *superTInfo
2839 = Context->getTrivialTypeSourceInfo(superType);
2840 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2841 superType, ILE, false);
2842 // struct objc_super *
John McCall2de56d12010-08-25 11:45:40 +00002843 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002844 Context->getPointerType(SuperRep->getType()),
2845 SourceLocation());
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002846 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002847 MsgExprs.push_back(SuperRep);
2848 break;
Steve Naroff6568d4d2007-11-14 23:54:14 +00002849 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002850
2851 case ObjCMessageExpr::Class: {
2852 llvm::SmallVector<Expr*, 8> ClsExprs;
2853 QualType argType = Context->getPointerType(Context->CharTy);
2854 ObjCInterfaceDecl *Class
John McCall506b57e2010-05-17 21:00:27 +00002855 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00002856 IdentifierInfo *clsName = Class->getIdentifier();
2857 ClsExprs.push_back(StringLiteral::Create(*Context,
2858 clsName->getNameStart(),
2859 clsName->getLength(),
2860 false, argType,
2861 SourceLocation()));
2862 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2863 &ClsExprs[0],
2864 ClsExprs.size(),
2865 StartLoc, EndLoc);
2866 MsgExprs.push_back(Cls);
2867 break;
2868 }
2869
2870 case ObjCMessageExpr::SuperInstance:{
2871 MsgSendFlavor = MsgSendSuperFunctionDecl;
2872 if (MsgSendStretFlavor)
2873 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2874 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2875 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2876 llvm::SmallVector<Expr*, 4> InitExprs;
2877
2878 InitExprs.push_back(
2879 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall2de56d12010-08-25 11:45:40 +00002880 CK_Unknown,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002881 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2882 Context->getObjCIdType(),
2883 SourceLocation()))
2884 ); // set the 'receiver'.
2885
2886 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2887 llvm::SmallVector<Expr*, 8> ClsExprs;
2888 QualType argType = Context->getPointerType(Context->CharTy);
2889 ClsExprs.push_back(StringLiteral::Create(*Context,
2890 ClassDecl->getIdentifier()->getNameStart(),
2891 ClassDecl->getIdentifier()->getLength(),
2892 false, argType, SourceLocation()));
2893 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2894 &ClsExprs[0],
2895 ClsExprs.size(),
2896 StartLoc, EndLoc);
2897 // (Class)objc_getClass("CurrentClass")
2898 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2899 Context->getObjCClassType(),
John McCall2de56d12010-08-25 11:45:40 +00002900 CK_Unknown, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002901 ClsExprs.clear();
2902 ClsExprs.push_back(ArgExpr);
2903 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2904 &ClsExprs[0], ClsExprs.size(),
2905 StartLoc, EndLoc);
2906
2907 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2908 // To turn off a warning, type-cast to 'id'
2909 InitExprs.push_back(
2910 // set 'super class', using class_getSuperclass().
2911 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall2de56d12010-08-25 11:45:40 +00002912 CK_Unknown, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002913 // struct objc_super
2914 QualType superType = getSuperStructType();
2915 Expr *SuperRep;
2916
2917 if (LangOpts.Microsoft) {
2918 SynthSuperContructorFunctionDecl();
2919 // Simulate a contructor call...
2920 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
2921 superType, SourceLocation());
2922 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2923 InitExprs.size(),
2924 superType, SourceLocation());
2925 // The code for super is a little tricky to prevent collision with
2926 // the structure definition in the header. The rewriter has it's own
2927 // internal definition (__rw_objc_super) that is uses. This is why
2928 // we need the cast below. For example:
2929 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2930 //
John McCall2de56d12010-08-25 11:45:40 +00002931 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002932 Context->getPointerType(SuperRep->getType()),
2933 SourceLocation());
2934 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2935 Context->getPointerType(superType),
John McCall2de56d12010-08-25 11:45:40 +00002936 CK_Unknown, SuperRep);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002937 } else {
2938 // (struct objc_super) { <exprs from above> }
2939 InitListExpr *ILE =
2940 new (Context) InitListExpr(*Context, SourceLocation(),
2941 &InitExprs[0], InitExprs.size(),
2942 SourceLocation());
2943 TypeSourceInfo *superTInfo
2944 = Context->getTrivialTypeSourceInfo(superType);
2945 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2946 superType, ILE, false);
2947 }
2948 MsgExprs.push_back(SuperRep);
2949 break;
2950 }
2951
2952 case ObjCMessageExpr::Instance: {
2953 // Remove all type-casts because it may contain objc-style types; e.g.
2954 // Foo<Proto> *.
2955 Expr *recExpr = Exp->getInstanceReceiver();
2956 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2957 recExpr = CE->getSubExpr();
2958 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall2de56d12010-08-25 11:45:40 +00002959 CK_Unknown, recExpr);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002960 MsgExprs.push_back(recExpr);
2961 break;
2962 }
2963 }
2964
Steve Naroffbeaf2992007-11-03 11:27:19 +00002965 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002966 llvm::SmallVector<Expr*, 8> SelExprs;
2967 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002968 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002969 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00002970 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00002971 false, argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00002972 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002973 &SelExprs[0], SelExprs.size(),
2974 StartLoc,
2975 EndLoc);
Steve Naroff934f2762007-10-24 22:48:43 +00002976 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002977
Steve Naroff934f2762007-10-24 22:48:43 +00002978 // Now push any user supplied arguments.
2979 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002980 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002981 // Make all implicit casts explicit...ICE comes in handy:-)
2982 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2983 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002984 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002985 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002986 : ICE->getType();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00002987 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00002988 (void)convertBlockPointerToFunctionPointer(type);
John McCall2de56d12010-08-25 11:45:40 +00002989 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK_Unknown,
John McCall9d125032010-01-15 18:39:57 +00002990 userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002991 }
2992 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002993 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002994 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002995 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002996 userExpr = CE->getSubExpr();
John McCall9d125032010-01-15 18:39:57 +00002997 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall2de56d12010-08-25 11:45:40 +00002998 CK_Unknown, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002999 }
Mike Stump1eb44332009-09-09 15:08:12 +00003000 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00003001 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003002 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3003 // out the argument in the original expression (since we aren't deleting
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003004 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003005 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00003006 }
Steve Naroffab972d32007-11-04 22:37:50 +00003007 // Generate the funky cast.
3008 CastExpr *cast;
3009 llvm::SmallVector<QualType, 8> ArgTypes;
3010 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00003011
Steve Naroffab972d32007-11-04 22:37:50 +00003012 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00003013 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3014 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3015 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003016 ArgTypes.push_back(Context->getObjCIdType());
3017 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00003018 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00003019 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00003020 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3021 E = OMD->param_end(); PI != E; ++PI) {
3022 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00003023 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00003024 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00003025 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003026 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff352336b2007-11-05 14:36:37 +00003027 ArgTypes.push_back(t);
3028 }
Chris Lattner89951a82009-02-20 18:43:26 +00003029 returnType = OMD->getResultType()->isObjCQualifiedIdType()
3030 ? Context->getObjCIdType() : OMD->getResultType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003031 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Naroffab972d32007-11-04 22:37:50 +00003032 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003033 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00003034 }
3035 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00003036 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003037
Steve Naroffab972d32007-11-04 22:37:50 +00003038 // Create a reference to the objc_msgSend() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003039 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003040 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00003041
Mike Stump1eb44332009-09-09 15:08:12 +00003042 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00003043 // If we don't do this cast, we get the following bizarre warning/note:
3044 // xx.m:13: warning: function called through a non-compatible type
3045 // xx.m:13: note: if this code is reached, the program will abort
John McCall9d125032010-01-15 18:39:57 +00003046 cast = NoTypeInfoCStyleCastExpr(Context,
3047 Context->getPointerType(Context->VoidTy),
John McCall2de56d12010-08-25 11:45:40 +00003048 CK_Unknown, DRE);
Mike Stump1eb44332009-09-09 15:08:12 +00003049
Steve Naroffab972d32007-11-04 22:37:50 +00003050 // Now do the "normal" pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00003051 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00003052 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00003053 // If we don't have a method decl, force a variadic cast.
Douglas Gregorce056bc2010-02-21 22:15:06 +00003054 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00003055 false, false, 0, 0,
3056 FunctionType::ExtInfo());
Steve Naroffab972d32007-11-04 22:37:50 +00003057 castType = Context->getPointerType(castType);
John McCall2de56d12010-08-25 11:45:40 +00003058 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_Unknown,
John McCall9d125032010-01-15 18:39:57 +00003059 cast);
Steve Naroffab972d32007-11-04 22:37:50 +00003060
3061 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003062 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003063
John McCall183700f2009-09-21 23:43:11 +00003064 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003065 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003066 MsgExprs.size(),
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003067 FT->getResultType(), EndLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003068 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003069 if (MsgSendStretFlavor) {
3070 // We have the method which returns a struct/union. Must also generate
3071 // call to objc_msgSend_stret and hang both varieties on a conditional
3072 // expression which dictate which one to envoke depending on size of
3073 // method's return type.
Mike Stump1eb44332009-09-09 15:08:12 +00003074
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003075 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003076 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003077 SourceLocation());
3078 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall9d125032010-01-15 18:39:57 +00003079 cast = NoTypeInfoCStyleCastExpr(Context,
3080 Context->getPointerType(Context->VoidTy),
John McCall2de56d12010-08-25 11:45:40 +00003081 CK_Unknown, STDRE);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003082 // Now do the "normal" pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00003083 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00003084 &ArgTypes[0], ArgTypes.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00003085 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00003086 false, false, 0, 0,
3087 FunctionType::ExtInfo());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003088 castType = Context->getPointerType(castType);
John McCall2de56d12010-08-25 11:45:40 +00003089 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_Unknown,
John McCall9d125032010-01-15 18:39:57 +00003090 cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003091
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003092 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003093 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003094
John McCall183700f2009-09-21 23:43:11 +00003095 FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003096 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003097 MsgExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00003098 FT->getResultType(), SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00003099
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003100 // Build sizeof(returnType)
Mike Stump1eb44332009-09-09 15:08:12 +00003101 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCalla93c9342009-12-07 02:54:59 +00003102 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl05189992008-11-11 17:56:53 +00003103 Context->getSizeType(),
3104 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003105 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3106 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3107 // For X86 it is more complicated and some kind of target specific routine
3108 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00003109 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00003110 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00003111 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3112 llvm::APInt(IntSize, 8),
3113 Context->IntTy,
3114 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00003115 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
John McCall2de56d12010-08-25 11:45:40 +00003116 BO_LE,
Mike Stump1eb44332009-09-09 15:08:12 +00003117 Context->IntTy,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003118 SourceLocation());
3119 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00003120 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003121 new (Context) ConditionalOperator(lessThanExpr,
3122 SourceLocation(), CE,
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003123 SourceLocation(), STCE, (Expr*)0,
3124 returnType);
3125 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3126 CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003127 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003128 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003129 return ReplacingStmt;
3130}
3131
Steve Naroffb29b4272008-04-14 22:03:09 +00003132Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003133 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3134 Exp->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00003135
Steve Naroff934f2762007-10-24 22:48:43 +00003136 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00003137 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00003138
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003139 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003140 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00003141}
3142
Steve Naroff621edce2009-04-29 16:37:50 +00003143// typedef struct objc_object Protocol;
3144QualType RewriteObjC::getProtocolType() {
3145 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00003146 TypeSourceInfo *TInfo
3147 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00003148 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00003149 SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00003150 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00003151 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00003152 }
3153 return Context->getTypeDeclType(ProtocolTypeDecl);
3154}
3155
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003156/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00003157/// a synthesized/forward data reference (to the protocol's metadata).
3158/// The forward references (and metadata) are generated in
3159/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00003160Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00003161 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3162 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00003163 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00003164 ID, getProtocolType(), 0,
John McCalld931b082010-08-26 03:08:43 +00003165 SC_Extern, SC_None);
Steve Naroff621edce2009-04-29 16:37:50 +00003166 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00003167 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroff621edce2009-04-29 16:37:50 +00003168 Context->getPointerType(DRE->getType()),
3169 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00003170 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCall2de56d12010-08-25 11:45:40 +00003171 CK_Unknown,
John McCall9d125032010-01-15 18:39:57 +00003172 DerefExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003173 ReplaceStmt(Exp, castExpr);
3174 ProtocolExprDecls.insert(Exp->getProtocol());
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003175 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003176 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003177
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003178}
3179
Mike Stump1eb44332009-09-09 15:08:12 +00003180bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00003181 const char *endBuf) {
3182 while (startBuf < endBuf) {
3183 if (*startBuf == '#') {
3184 // Skip whitespace.
3185 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3186 ;
3187 if (!strncmp(startBuf, "if", strlen("if")) ||
3188 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3189 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3190 !strncmp(startBuf, "define", strlen("define")) ||
3191 !strncmp(startBuf, "undef", strlen("undef")) ||
3192 !strncmp(startBuf, "else", strlen("else")) ||
3193 !strncmp(startBuf, "elif", strlen("elif")) ||
3194 !strncmp(startBuf, "endif", strlen("endif")) ||
3195 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3196 !strncmp(startBuf, "include", strlen("include")) ||
3197 !strncmp(startBuf, "import", strlen("import")) ||
3198 !strncmp(startBuf, "include_next", strlen("include_next")))
3199 return true;
3200 }
3201 startBuf++;
3202 }
3203 return false;
3204}
3205
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003206/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003207/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00003208void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003209 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003210 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar4087f272010-08-17 22:39:59 +00003211 assert(CDecl->getName() != "" &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003212 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003213 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003214 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003215 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003216 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003217 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00003218 SourceLocation LocStart = CDecl->getLocStart();
3219 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00003220
Steve Narofffea763e82007-11-14 19:25:57 +00003221 const char *startBuf = SM->getCharacterData(LocStart);
3222 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00003223
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003224 // If no ivars and no root or if its root, directly or indirectly,
3225 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003226 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
3227 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00003228 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003229 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003230 return;
3231 }
Mike Stump1eb44332009-09-09 15:08:12 +00003232
3233 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003234 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003235 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003236 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00003237 if (LangOpts.Microsoft)
3238 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00003239
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003240 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00003241 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00003242 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003243 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00003244 // If the buffer contains preprocessor directives, we do more fine-grained
3245 // rewrites. This is intended to fix code that looks like (which occurs in
3246 // NSURL.h, for example):
3247 //
3248 // #ifdef XYZ
3249 // @interface Foo : NSObject
3250 // #else
3251 // @interface FooBar : NSObject
3252 // #endif
3253 // {
3254 // int i;
3255 // }
3256 // @end
3257 //
3258 // This clause is segregated to avoid breaking the common case.
3259 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003260 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffbaf58c32008-05-31 14:15:04 +00003261 CDecl->getClassLoc();
3262 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00003263 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003264
Chris Lattnercafeb352009-02-20 18:18:36 +00003265 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00003266 // advance to the end of the referenced protocols.
3267 while (endHeader < cursor && *endHeader != '>') endHeader++;
3268 endHeader++;
3269 }
3270 // rewrite the original header
Benjamin Kramerd999b372010-02-14 14:14:16 +00003271 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003272 } else {
3273 // rewrite the original header *without* disturbing the '{'
Benjamin Kramerd999b372010-02-14 14:14:16 +00003274 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003275 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003276 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00003277 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003278 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003279 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003280 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003281 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003282
Steve Narofffea763e82007-11-14 19:25:57 +00003283 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00003284 SourceLocation OnePastCurly =
3285 LocStart.getFileLocWithOffset(cursor-startBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003286 InsertText(OnePastCurly, Result);
Steve Narofffea763e82007-11-14 19:25:57 +00003287 }
3288 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00003289
Steve Narofffea763e82007-11-14 19:25:57 +00003290 // Now comment out any visibility specifiers.
3291 while (cursor < endBuf) {
3292 if (*cursor == '@') {
3293 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00003294 // Skip whitespace.
3295 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3296 /*scan*/;
3297
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003298 // FIXME: presence of @public, etc. inside comment results in
3299 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00003300 if (!strncmp(cursor, "public", strlen("public")) ||
3301 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00003302 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00003303 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramerd999b372010-02-14 14:14:16 +00003304 InsertText(atLoc, "// ");
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003305 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00003306 // FIXME: If there are cases where '<' is used in ivar declaration part
3307 // of user code, then scan the ivar list and use needToScanForQualifiers
3308 // for type checking.
3309 else if (*cursor == '<') {
3310 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003311 InsertText(atLoc, "/* ");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003312 cursor = strchr(cursor, '>');
3313 cursor++;
3314 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003315 InsertText(atLoc, " */");
Steve Naroffced80a82008-10-30 12:09:33 +00003316 } else if (*cursor == '^') { // rewrite block specifier.
3317 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003318 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003319 }
Steve Narofffea763e82007-11-14 19:25:57 +00003320 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003321 }
Steve Narofffea763e82007-11-14 19:25:57 +00003322 // Don't forget to add a ';'!!
Benjamin Kramerd999b372010-02-14 14:14:16 +00003323 InsertText(LocEnd.getFileLocWithOffset(1), ";");
Steve Narofffea763e82007-11-14 19:25:57 +00003324 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00003325 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00003326 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003327 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003328 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003329 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003330 Result += "_IVARS;\n};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00003331 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003332 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003333 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003334 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00003335 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003336}
3337
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003338// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003339/// class methods.
Douglas Gregor653f1b12009-04-23 01:02:12 +00003340template<typename MethodIterator>
3341void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3342 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00003343 bool IsInstanceMethod,
Daniel Dunbar4087f272010-08-17 22:39:59 +00003344 llvm::StringRef prefix,
3345 llvm::StringRef ClassName,
Chris Lattner158ecb92007-10-25 17:07:24 +00003346 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003347 if (MethodBegin == MethodEnd) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003348
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003349 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003350 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003351 SEL _cmd;
3352 char *method_types;
3353 void *_imp;
3354 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003355 */
Chris Lattner158ecb92007-10-25 17:07:24 +00003356 Result += "\nstruct _objc_method {\n";
3357 Result += "\tSEL _cmd;\n";
3358 Result += "\tchar *method_types;\n";
3359 Result += "\tvoid *_imp;\n";
3360 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003361
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003362 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00003363 }
Mike Stump1eb44332009-09-09 15:08:12 +00003364
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003365 // Build _objc_method_list for class's methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003366
Steve Naroff946a6932008-03-11 00:12:29 +00003367 /* struct {
3368 struct _objc_method_list *next_method;
3369 int method_count;
3370 struct _objc_method method_list[];
3371 }
3372 */
Douglas Gregor653f1b12009-04-23 01:02:12 +00003373 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroff946a6932008-03-11 00:12:29 +00003374 Result += "\nstatic struct {\n";
3375 Result += "\tstruct _objc_method_list *next_method;\n";
3376 Result += "\tint method_count;\n";
3377 Result += "\tstruct _objc_method method_list[";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003378 Result += utostr(NumMethods);
Steve Naroff946a6932008-03-11 00:12:29 +00003379 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003380 Result += prefix;
3381 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3382 Result += "_METHODS_";
3383 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003384 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003385 Result += IsInstanceMethod ? "inst" : "cls";
3386 Result += "_meth\")))= ";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003387 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003388
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003389 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003390 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003391 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003392 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003393 Result += "\", \"";
3394 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003395 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003396 Result += MethodInternalNames[*MethodBegin];
3397 Result += "}\n";
3398 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3399 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003400 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003401 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003402 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003403 Result += "\", \"";
3404 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003405 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003406 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00003407 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003408 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003409 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003410}
3411
Steve Naroff621edce2009-04-29 16:37:50 +00003412/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00003413void RewriteObjC::
Daniel Dunbar4087f272010-08-17 22:39:59 +00003414RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, llvm::StringRef prefix,
3415 llvm::StringRef ClassName, std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003416 static bool objc_protocol_methods = false;
Steve Naroff621edce2009-04-29 16:37:50 +00003417
3418 // Output struct protocol_methods holder of method selector and type.
3419 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3420 /* struct protocol_methods {
3421 SEL _cmd;
3422 char *method_types;
3423 }
3424 */
3425 Result += "\nstruct _protocol_methods {\n";
3426 Result += "\tstruct objc_selector *_cmd;\n";
3427 Result += "\tchar *method_types;\n";
3428 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003429
Steve Naroff621edce2009-04-29 16:37:50 +00003430 objc_protocol_methods = true;
3431 }
3432 // Do not synthesize the protocol more than once.
3433 if (ObjCSynthesizedProtocols.count(PDecl))
3434 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003435
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003436 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3437 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3438 PDecl->instmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003439 /* struct _objc_protocol_method_list {
3440 int protocol_method_count;
3441 struct protocol_methods protocols[];
3442 }
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003443 */
Steve Naroff621edce2009-04-29 16:37:50 +00003444 Result += "\nstatic struct {\n";
3445 Result += "\tint protocol_method_count;\n";
3446 Result += "\tstruct _protocol_methods protocol_methods[";
3447 Result += utostr(NumMethods);
3448 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3449 Result += PDecl->getNameAsString();
3450 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3451 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003452
Steve Naroff621edce2009-04-29 16:37:50 +00003453 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003454 for (ObjCProtocolDecl::instmeth_iterator
3455 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003456 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003457 if (I == PDecl->instmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003458 Result += "\t ,{{(struct objc_selector *)\"";
3459 else
3460 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar4087f272010-08-17 22:39:59 +00003461 Result += (*I)->getSelector().getAsString();
Steve Naroff621edce2009-04-29 16:37:50 +00003462 std::string MethodTypeString;
3463 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3464 Result += "\", \"";
3465 Result += MethodTypeString;
3466 Result += "\"}\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003467 }
Steve Naroff621edce2009-04-29 16:37:50 +00003468 Result += "\t }\n};\n";
3469 }
Mike Stump1eb44332009-09-09 15:08:12 +00003470
Steve Naroff621edce2009-04-29 16:37:50 +00003471 // Output class methods declared in this protocol.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003472 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3473 PDecl->classmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003474 if (NumMethods > 0) {
3475 /* struct _objc_protocol_method_list {
3476 int protocol_method_count;
3477 struct protocol_methods protocols[];
3478 }
3479 */
3480 Result += "\nstatic struct {\n";
3481 Result += "\tint protocol_method_count;\n";
3482 Result += "\tstruct _protocol_methods protocol_methods[";
3483 Result += utostr(NumMethods);
3484 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3485 Result += PDecl->getNameAsString();
3486 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3487 "{\n\t";
3488 Result += utostr(NumMethods);
3489 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003490
Steve Naroff621edce2009-04-29 16:37:50 +00003491 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003492 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003493 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003494 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003495 if (I == PDecl->classmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003496 Result += "\t ,{{(struct objc_selector *)\"";
3497 else
3498 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar4087f272010-08-17 22:39:59 +00003499 Result += (*I)->getSelector().getAsString();
Steve Naroff621edce2009-04-29 16:37:50 +00003500 std::string MethodTypeString;
3501 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3502 Result += "\", \"";
3503 Result += MethodTypeString;
3504 Result += "\"}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003505 }
Steve Naroff621edce2009-04-29 16:37:50 +00003506 Result += "\t }\n};\n";
3507 }
3508
3509 // Output:
3510 /* struct _objc_protocol {
3511 // Objective-C 1.0 extensions
3512 struct _objc_protocol_extension *isa;
3513 char *protocol_name;
3514 struct _objc_protocol **protocol_list;
3515 struct _objc_protocol_method_list *instance_methods;
3516 struct _objc_protocol_method_list *class_methods;
Mike Stump1eb44332009-09-09 15:08:12 +00003517 };
Steve Naroff621edce2009-04-29 16:37:50 +00003518 */
3519 static bool objc_protocol = false;
3520 if (!objc_protocol) {
3521 Result += "\nstruct _objc_protocol {\n";
3522 Result += "\tstruct _objc_protocol_extension *isa;\n";
3523 Result += "\tchar *protocol_name;\n";
3524 Result += "\tstruct _objc_protocol **protocol_list;\n";
3525 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3526 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003527 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003528
Steve Naroff621edce2009-04-29 16:37:50 +00003529 objc_protocol = true;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003530 }
Mike Stump1eb44332009-09-09 15:08:12 +00003531
Steve Naroff621edce2009-04-29 16:37:50 +00003532 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3533 Result += PDecl->getNameAsString();
3534 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3535 "{\n\t0, \"";
3536 Result += PDecl->getNameAsString();
3537 Result += "\", 0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003538 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003539 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3540 Result += PDecl->getNameAsString();
3541 Result += ", ";
3542 }
3543 else
3544 Result += "0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003545 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003546 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3547 Result += PDecl->getNameAsString();
3548 Result += "\n";
3549 }
3550 else
3551 Result += "0\n";
3552 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003553
Steve Naroff621edce2009-04-29 16:37:50 +00003554 // Mark this protocol as having been generated.
3555 if (!ObjCSynthesizedProtocols.insert(PDecl))
3556 assert(false && "protocol already synthesized");
3557
3558}
3559
3560void RewriteObjC::
3561RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
Daniel Dunbar4087f272010-08-17 22:39:59 +00003562 llvm::StringRef prefix, llvm::StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +00003563 std::string &Result) {
3564 if (Protocols.empty()) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003565
Steve Naroff621edce2009-04-29 16:37:50 +00003566 for (unsigned i = 0; i != Protocols.size(); i++)
3567 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3568
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003569 // Output the top lovel protocol meta-data for the class.
3570 /* struct _objc_protocol_list {
3571 struct _objc_protocol_list *next;
3572 int protocol_count;
3573 struct _objc_protocol *class_protocols[];
3574 }
3575 */
3576 Result += "\nstatic struct {\n";
3577 Result += "\tstruct _objc_protocol_list *next;\n";
3578 Result += "\tint protocol_count;\n";
3579 Result += "\tstruct _objc_protocol *class_protocols[";
3580 Result += utostr(Protocols.size());
3581 Result += "];\n} _OBJC_";
3582 Result += prefix;
3583 Result += "_PROTOCOLS_";
3584 Result += ClassName;
3585 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3586 "{\n\t0, ";
3587 Result += utostr(Protocols.size());
3588 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003589
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003590 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003591 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003592 Result += " \n";
Mike Stump1eb44332009-09-09 15:08:12 +00003593
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003594 for (unsigned i = 1; i != Protocols.size(); i++) {
3595 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003596 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003597 Result += "\n";
3598 }
3599 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003600}
3601
Steve Naroff621edce2009-04-29 16:37:50 +00003602
Mike Stump1eb44332009-09-09 15:08:12 +00003603/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003604/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003605void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003606 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003607 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003608 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003609 ObjCCategoryDecl *CDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00003610 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003611 CDecl = CDecl->getNextClassCategory())
3612 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3613 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003614
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003615 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003616 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003617 FullCategoryName += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003618
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003619 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003620 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003621 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003622
3623 // If any of our property implementations have associated getters or
3624 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003625 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3626 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003627 Prop != PropEnd; ++Prop) {
3628 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3629 continue;
3630 if (!(*Prop)->getPropertyIvarDecl())
3631 continue;
3632 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3633 if (!PD)
3634 continue;
3635 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3636 InstanceMethods.push_back(Getter);
3637 if (PD->isReadOnly())
3638 continue;
3639 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3640 InstanceMethods.push_back(Setter);
3641 }
3642 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003643 true, "CATEGORY_", FullCategoryName.c_str(),
3644 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003645
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003646 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003647 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003648 false, "CATEGORY_", FullCategoryName.c_str(),
3649 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003650
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003651 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003652 // Null CDecl is case of a category implementation with no category interface
3653 if (CDecl)
Steve Naroff621edce2009-04-29 16:37:50 +00003654 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Daniel Dunbar4087f272010-08-17 22:39:59 +00003655 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003656 /* struct _objc_category {
3657 char *category_name;
3658 char *class_name;
3659 struct _objc_method_list *instance_methods;
3660 struct _objc_method_list *class_methods;
3661 struct _objc_protocol_list *protocols;
3662 // Objective-C 1.0 extensions
3663 uint32_t size; // sizeof (struct _objc_category)
Mike Stump1eb44332009-09-09 15:08:12 +00003664 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003665 // @property decl.
Mike Stump1eb44332009-09-09 15:08:12 +00003666 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003667 */
Mike Stump1eb44332009-09-09 15:08:12 +00003668
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003669 static bool objc_category = false;
3670 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003671 Result += "\nstruct _objc_category {\n";
3672 Result += "\tchar *category_name;\n";
3673 Result += "\tchar *class_name;\n";
3674 Result += "\tstruct _objc_method_list *instance_methods;\n";
3675 Result += "\tstruct _objc_method_list *class_methods;\n";
3676 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003677 Result += "\tunsigned int size;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003678 Result += "\tstruct _objc_property_list *instance_properties;\n";
3679 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003680 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003681 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003682 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3683 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003684 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003685 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003686 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003687 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003688 Result += "\"\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003689
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003690 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003691 Result += "\t, (struct _objc_method_list *)"
3692 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3693 Result += FullCategoryName;
3694 Result += "\n";
3695 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003696 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003697 Result += "\t, 0\n";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003698 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003699 Result += "\t, (struct _objc_method_list *)"
3700 "&_OBJC_CATEGORY_CLASS_METHODS_";
3701 Result += FullCategoryName;
3702 Result += "\n";
3703 }
3704 else
3705 Result += "\t, 0\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003706
Chris Lattnercafeb352009-02-20 18:18:36 +00003707 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003708 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003709 Result += FullCategoryName;
3710 Result += "\n";
3711 }
3712 else
3713 Result += "\t, 0\n";
3714 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003715}
3716
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003717/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3718/// ivar offset.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003719void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003720 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003721 if (ivar->isBitField()) {
3722 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3723 // place all bitfields at offset 0.
3724 Result += "0";
3725 } else {
3726 Result += "__OFFSETOFIVAR__(struct ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003727 Result += ivar->getContainingInterface()->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003728 if (LangOpts.Microsoft)
3729 Result += "_IMPL";
3730 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003731 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003732 Result += ")";
3733 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003734}
3735
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003736//===----------------------------------------------------------------------===//
3737// Meta Data Emission
3738//===----------------------------------------------------------------------===//
3739
Steve Naroffb29b4272008-04-14 22:03:09 +00003740void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003741 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003742 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00003743
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003744 // Explictly declared @interface's are already synthesized.
Steve Naroff33feeb02009-04-20 20:09:33 +00003745 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003746 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003747 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003748 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003749 }
Mike Stump1eb44332009-09-09 15:08:12 +00003750
Chris Lattnerbe6df082007-12-12 07:56:42 +00003751 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003752 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump1eb44332009-09-09 15:08:12 +00003753 ? IDecl->ivar_size()
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003754 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003755 if (NumIvars > 0) {
3756 static bool objc_ivar = false;
3757 if (!objc_ivar) {
3758 /* struct _objc_ivar {
3759 char *ivar_name;
3760 char *ivar_type;
3761 int ivar_offset;
Mike Stump1eb44332009-09-09 15:08:12 +00003762 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003763 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003764 Result += "\nstruct _objc_ivar {\n";
3765 Result += "\tchar *ivar_name;\n";
3766 Result += "\tchar *ivar_type;\n";
3767 Result += "\tint ivar_offset;\n";
3768 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003769
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003770 objc_ivar = true;
3771 }
3772
Steve Naroff946a6932008-03-11 00:12:29 +00003773 /* struct {
3774 int ivar_count;
3775 struct _objc_ivar ivar_list[nIvars];
Mike Stump1eb44332009-09-09 15:08:12 +00003776 };
Steve Naroff946a6932008-03-11 00:12:29 +00003777 */
Mike Stump1eb44332009-09-09 15:08:12 +00003778 Result += "\nstatic struct {\n";
Steve Naroff946a6932008-03-11 00:12:29 +00003779 Result += "\tint ivar_count;\n";
3780 Result += "\tstruct _objc_ivar ivar_list[";
3781 Result += utostr(NumIvars);
3782 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003783 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003784 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003785 "{\n\t";
3786 Result += utostr(NumIvars);
3787 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003788
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003789 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003790 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003791 if (!IDecl->ivar_empty()) {
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003792 for (ObjCInterfaceDecl::ivar_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003793 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003794 IV != IVEnd; ++IV)
3795 IVars.push_back(*IV);
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003796 IVI = IDecl->ivar_begin();
3797 IVE = IDecl->ivar_end();
Chris Lattnerbe6df082007-12-12 07:56:42 +00003798 } else {
3799 IVI = CDecl->ivar_begin();
3800 IVE = CDecl->ivar_end();
3801 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003802 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003803 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003804 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003805 std::string TmpString, StrEncoding;
3806 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3807 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003808 Result += StrEncoding;
3809 Result += "\", ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003810 SynthesizeIvarOffsetComputation(*IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003811 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003812 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003813 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003814 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003815 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003816 std::string TmpString, StrEncoding;
3817 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3818 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003819 Result += StrEncoding;
3820 Result += "\", ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003821 SynthesizeIvarOffsetComputation((*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003822 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003823 }
Mike Stump1eb44332009-09-09 15:08:12 +00003824
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003825 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003826 }
Mike Stump1eb44332009-09-09 15:08:12 +00003827
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003828 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003829 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003830 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003831
3832 // If any of our property implementations have associated getters or
3833 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003834 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3835 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003836 Prop != PropEnd; ++Prop) {
3837 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3838 continue;
3839 if (!(*Prop)->getPropertyIvarDecl())
3840 continue;
3841 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3842 if (!PD)
3843 continue;
3844 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanianec3683b2010-10-19 23:47:54 +00003845 if (!Getter->isDefined())
3846 InstanceMethods.push_back(Getter);
Douglas Gregor653f1b12009-04-23 01:02:12 +00003847 if (PD->isReadOnly())
3848 continue;
3849 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanianec3683b2010-10-19 23:47:54 +00003850 if (!Setter->isDefined())
3851 InstanceMethods.push_back(Setter);
Douglas Gregor653f1b12009-04-23 01:02:12 +00003852 }
3853 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003854 true, "", IDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003855
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003856 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003857 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003858 false, "", IDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003859
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003860 // Protocols referenced in class declaration?
Steve Naroff621edce2009-04-29 16:37:50 +00003861 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003862 "CLASS", CDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003863
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003864 // Declaration of class/meta-class metadata
3865 /* struct _objc_class {
3866 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003867 const char *super_class_name;
3868 char *name;
3869 long version;
3870 long info;
3871 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003872 struct _objc_ivar_list *ivars;
3873 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003874 struct objc_cache *cache;
3875 struct objc_protocol_list *protocols;
3876 const char *ivar_layout;
3877 struct _objc_class_ext *ext;
Mike Stump1eb44332009-09-09 15:08:12 +00003878 };
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003879 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003880 static bool objc_class = false;
3881 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003882 Result += "\nstruct _objc_class {\n";
3883 Result += "\tstruct _objc_class *isa;\n";
3884 Result += "\tconst char *super_class_name;\n";
3885 Result += "\tchar *name;\n";
3886 Result += "\tlong version;\n";
3887 Result += "\tlong info;\n";
3888 Result += "\tlong instance_size;\n";
3889 Result += "\tstruct _objc_ivar_list *ivars;\n";
3890 Result += "\tstruct _objc_method_list *methods;\n";
3891 Result += "\tstruct objc_cache *cache;\n";
3892 Result += "\tstruct _objc_protocol_list *protocols;\n";
3893 Result += "\tconst char *ivar_layout;\n";
3894 Result += "\tstruct _objc_class_ext *ext;\n";
3895 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003896 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003897 }
Mike Stump1eb44332009-09-09 15:08:12 +00003898
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003899 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003900 ObjCInterfaceDecl *RootClass = 0;
3901 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003902 while (SuperClass) {
3903 RootClass = SuperClass;
3904 SuperClass = SuperClass->getSuperClass();
3905 }
3906 SuperClass = CDecl->getSuperClass();
Mike Stump1eb44332009-09-09 15:08:12 +00003907
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003908 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003909 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003910 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003911 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003912 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003913 Result += "\"";
3914
3915 if (SuperClass) {
3916 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003917 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003918 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003919 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003920 Result += "\"";
3921 }
3922 else {
3923 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003924 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003925 Result += "\"";
3926 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003927 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003928 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003929 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003930 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff23f41272008-03-11 18:14:26 +00003931 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003932 Result += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003933 Result += "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003934 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003935 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003936 Result += ", 0\n";
Chris Lattnercafeb352009-02-20 18:18:36 +00003937 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003938 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003939 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003940 Result += ",0,0\n";
3941 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003942 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003943 Result += "\t,0,0,0,0\n";
3944 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003945
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003946 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003947 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003948 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003949 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003950 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003951 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003952 if (SuperClass) {
3953 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003954 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003955 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003956 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003957 Result += "\"";
3958 }
3959 else {
3960 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003961 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003962 Result += "\"";
3963 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003964 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003965 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003966 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003967 Result += ",0";
3968 else {
3969 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003970 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003971 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003972 if (LangOpts.Microsoft)
3973 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003974 Result += ")";
3975 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003976 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003977 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003978 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003979 Result += "\n\t";
3980 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003981 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003982 Result += ",0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003983 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroff946a6932008-03-11 00:12:29 +00003984 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003985 Result += CDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003986 Result += ", 0\n\t";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003987 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003988 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003989 Result += ",0,0";
Chris Lattnercafeb352009-02-20 18:18:36 +00003990 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003991 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003992 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003993 Result += ", 0,0\n";
3994 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003995 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003996 Result += ",0,0,0\n";
3997 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003998}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003999
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00004000/// RewriteImplementations - This routine rewrites all method implementations
4001/// and emits meta-data.
4002
Steve Narofface66252008-11-13 20:07:04 +00004003void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004004 int ClsDefCount = ClassImplementation.size();
4005 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00004006
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00004007 // Rewrite implemented methods
4008 for (int i = 0; i < ClsDefCount; i++)
4009 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00004010
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00004011 for (int i = 0; i < CatDefCount; i++)
4012 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00004013}
Mike Stump1eb44332009-09-09 15:08:12 +00004014
Steve Narofface66252008-11-13 20:07:04 +00004015void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
4016 int ClsDefCount = ClassImplementation.size();
4017 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00004018
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00004019 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00004020 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004021 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump1eb44332009-09-09 15:08:12 +00004022
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00004023 // For each implemented category, write out all its meta data.
4024 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004025 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroff621edce2009-04-29 16:37:50 +00004026
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004027 // Write objc_symtab metadata
4028 /*
4029 struct _objc_symtab
4030 {
4031 long sel_ref_cnt;
4032 SEL *refs;
4033 short cls_def_cnt;
4034 short cat_def_cnt;
4035 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump1eb44332009-09-09 15:08:12 +00004036 };
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004037 */
Mike Stump1eb44332009-09-09 15:08:12 +00004038
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004039 Result += "\nstruct _objc_symtab {\n";
4040 Result += "\tlong sel_ref_cnt;\n";
4041 Result += "\tSEL *refs;\n";
4042 Result += "\tshort cls_def_cnt;\n";
4043 Result += "\tshort cat_def_cnt;\n";
4044 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
4045 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004046
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004047 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00004048 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004049 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004050 + ", " + utostr(CatDefCount) + "\n";
4051 for (int i = 0; i < ClsDefCount; i++) {
4052 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004053 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004054 Result += "\n";
4055 }
Mike Stump1eb44332009-09-09 15:08:12 +00004056
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004057 for (int i = 0; i < CatDefCount; i++) {
4058 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004059 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004060 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004061 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004062 Result += "\n";
4063 }
Mike Stump1eb44332009-09-09 15:08:12 +00004064
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004065 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004066
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004067 // Write objc_module metadata
Mike Stump1eb44332009-09-09 15:08:12 +00004068
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004069 /*
4070 struct _objc_module {
4071 long version;
4072 long size;
4073 const char *name;
4074 struct _objc_symtab *symtab;
4075 }
4076 */
Mike Stump1eb44332009-09-09 15:08:12 +00004077
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004078 Result += "\nstruct _objc_module {\n";
4079 Result += "\tlong version;\n";
4080 Result += "\tlong size;\n";
4081 Result += "\tconst char *name;\n";
4082 Result += "\tstruct _objc_symtab *symtab;\n";
4083 Result += "};\n\n";
4084 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00004085 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004086 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00004087 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004088 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004089
4090 if (LangOpts.Microsoft) {
Steve Naroff621edce2009-04-29 16:37:50 +00004091 if (ProtocolExprDecls.size()) {
4092 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
4093 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004094 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00004095 E = ProtocolExprDecls.end(); I != E; ++I) {
4096 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
4097 Result += (*I)->getNameAsString();
4098 Result += " = &_OBJC_PROTOCOL_";
4099 Result += (*I)->getNameAsString();
4100 Result += ";\n";
4101 }
4102 Result += "#pragma data_seg(pop)\n\n";
4103 }
Steve Naroff4f943c22008-03-10 20:43:59 +00004104 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00004105 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004106 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
4107 Result += "&_OBJC_MODULES;\n";
4108 Result += "#pragma data_seg(pop)\n\n";
4109 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004110}
Chris Lattner311ff022007-10-16 22:36:42 +00004111
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004112void RewriteObjC::RewriteByRefString(std::string &ResultStr,
4113 const std::string &Name,
4114 ValueDecl *VD) {
4115 assert(BlockByRefDeclNo.count(VD) &&
4116 "RewriteByRefString: ByRef decl missing");
4117 ResultStr += "struct __Block_byref_" + Name +
4118 "_" + utostr(BlockByRefDeclNo[VD]) ;
4119}
4120
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004121static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4122 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4123 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4124 return false;
4125}
4126
Steve Naroff54055232008-10-27 17:20:55 +00004127std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Daniel Dunbar4087f272010-08-17 22:39:59 +00004128 llvm::StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00004129 std::string Tag) {
4130 const FunctionType *AFT = CE->getFunctionType();
4131 QualType RT = AFT->getResultType();
4132 std::string StructRef = "struct " + Tag;
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00004133 std::string S = "static " + RT.getAsString(Context->PrintingPolicy) + " __" +
Daniel Dunbar4087f272010-08-17 22:39:59 +00004134 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00004135
Steve Naroff54055232008-10-27 17:20:55 +00004136 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00004137
Douglas Gregor72564e72009-02-26 23:50:07 +00004138 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004139 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00004140 // block (to reference imported block decl refs).
4141 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00004142 } else if (BD->param_empty()) {
4143 S += "(" + StructRef + " *__cself)";
4144 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00004145 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00004146 assert(FT && "SynthesizeBlockFunc: No function proto");
4147 S += '(';
4148 // first add the implicit argument.
4149 S += StructRef + " *__cself, ";
4150 std::string ParamStr;
4151 for (BlockDecl::param_iterator AI = BD->param_begin(),
4152 E = BD->param_end(); AI != E; ++AI) {
4153 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004154 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004155 QualType QT = (*AI)->getType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004156 if (convertBlockPointerToFunctionPointer(QT))
4157 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004158 else
4159 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00004160 S += ParamStr;
4161 }
4162 if (FT->isVariadic()) {
4163 if (!BD->param_empty()) S += ", ";
4164 S += "...";
4165 }
4166 S += ')';
4167 }
4168 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004169
Steve Naroff54055232008-10-27 17:20:55 +00004170 // Create local declarations to avoid rewriting all closure decl ref exprs.
4171 // First, emit a declaration for all "by ref" decls.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004172 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004173 E = BlockByRefDecls.end(); I != E; ++I) {
4174 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004175 std::string Name = (*I)->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004176 std::string TypeString;
4177 RewriteByRefString(TypeString, Name, (*I));
4178 TypeString += " *";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004179 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004180 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004181 }
Steve Naroff54055232008-10-27 17:20:55 +00004182 // Next, emit a declaration for all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004183 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004184 E = BlockByCopyDecls.end(); I != E; ++I) {
4185 S += " ";
Steve Naroff54055232008-10-27 17:20:55 +00004186 // Handle nested closure invocation. For example:
4187 //
4188 // void (^myImportedClosure)(void);
4189 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004190 //
Steve Naroff54055232008-10-27 17:20:55 +00004191 // void (^anotherClosure)(void);
4192 // anotherClosure = ^(void) {
4193 // myImportedClosure(); // import and invoke the closure
4194 // };
4195 //
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004196 if (isTopLevelBlockPointerType((*I)->getType())) {
4197 RewriteBlockPointerTypeVariable(S, (*I));
4198 S += " = (";
4199 RewriteBlockPointerType(S, (*I)->getType());
4200 S += ")";
4201 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4202 }
4203 else {
Fariborz Jahanian210c2482010-02-16 17:26:03 +00004204 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004205 QualType QT = (*I)->getType();
4206 if (HasLocalVariableExternalStorage(*I))
4207 QT = Context->getPointerType(QT);
4208 QT.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004209 S += Name + " = __cself->" +
4210 (*I)->getNameAsString() + "; // bound by copy\n";
4211 }
Steve Naroff54055232008-10-27 17:20:55 +00004212 }
4213 std::string RewrittenStr = RewrittenBlockExprs[CE];
4214 const char *cstr = RewrittenStr.c_str();
4215 while (*cstr++ != '{') ;
4216 S += cstr;
4217 S += "\n";
4218 return S;
4219}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00004220
Steve Naroff54055232008-10-27 17:20:55 +00004221std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Daniel Dunbar4087f272010-08-17 22:39:59 +00004222 llvm::StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00004223 std::string Tag) {
4224 std::string StructRef = "struct " + Tag;
4225 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00004226
Steve Naroff54055232008-10-27 17:20:55 +00004227 S += funcName;
4228 S += "_block_copy_" + utostr(i);
4229 S += "(" + StructRef;
4230 S += "*dst, " + StructRef;
4231 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004232 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004233 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00004234 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004235 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00004236 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004237 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004238 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004239 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004240 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004241 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004242 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004243 S += "}\n";
4244
Steve Naroff54055232008-10-27 17:20:55 +00004245 S += "\nstatic void __";
4246 S += funcName;
4247 S += "_block_dispose_" + utostr(i);
4248 S += "(" + StructRef;
4249 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004250 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004251 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00004252 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004253 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004254 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004255 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004256 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004257 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004258 }
Mike Stump1eb44332009-09-09 15:08:12 +00004259 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00004260 return S;
4261}
4262
Steve Naroff01aec112009-12-06 21:14:13 +00004263std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4264 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00004265 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00004266 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00004267
Steve Naroff54055232008-10-27 17:20:55 +00004268 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004269 S += " struct " + Desc;
4270 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004271
Steve Naroff01aec112009-12-06 21:14:13 +00004272 Constructor += "(void *fp, "; // Invoke function pointer.
4273 Constructor += "struct " + Desc; // Descriptor pointer.
4274 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00004275
Steve Naroff54055232008-10-27 17:20:55 +00004276 if (BlockDeclRefs.size()) {
4277 // Output all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004278 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004279 E = BlockByCopyDecls.end(); I != E; ++I) {
4280 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004281 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004282 std::string ArgName = "_" + FieldName;
4283 // Handle nested closure invocation. For example:
4284 //
4285 // void (^myImportedBlock)(void);
4286 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004287 //
Steve Naroff54055232008-10-27 17:20:55 +00004288 // void (^anotherBlock)(void);
4289 // anotherBlock = ^(void) {
4290 // myImportedBlock(); // import and invoke the closure
4291 // };
4292 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004293 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00004294 S += "struct __block_impl *";
4295 Constructor += ", void *" + ArgName;
4296 } else {
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004297 QualType QT = (*I)->getType();
4298 if (HasLocalVariableExternalStorage(*I))
4299 QT = Context->getPointerType(QT);
4300 QT.getAsStringInternal(FieldName, Context->PrintingPolicy);
4301 QT.getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00004302 Constructor += ", " + ArgName;
4303 }
4304 S += FieldName + ";\n";
4305 }
4306 // Output all "by ref" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004307 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004308 E = BlockByRefDecls.end(); I != E; ++I) {
4309 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004310 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004311 std::string ArgName = "_" + FieldName;
4312 // Handle nested closure invocation. For example:
4313 //
4314 // void (^myImportedBlock)(void);
4315 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004316 //
Steve Naroff54055232008-10-27 17:20:55 +00004317 // void (^anotherBlock)(void);
4318 // anotherBlock = ^(void) {
4319 // myImportedBlock(); // import and invoke the closure
4320 // };
4321 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004322 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00004323 S += "struct __block_impl *";
4324 Constructor += ", void *" + ArgName;
4325 } else {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004326 std::string TypeString;
4327 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004328 TypeString += " *";
4329 FieldName = TypeString + FieldName;
4330 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00004331 Constructor += ", " + ArgName;
4332 }
4333 S += FieldName + "; // by ref\n";
4334 }
4335 // Finish writing the constructor.
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004336 Constructor += ", int flags=0)";
4337 // Initialize all "by copy" arguments.
4338 bool firsTime = true;
4339 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4340 E = BlockByCopyDecls.end(); I != E; ++I) {
4341 std::string Name = (*I)->getNameAsString();
4342 if (firsTime) {
4343 Constructor += " : ";
4344 firsTime = false;
4345 }
4346 else
4347 Constructor += ", ";
4348 if (isTopLevelBlockPointerType((*I)->getType()))
4349 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4350 else
4351 Constructor += Name + "(_" + Name + ")";
4352 }
4353 // Initialize all "by ref" arguments.
4354 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4355 E = BlockByRefDecls.end(); I != E; ++I) {
4356 std::string Name = (*I)->getNameAsString();
4357 if (firsTime) {
4358 Constructor += " : ";
4359 firsTime = false;
4360 }
4361 else
4362 Constructor += ", ";
4363 if (isTopLevelBlockPointerType((*I)->getType()))
4364 Constructor += Name + "((struct __block_impl *)_"
4365 + Name + "->__forwarding)";
4366 else
4367 Constructor += Name + "(_" + Name + "->__forwarding)";
4368 }
4369
4370 Constructor += " {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004371 if (GlobalVarDecl)
4372 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4373 else
4374 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004375 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004376
Steve Naroff01aec112009-12-06 21:14:13 +00004377 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004378 } else {
4379 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00004380 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004381 if (GlobalVarDecl)
4382 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4383 else
4384 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004385 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4386 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004387 }
4388 Constructor += " ";
4389 Constructor += "}\n";
4390 S += Constructor;
4391 S += "};\n";
4392 return S;
4393}
4394
Steve Naroff01aec112009-12-06 21:14:13 +00004395std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4396 std::string ImplTag, int i,
Daniel Dunbar4087f272010-08-17 22:39:59 +00004397 llvm::StringRef FunName,
Steve Naroff01aec112009-12-06 21:14:13 +00004398 unsigned hasCopy) {
4399 std::string S = "\nstatic struct " + DescTag;
4400
4401 S += " {\n unsigned long reserved;\n";
4402 S += " unsigned long Block_size;\n";
4403 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004404 S += " void (*copy)(struct ";
4405 S += ImplTag; S += "*, struct ";
4406 S += ImplTag; S += "*);\n";
4407
4408 S += " void (*dispose)(struct ";
4409 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004410 }
4411 S += "} ";
4412
4413 S += DescTag + "_DATA = { 0, sizeof(struct ";
4414 S += ImplTag + ")";
4415 if (hasCopy) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00004416 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4417 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff01aec112009-12-06 21:14:13 +00004418 }
4419 S += "};\n";
4420 return S;
4421}
4422
Steve Naroff54055232008-10-27 17:20:55 +00004423void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Daniel Dunbar4087f272010-08-17 22:39:59 +00004424 llvm::StringRef FunName) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004425 // Insert declaration for the function in which block literal is used.
Fariborz Jahanianbf070122010-01-15 18:14:52 +00004426 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004427 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004428 bool RewriteSC = (GlobalVarDecl &&
4429 !Blocks.empty() &&
John McCalld931b082010-08-26 03:08:43 +00004430 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004431 GlobalVarDecl->getType().getCVRQualifiers());
4432 if (RewriteSC) {
4433 std::string SC(" void __");
4434 SC += GlobalVarDecl->getNameAsString();
4435 SC += "() {}";
4436 InsertText(FunLocStart, SC);
4437 }
4438
Steve Naroff54055232008-10-27 17:20:55 +00004439 // Insert closures that were part of the function.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004440 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4441 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004442 // Need to copy-in the inner copied-in variables not actually used in this
4443 // block.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004444 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4445 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
4446 ValueDecl *VD = Exp->getDecl();
4447 BlockDeclRefs.push_back(Exp);
4448 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
4449 BlockByCopyDeclsPtrSet.insert(VD);
4450 BlockByCopyDecls.push_back(VD);
4451 }
4452 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4453 BlockByRefDeclsPtrSet.insert(VD);
4454 BlockByRefDecls.push_back(VD);
4455 }
Fariborz Jahanian92c85682010-10-05 18:05:06 +00004456 // imported objects in the inner blocks not used in the outer
4457 // blocks must be copied/disposed in the outer block as well.
4458 if (Exp->isByRef() ||
4459 VD->getType()->isObjCObjectPointerType() ||
4460 VD->getType()->isBlockPointerType())
4461 ImportedBlockDecls.insert(VD);
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004462 }
Steve Naroff54055232008-10-27 17:20:55 +00004463
Daniel Dunbar4087f272010-08-17 22:39:59 +00004464 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4465 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00004466
Steve Naroff01aec112009-12-06 21:14:13 +00004467 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00004468
Benjamin Kramerd999b372010-02-14 14:14:16 +00004469 InsertText(FunLocStart, CI);
Steve Naroff54055232008-10-27 17:20:55 +00004470
Steve Naroff01aec112009-12-06 21:14:13 +00004471 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00004472
Benjamin Kramerd999b372010-02-14 14:14:16 +00004473 InsertText(FunLocStart, CF);
Steve Naroff54055232008-10-27 17:20:55 +00004474
4475 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00004476 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004477 InsertText(FunLocStart, HF);
Steve Naroff54055232008-10-27 17:20:55 +00004478 }
Steve Naroff01aec112009-12-06 21:14:13 +00004479 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4480 ImportedBlockDecls.size() > 0);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004481 InsertText(FunLocStart, BD);
Mike Stump1eb44332009-09-09 15:08:12 +00004482
Steve Naroff54055232008-10-27 17:20:55 +00004483 BlockDeclRefs.clear();
4484 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004485 BlockByRefDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004486 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004487 BlockByCopyDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004488 ImportedBlockDecls.clear();
4489 }
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004490 if (RewriteSC) {
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004491 // Must insert any 'const/volatile/static here. Since it has been
4492 // removed as result of rewriting of block literals.
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004493 std::string SC;
John McCalld931b082010-08-26 03:08:43 +00004494 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004495 SC = "static ";
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004496 if (GlobalVarDecl->getType().isConstQualified())
4497 SC += "const ";
4498 if (GlobalVarDecl->getType().isVolatileQualified())
4499 SC += "volatile ";
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004500 if (GlobalVarDecl->getType().isRestrictQualified())
4501 SC += "restrict ";
4502 InsertText(FunLocStart, SC);
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004503 }
4504
Steve Naroff54055232008-10-27 17:20:55 +00004505 Blocks.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004506 InnerDeclRefsCount.clear();
4507 InnerDeclRefs.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004508 RewrittenBlockExprs.clear();
4509}
4510
4511void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4512 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Daniel Dunbar4087f272010-08-17 22:39:59 +00004513 llvm::StringRef FuncName = FD->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00004514
Steve Naroff54055232008-10-27 17:20:55 +00004515 SynthesizeBlockLiterals(FunLocStart, FuncName);
4516}
4517
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004518static void BuildUniqueMethodName(std::string &Name,
4519 ObjCMethodDecl *MD) {
4520 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar4087f272010-08-17 22:39:59 +00004521 Name = IFace->getName();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004522 Name += "__" + MD->getSelector().getAsString();
4523 // Convert colons to underscores.
4524 std::string::size_type loc = 0;
4525 while ((loc = Name.find(":", loc)) != std::string::npos)
4526 Name.replace(loc, 1, "_");
4527}
4528
Steve Naroff54055232008-10-27 17:20:55 +00004529void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00004530 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4531 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanian0e1c99a2010-01-29 01:55:49 +00004532 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004533 std::string FuncName;
4534 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar4087f272010-08-17 22:39:59 +00004535 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff54055232008-10-27 17:20:55 +00004536}
4537
4538void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4539 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4540 CI != E; ++CI)
4541 if (*CI) {
4542 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4543 GetBlockDeclRefExprs(CBE->getBody());
4544 else
4545 GetBlockDeclRefExprs(*CI);
4546 }
4547 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004548 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Steve Naroff54055232008-10-27 17:20:55 +00004549 // FIXME: Handle enums.
4550 if (!isa<FunctionDecl>(CDRE->getDecl()))
4551 BlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004552 }
4553 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4554 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
4555 BlockDeclRefExpr *BDRE =
4556 new (Context)BlockDeclRefExpr(DRE->getDecl(), DRE->getType(),
4557 DRE->getLocation(), false);
4558 BlockDeclRefs.push_back(BDRE);
4559 }
4560
Steve Naroff54055232008-10-27 17:20:55 +00004561 return;
4562}
4563
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004564void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4565 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004566 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004567 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4568 CI != E; ++CI)
4569 if (*CI) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004570 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4571 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004572 GetInnerBlockDeclRefExprs(CBE->getBody(),
4573 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004574 InnerContexts);
4575 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004576 else
4577 GetInnerBlockDeclRefExprs(*CI,
4578 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004579 InnerContexts);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004580
4581 }
4582 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004583 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004584 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004585 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004586 InnerBlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004587 }
4588 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4589 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4590 if (Var->isFunctionOrMethodVarDecl())
4591 ImportedLocalExternalDecls.insert(Var);
4592 }
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004593
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004594 return;
4595}
4596
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004597/// convertFunctionTypeOfBlocks - This routine converts a function type
4598/// whose result type may be a block pointer or whose argument type(s)
4599/// might be block pointers to an equivalent funtion type replacing
4600/// all block pointers to function pointers.
4601QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4602 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4603 // FTP will be null for closures that don't take arguments.
4604 // Generate a funky cast.
4605 llvm::SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004606 QualType Res = FT->getResultType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004607 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004608
4609 if (FTP) {
4610 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4611 E = FTP->arg_type_end(); I && (I != E); ++I) {
4612 QualType t = *I;
4613 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004614 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004615 HasBlockType = true;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004616 ArgTypes.push_back(t);
4617 }
4618 }
4619 QualType FuncType;
4620 // FIXME. Does this work if block takes no argument but has a return type
4621 // which is of block type?
4622 if (HasBlockType)
4623 FuncType = Context->getFunctionType(Res,
4624 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0,
4625 false, false, 0, 0, FunctionType::ExtInfo());
4626 else FuncType = QualType(FT, 0);
4627 return FuncType;
4628}
4629
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004630Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00004631 // Navigate to relevant type information.
Steve Naroff54055232008-10-27 17:20:55 +00004632 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004633
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004634 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004635 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004636 } else if (const BlockDeclRefExpr *CDRE =
4637 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004638 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004639 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004640 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004641 }
4642 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4643 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4644 }
4645 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4646 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4647 else if (const ConditionalOperator *CEXPR =
4648 dyn_cast<ConditionalOperator>(BlockExp)) {
4649 Expr *LHSExp = CEXPR->getLHS();
4650 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4651 Expr *RHSExp = CEXPR->getRHS();
4652 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4653 Expr *CONDExp = CEXPR->getCond();
4654 ConditionalOperator *CondExpr =
4655 new (Context) ConditionalOperator(CONDExp,
4656 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00004657 SourceLocation(), cast<Expr>(RHSStmt),
4658 (Expr*)0,
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004659 Exp->getType());
4660 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00004661 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4662 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004663 } else {
4664 assert(1 && "RewriteBlockClass: Bad type");
4665 }
4666 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00004667 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00004668 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00004669 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00004670 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004671
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004672 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004673 SourceLocation(),
4674 &Context->Idents.get("__block_impl"));
4675 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00004676
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004677 // Generate a funky cast.
4678 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004679
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004680 // Push the block argument type.
4681 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00004682 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004683 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004684 E = FTP->arg_type_end(); I && (I != E); ++I) {
4685 QualType t = *I;
4686 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004687 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004688 ArgTypes.push_back(t);
4689 }
Steve Naroff54055232008-10-27 17:20:55 +00004690 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004691 // Now do the pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00004692 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00004693 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0,
4694 false, false, 0, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00004695 FunctionType::ExtInfo());
Mike Stump1eb44332009-09-09 15:08:12 +00004696
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004697 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00004698
John McCall9d125032010-01-15 18:39:57 +00004699 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCall2de56d12010-08-25 11:45:40 +00004700 CK_Unknown,
John McCall9d125032010-01-15 18:39:57 +00004701 const_cast<Expr*>(BlockExp));
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004702 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004703 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4704 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004705 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00004706
Douglas Gregor44b43212008-12-11 16:49:14 +00004707 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00004708 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004709 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004710 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4711 FD->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00004712
John McCall9d125032010-01-15 18:39:57 +00004713 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
John McCall2de56d12010-08-25 11:45:40 +00004714 CK_Unknown, ME);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004715 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00004716
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004717 llvm::SmallVector<Expr*, 8> BlkExprs;
4718 // Add the implicit argument.
4719 BlkExprs.push_back(BlkCast);
4720 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004721 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004722 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004723 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00004724 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004725 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4726 BlkExprs.size(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00004727 Exp->getType(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004728 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00004729}
4730
Steve Naroff621edce2009-04-29 16:37:50 +00004731// We need to return the rewritten expression to handle cases where the
4732// BlockDeclRefExpr is embedded in another expression being rewritten.
4733// For example:
4734//
4735// int main() {
4736// __block Foo *f;
4737// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00004738//
Steve Naroff621edce2009-04-29 16:37:50 +00004739// void (^myblock)() = ^() {
4740// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4741// i = 77;
4742// };
4743//}
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004744Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00004745 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004746 // for each DeclRefExp where BYREFVAR is name of the variable.
4747 ValueDecl *VD;
4748 bool isArrow = true;
4749 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4750 VD = BDRE->getDecl();
4751 else {
4752 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4753 isArrow = false;
4754 }
4755
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004756 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4757 &Context->Idents.get("__forwarding"),
4758 Context->VoidPtrTy, 0,
4759 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004760 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4761 FD, SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004762 FD->getType());
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004763
Daniel Dunbar4087f272010-08-17 22:39:59 +00004764 llvm::StringRef Name = VD->getName();
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004765 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4766 &Context->Idents.get(Name),
4767 Context->VoidPtrTy, 0,
4768 /*BitWidth=*/0, /*Mutable=*/true);
4769 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004770 DeclRefExp->getType());
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004771
4772
4773
Steve Naroffdf8570d2009-02-02 17:19:26 +00004774 // Need parens to enforce precedence.
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004775 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4776 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004777 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00004778 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00004779}
4780
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004781// Rewrites the imported local variable V with external storage
4782// (static, extern, etc.) as *V
4783//
4784Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4785 ValueDecl *VD = DRE->getDecl();
4786 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4787 if (!ImportedLocalExternalDecls.count(Var))
4788 return DRE;
John McCall2de56d12010-08-25 11:45:40 +00004789 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref,
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004790 DRE->getType(), DRE->getLocation());
4791 // Need parens to enforce precedence.
4792 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4793 Exp);
4794 ReplaceStmt(DRE, PE);
4795 return PE;
4796}
4797
Steve Naroffb2f9e512008-11-03 23:29:32 +00004798void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4799 SourceLocation LocStart = CE->getLParenLoc();
4800 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00004801
4802 // Need to avoid trying to rewrite synthesized casts.
4803 if (LocStart.isInvalid())
4804 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00004805 // Need to avoid trying to rewrite casts contained in macros.
4806 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4807 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004808
Steve Naroff54055232008-10-27 17:20:55 +00004809 const char *startBuf = SM->getCharacterData(LocStart);
4810 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004811 QualType QT = CE->getType();
4812 const Type* TypePtr = QT->getAs<Type>();
4813 if (isa<TypeOfExprType>(TypePtr)) {
4814 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4815 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4816 std::string TypeAsString = "(";
Fariborz Jahanianafad76f2010-02-18 01:20:22 +00004817 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004818 TypeAsString += ")";
Benjamin Kramerd999b372010-02-14 14:14:16 +00004819 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004820 return;
4821 }
Steve Naroff54055232008-10-27 17:20:55 +00004822 // advance the location to startArgList.
4823 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00004824
Steve Naroff54055232008-10-27 17:20:55 +00004825 while (*argPtr++ && (argPtr < endBuf)) {
4826 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004827 case '^':
4828 // Replace the '^' with '*'.
4829 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004830 ReplaceText(LocStart, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004831 break;
Steve Naroff54055232008-10-27 17:20:55 +00004832 }
4833 }
4834 return;
4835}
4836
4837void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4838 SourceLocation DeclLoc = FD->getLocation();
4839 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004840
Steve Naroff54055232008-10-27 17:20:55 +00004841 // We have 1 or more arguments that have closure pointers.
4842 const char *startBuf = SM->getCharacterData(DeclLoc);
4843 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00004844
Steve Naroff54055232008-10-27 17:20:55 +00004845 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004846
Steve Naroff54055232008-10-27 17:20:55 +00004847 parenCount++;
4848 // advance the location to startArgList.
4849 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4850 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00004851
Steve Naroff54055232008-10-27 17:20:55 +00004852 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00004853
Steve Naroff54055232008-10-27 17:20:55 +00004854 while (*argPtr++ && parenCount) {
4855 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004856 case '^':
4857 // Replace the '^' with '*'.
4858 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004859 ReplaceText(DeclLoc, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004860 break;
4861 case '(':
4862 parenCount++;
4863 break;
4864 case ')':
4865 parenCount--;
4866 break;
Steve Naroff54055232008-10-27 17:20:55 +00004867 }
4868 }
4869 return;
4870}
4871
4872bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004873 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004874 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004875 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004876 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004877 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004878 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004879 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004880 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004881 }
4882 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004883 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004884 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004885 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004886 return true;
4887 }
4888 return false;
4889}
4890
Ted Kremenek8189cde2009-02-07 01:47:29 +00004891void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4892 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00004893 const char *argPtr = strchr(Name, '(');
4894 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004895
Steve Naroff54055232008-10-27 17:20:55 +00004896 LParen = argPtr; // output the start.
4897 argPtr++; // skip past the left paren.
4898 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004899
Steve Naroff54055232008-10-27 17:20:55 +00004900 while (*argPtr && parenCount) {
4901 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004902 case '(': parenCount++; break;
4903 case ')': parenCount--; break;
4904 default: break;
Steve Naroff54055232008-10-27 17:20:55 +00004905 }
4906 if (parenCount) argPtr++;
4907 }
4908 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4909 RParen = argPtr; // output the end
4910}
4911
4912void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4913 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4914 RewriteBlockPointerFunctionArgs(FD);
4915 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004916 }
Steve Naroff54055232008-10-27 17:20:55 +00004917 // Handle Variables and Typedefs.
4918 SourceLocation DeclLoc = ND->getLocation();
4919 QualType DeclT;
4920 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4921 DeclT = VD->getType();
4922 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4923 DeclT = TDD->getUnderlyingType();
4924 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4925 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004926 else
Steve Naroff54055232008-10-27 17:20:55 +00004927 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00004928
Steve Naroff54055232008-10-27 17:20:55 +00004929 const char *startBuf = SM->getCharacterData(DeclLoc);
4930 const char *endBuf = startBuf;
4931 // scan backward (from the decl location) for the end of the previous decl.
4932 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4933 startBuf--;
Mike Stump1eb44332009-09-09 15:08:12 +00004934
Steve Naroff54055232008-10-27 17:20:55 +00004935 // *startBuf != '^' if we are dealing with a pointer to function that
4936 // may take block argument types (which will be handled below).
4937 if (*startBuf == '^') {
4938 // Replace the '^' with '*', computing a negative offset.
4939 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004940 ReplaceText(DeclLoc, 1, "*");
Steve Naroff54055232008-10-27 17:20:55 +00004941 }
4942 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4943 // Replace the '^' with '*' for arguments.
4944 DeclLoc = ND->getLocation();
4945 startBuf = SM->getCharacterData(DeclLoc);
4946 const char *argListBegin, *argListEnd;
4947 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4948 while (argListBegin < argListEnd) {
4949 if (*argListBegin == '^') {
4950 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004951 ReplaceText(CaretLoc, 1, "*");
Steve Naroff54055232008-10-27 17:20:55 +00004952 }
4953 argListBegin++;
4954 }
4955 }
4956 return;
4957}
4958
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004959
4960/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4961/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4962/// struct Block_byref_id_object *src) {
4963/// _Block_object_assign (&_dest->object, _src->object,
4964/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4965/// [|BLOCK_FIELD_IS_WEAK]) // object
4966/// _Block_object_assign(&_dest->object, _src->object,
4967/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4968/// [|BLOCK_FIELD_IS_WEAK]) // block
4969/// }
4970/// And:
4971/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4972/// _Block_object_dispose(_src->object,
4973/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4974/// [|BLOCK_FIELD_IS_WEAK]) // object
4975/// _Block_object_dispose(_src->object,
4976/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4977/// [|BLOCK_FIELD_IS_WEAK]) // block
4978/// }
4979
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004980std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4981 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004982 std::string S;
Benjamin Kramer1211a712010-01-10 19:57:50 +00004983 if (CopyDestroyCache.count(flag))
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004984 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004985 CopyDestroyCache.insert(flag);
4986 S = "static void __Block_byref_id_object_copy_";
4987 S += utostr(flag);
4988 S += "(void *dst, void *src) {\n";
4989
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004990 // offset into the object pointer is computed as:
4991 // void * + void* + int + int + void* + void *
4992 unsigned IntSize =
4993 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4994 unsigned VoidPtrSize =
4995 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4996
4997 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
4998 S += " _Block_object_assign((char*)dst + ";
4999 S += utostr(offset);
5000 S += ", *(void * *) ((char*)src + ";
5001 S += utostr(offset);
5002 S += "), ";
5003 S += utostr(flag);
5004 S += ");\n}\n";
5005
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005006 S += "static void __Block_byref_id_object_dispose_";
5007 S += utostr(flag);
5008 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005009 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5010 S += utostr(offset);
5011 S += "), ";
5012 S += utostr(flag);
5013 S += ");\n}\n";
5014 return S;
5015}
5016
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005017/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5018/// the declaration into:
5019/// struct __Block_byref_ND {
5020/// void *__isa; // NULL for everything except __weak pointers
5021/// struct __Block_byref_ND *__forwarding;
5022/// int32_t __flags;
5023/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005024/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5025/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005026/// typex ND;
5027/// };
5028///
5029/// It then replaces declaration of ND variable with:
5030/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5031/// __size=sizeof(struct __Block_byref_ND),
5032/// ND=initializer-if-any};
5033///
5034///
5035void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005036 // Insert declaration for the function in which block literal is
5037 // used.
5038 if (CurFunctionDeclToDeclareForBlock)
5039 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005040 int flag = 0;
5041 int isa = 0;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005042 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahaniand64a4f42010-02-26 22:49:11 +00005043 if (DeclLoc.isInvalid())
5044 // If type location is missing, it is because of missing type (a warning).
5045 // Use variable's location which is good for this case.
5046 DeclLoc = ND->getLocation();
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005047 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00005048 SourceLocation X = ND->getLocEnd();
5049 X = SM->getInstantiationLoc(X);
5050 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005051 std::string Name(ND->getNameAsString());
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005052 std::string ByrefType;
5053 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005054 ByrefType += " {\n";
5055 ByrefType += " void *__isa;\n";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005056 RewriteByRefString(ByrefType, Name, ND);
5057 ByrefType += " *__forwarding;\n";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005058 ByrefType += " int __flags;\n";
5059 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005060 // Add void *__Block_byref_id_object_copy;
5061 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005062 QualType Ty = ND->getType();
5063 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
5064 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005065 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5066 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005067 }
5068
5069 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005070 ByrefType += " " + Name + ";\n";
5071 ByrefType += "};\n";
5072 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005073 SourceLocation FunLocStart;
5074 if (CurFunctionDef)
5075 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
5076 else {
5077 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5078 FunLocStart = CurMethodDef->getLocStart();
5079 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00005080 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005081 if (Ty.isObjCGCWeak()) {
5082 flag |= BLOCK_FIELD_IS_WEAK;
5083 isa = 1;
5084 }
5085
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005086 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005087 flag = BLOCK_BYREF_CALLER;
5088 QualType Ty = ND->getType();
5089 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5090 if (Ty->isBlockPointerType())
5091 flag |= BLOCK_FIELD_IS_BLOCK;
5092 else
5093 flag |= BLOCK_FIELD_IS_OBJECT;
5094 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005095 if (!HF.empty())
Benjamin Kramerd999b372010-02-14 14:14:16 +00005096 InsertText(FunLocStart, HF);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005097 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005098
5099 // struct __Block_byref_ND ND =
5100 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5101 // initializer-if-any};
5102 bool hasInit = (ND->getInit() != 0);
Fariborz Jahaniane1f84f82010-01-05 18:15:57 +00005103 unsigned flags = 0;
5104 if (HasCopyAndDispose)
5105 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005106 Name = ND->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005107 ByrefType.clear();
5108 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005109 std::string ForwardingCastType("(");
5110 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005111 if (!hasInit) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005112 ByrefType += " " + Name + " = {(void*)";
5113 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005114 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005115 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005116 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005117 ByrefType += "sizeof(";
5118 RewriteByRefString(ByrefType, Name, ND);
5119 ByrefType += ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005120 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005121 ByrefType += ", __Block_byref_id_object_copy_";
5122 ByrefType += utostr(flag);
5123 ByrefType += ", __Block_byref_id_object_dispose_";
5124 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005125 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005126 ByrefType += "};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00005127 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(), ByrefType);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005128 }
5129 else {
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005130 SourceLocation startLoc;
5131 Expr *E = ND->getInit();
5132 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5133 startLoc = ECE->getLParenLoc();
5134 else
5135 startLoc = E->getLocStart();
Fariborz Jahanian791b10d2010-01-05 23:06:29 +00005136 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005137 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005138 ByrefType += " " + Name;
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005139 ByrefType += " = {(void*)";
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005140 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005141 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005142 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005143 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005144 ByrefType += "sizeof(";
5145 RewriteByRefString(ByrefType, Name, ND);
5146 ByrefType += "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005147 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005148 ByrefType += "__Block_byref_id_object_copy_";
5149 ByrefType += utostr(flag);
5150 ByrefType += ", __Block_byref_id_object_dispose_";
5151 ByrefType += utostr(flag);
5152 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005153 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00005154 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroffc5143c52009-12-23 17:24:33 +00005155
5156 // Complete the newly synthesized compound expression by inserting a right
5157 // curly brace before the end of the declaration.
5158 // FIXME: This approach avoids rewriting the initializer expression. It
5159 // also assumes there is only one declarator. For example, the following
5160 // isn't currently supported by this routine (in general):
5161 //
5162 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
5163 //
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00005164 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5165 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroffc5143c52009-12-23 17:24:33 +00005166 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
5167 SourceLocation semiLoc =
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00005168 startLoc.getFileLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroffc5143c52009-12-23 17:24:33 +00005169
Benjamin Kramerd999b372010-02-14 14:14:16 +00005170 InsertText(semiLoc, "}");
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005171 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00005172 return;
5173}
5174
Mike Stump1eb44332009-09-09 15:08:12 +00005175void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00005176 // Add initializers for any closure decl refs.
5177 GetBlockDeclRefExprs(Exp->getBody());
5178 if (BlockDeclRefs.size()) {
5179 // Unique all "by copy" declarations.
5180 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005181 if (!BlockDeclRefs[i]->isByRef()) {
5182 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5183 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5184 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5185 }
5186 }
Steve Naroff54055232008-10-27 17:20:55 +00005187 // Unique all "by ref" declarations.
5188 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5189 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005190 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5191 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5192 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5193 }
Steve Naroff54055232008-10-27 17:20:55 +00005194 }
5195 // Find any imported blocks...they will need special attention.
5196 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00005197 if (BlockDeclRefs[i]->isByRef() ||
5198 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian5b011b02010-02-26 21:46:27 +00005199 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff54055232008-10-27 17:20:55 +00005200 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff54055232008-10-27 17:20:55 +00005201 }
5202}
5203
Daniel Dunbar4087f272010-08-17 22:39:59 +00005204FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(llvm::StringRef name) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005205 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00005206 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump1eb44332009-09-09 15:08:12 +00005207 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
John McCalld931b082010-08-26 03:08:43 +00005208 ID, FType, 0, SC_Extern,
5209 SC_None, false, false);
Steve Narofffa15fd92008-10-28 20:29:00 +00005210}
5211
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005212Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
5213 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005214 Blocks.push_back(Exp);
5215
5216 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005217
5218 // Add inner imported variables now used in current block.
5219 int countOfInnerDecls = 0;
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005220 if (!InnerBlockDeclRefs.empty()) {
5221 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5222 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
5223 ValueDecl *VD = Exp->getDecl();
5224 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005225 // We need to save the copied-in variables in nested
5226 // blocks because it is needed at the end for some of the API generations.
5227 // See SynthesizeBlockLiterals routine.
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005228 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5229 BlockDeclRefs.push_back(Exp);
5230 BlockByCopyDeclsPtrSet.insert(VD);
5231 BlockByCopyDecls.push_back(VD);
5232 }
5233 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
5234 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5235 BlockDeclRefs.push_back(Exp);
5236 BlockByRefDeclsPtrSet.insert(VD);
5237 BlockByRefDecls.push_back(VD);
5238 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005239 }
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005240 // Find any imported blocks...they will need special attention.
5241 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5242 if (InnerBlockDeclRefs[i]->isByRef() ||
5243 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5244 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5245 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005246 }
5247 InnerDeclRefsCount.push_back(countOfInnerDecls);
5248
Steve Narofffa15fd92008-10-28 20:29:00 +00005249 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00005250
Steve Narofffa15fd92008-10-28 20:29:00 +00005251 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00005252 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00005253 else if (CurMethodDef)
5254 BuildUniqueMethodName(FuncName, CurMethodDef);
5255 else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005256 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00005257
Steve Narofffa15fd92008-10-28 20:29:00 +00005258 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00005259
Steve Narofffa15fd92008-10-28 20:29:00 +00005260 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
5261 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00005262
Steve Narofffa15fd92008-10-28 20:29:00 +00005263 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian1f906222010-05-25 15:56:08 +00005264 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5265 QualType FType = Context->getPointerType(BFT);
Steve Narofffa15fd92008-10-28 20:29:00 +00005266
5267 FunctionDecl *FD;
5268 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00005269
Steve Narofffa15fd92008-10-28 20:29:00 +00005270 // Simulate a contructor call...
Daniel Dunbar4087f272010-08-17 22:39:59 +00005271 FD = SynthBlockInitFunctionDecl(Tag);
Ted Kremenek8189cde2009-02-07 01:47:29 +00005272 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00005273
Steve Narofffa15fd92008-10-28 20:29:00 +00005274 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00005275
Steve Narofffdc03722008-10-29 21:23:59 +00005276 // Initialize the block function.
Daniel Dunbar4087f272010-08-17 22:39:59 +00005277 FD = SynthBlockInitFunctionDecl(Func);
Ted Kremenek8189cde2009-02-07 01:47:29 +00005278 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
5279 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005280 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCall2de56d12010-08-25 11:45:40 +00005281 CK_Unknown, Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00005282 InitExprs.push_back(castExpr);
5283
Steve Naroff01aec112009-12-06 21:14:13 +00005284 // Initialize the block descriptor.
5285 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00005286
Steve Naroff01aec112009-12-06 21:14:13 +00005287 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
5288 &Context->Idents.get(DescData.c_str()),
5289 Context->VoidPtrTy, 0,
John McCalld931b082010-08-26 03:08:43 +00005290 SC_Static, SC_None);
Steve Naroff01aec112009-12-06 21:14:13 +00005291 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
5292 new (Context) DeclRefExpr(NewVD,
5293 Context->VoidPtrTy, SourceLocation()),
John McCall2de56d12010-08-25 11:45:40 +00005294 UO_AddrOf,
Steve Naroff01aec112009-12-06 21:14:13 +00005295 Context->getPointerType(Context->VoidPtrTy),
5296 SourceLocation());
5297 InitExprs.push_back(DescRefExpr);
5298
Steve Narofffa15fd92008-10-28 20:29:00 +00005299 // Add initializers for any closure decl refs.
5300 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00005301 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00005302 // Output all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005303 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005304 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005305 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00005306 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar4087f272010-08-17 22:39:59 +00005307 FD = SynthBlockInitFunctionDecl((*I)->getName());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005308 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00005309 if (HasLocalVariableExternalStorage(*I)) {
5310 QualType QT = (*I)->getType();
5311 QT = Context->getPointerType(QT);
John McCall2de56d12010-08-25 11:45:40 +00005312 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT,
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00005313 SourceLocation());
5314 }
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005315 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00005316 FD = SynthBlockInitFunctionDecl((*I)->getName());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005317 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005318 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCall2de56d12010-08-25 11:45:40 +00005319 CK_Unknown, Arg);
Steve Narofffa15fd92008-10-28 20:29:00 +00005320 } else {
Daniel Dunbar4087f272010-08-17 22:39:59 +00005321 FD = SynthBlockInitFunctionDecl((*I)->getName());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005322 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005323 if (HasLocalVariableExternalStorage(*I)) {
5324 QualType QT = (*I)->getType();
5325 QT = Context->getPointerType(QT);
John McCall2de56d12010-08-25 11:45:40 +00005326 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT,
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005327 SourceLocation());
5328 }
5329
Steve Narofffa15fd92008-10-28 20:29:00 +00005330 }
Mike Stump1eb44332009-09-09 15:08:12 +00005331 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005332 }
5333 // Output all "by ref" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005334 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005335 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005336 ValueDecl *ND = (*I);
5337 std::string Name(ND->getNameAsString());
5338 std::string RecName;
5339 RewriteByRefString(RecName, Name, ND);
5340 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5341 + sizeof("struct"));
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005342 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005343 SourceLocation(), II);
5344 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5345 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5346
Daniel Dunbar4087f272010-08-17 22:39:59 +00005347 FD = SynthBlockInitFunctionDecl((*I)->getName());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005348 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00005349 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00005350 Context->getPointerType(Exp->getType()),
Steve Narofffdc03722008-10-29 21:23:59 +00005351 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00005352 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_Unknown, Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00005353 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005354 }
5355 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00005356 if (ImportedBlockDecls.size()) {
5357 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5358 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00005359 unsigned IntSize =
5360 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005361 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5362 Context->IntTy, SourceLocation());
Fariborz Jahanianff127882009-12-23 21:52:32 +00005363 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00005364 }
Ted Kremenek668bf912009-02-09 20:51:47 +00005365 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
5366 FType, SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00005367 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00005368 Context->getPointerType(NewRep->getType()),
Steve Narofffa15fd92008-10-28 20:29:00 +00005369 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00005370 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_Unknown,
John McCall9d125032010-01-15 18:39:57 +00005371 NewRep);
Steve Narofffa15fd92008-10-28 20:29:00 +00005372 BlockDeclRefs.clear();
5373 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005374 BlockByRefDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005375 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005376 BlockByCopyDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005377 ImportedBlockDecls.clear();
5378 return NewRep;
5379}
5380
5381//===----------------------------------------------------------------------===//
5382// Function Body / Expression rewriting
5383//===----------------------------------------------------------------------===//
5384
Steve Naroffc77a6362008-12-04 16:24:46 +00005385// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
5386// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
5387// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
5388// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
5389// Since the rewriter isn't capable of rewriting rewritten code, it's important
5390// we get this right.
5391void RewriteObjC::CollectPropertySetters(Stmt *S) {
5392 // Perform a bottom up traversal of all children.
5393 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5394 CI != E; ++CI)
5395 if (*CI)
5396 CollectPropertySetters(*CI);
5397
5398 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
5399 if (BinOp->isAssignmentOp()) {
Fariborz Jahanian8537f7b2010-10-11 22:21:03 +00005400 if (isa<ObjCPropertyRefExpr>(BinOp->getLHS()) ||
5401 isa<ObjCImplicitSetterGetterRefExpr>(BinOp->getLHS()))
5402 PropSetters[BinOp->getLHS()] = BinOp;
Steve Naroffc77a6362008-12-04 16:24:46 +00005403 }
5404 }
5405}
5406
Steve Narofffa15fd92008-10-28 20:29:00 +00005407Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00005408 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005409 isa<DoStmt>(S) || isa<ForStmt>(S))
5410 Stmts.push_back(S);
5411 else if (isa<ObjCForCollectionStmt>(S)) {
5412 Stmts.push_back(S);
Chris Lattner4824fcd2010-01-09 21:45:57 +00005413 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00005414 }
Mike Stump1eb44332009-09-09 15:08:12 +00005415
Steve Narofffa15fd92008-10-28 20:29:00 +00005416 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005417
Steve Narofffa15fd92008-10-28 20:29:00 +00005418 // Perform a bottom up rewrite of all children.
5419 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5420 CI != E; ++CI)
5421 if (*CI) {
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005422 Stmt *newStmt;
5423 Stmt *S = (*CI);
5424 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5425 Expr *OldBase = IvarRefExpr->getBase();
5426 bool replaced = false;
5427 newStmt = RewriteObjCNestedIvarRefExpr(S, replaced);
5428 if (replaced) {
5429 if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
5430 ReplaceStmt(OldBase, IRE->getBase());
5431 else
5432 ReplaceStmt(S, newStmt);
5433 }
5434 }
5435 else
5436 newStmt = RewriteFunctionBodyOrGlobalInitializer(S);
Mike Stump1eb44332009-09-09 15:08:12 +00005437 if (newStmt)
Steve Narofffa15fd92008-10-28 20:29:00 +00005438 *CI = newStmt;
Fariborz Jahanian90fe4bc2010-10-08 21:12:22 +00005439 // If dealing with an assignment with LHS being a property reference
5440 // expression, the entire assignment tree is rewritten into a property
5441 // setter messaging. This involvs the RHS too. Do not attempt to rewrite
5442 // RHS again.
Fariborz Jahanian8537f7b2010-10-11 22:21:03 +00005443 if (Expr *Exp = dyn_cast<Expr>(S))
5444 if (isa<ObjCPropertyRefExpr>(Exp) ||
5445 isa<ObjCImplicitSetterGetterRefExpr>(Exp)) {
5446 if (PropSetters[Exp]) {
5447 ++CI;
5448 continue;
5449 }
Fariborz Jahanian90fe4bc2010-10-08 21:12:22 +00005450 }
Fariborz Jahanian8537f7b2010-10-11 22:21:03 +00005451 }
Mike Stump1eb44332009-09-09 15:08:12 +00005452
Steve Narofffa15fd92008-10-28 20:29:00 +00005453 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005454 llvm::SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005455 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5456 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005457 ImportedLocalExternalDecls.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005458 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005459 InnerBlockDeclRefs, InnerContexts);
Steve Narofffa15fd92008-10-28 20:29:00 +00005460 // Rewrite the block body in place.
5461 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005462 ImportedLocalExternalDecls.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005463 // Now we snarf the rewritten text and stash it away for later use.
Ted Kremenek6a12a142010-01-07 18:00:35 +00005464 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005465 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00005466
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005467 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5468
Steve Narofffa15fd92008-10-28 20:29:00 +00005469 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005470 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00005471 return blockTranscribed;
5472 }
5473 // Handle specific things.
5474 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5475 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00005476
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005477 if (isa<ObjCPropertyRefExpr>(S) || isa<ObjCImplicitSetterGetterRefExpr>(S)) {
5478 Expr *PropOrImplicitRefExpr = dyn_cast<Expr>(S);
5479 assert(PropOrImplicitRefExpr && "Property or implicit setter/getter is null");
5480
5481 BinaryOperator *BinOp = PropSetters[PropOrImplicitRefExpr];
Steve Naroffc77a6362008-12-04 16:24:46 +00005482 if (BinOp) {
5483 // Because the rewriter doesn't allow us to rewrite rewritten code,
5484 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffb619d952008-12-09 12:56:34 +00005485 DisableReplaceStmt = true;
5486 // Save the source range. Even if we disable the replacement, the
5487 // rewritten node will have been inserted into the tree. If the synthesized
5488 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump1eb44332009-09-09 15:08:12 +00005489 // self.errorHandler = handler ? handler :
Steve Naroffb619d952008-12-09 12:56:34 +00005490 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
5491 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroffc77a6362008-12-04 16:24:46 +00005492 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Fariborz Jahanianf2c6fa42010-10-14 23:31:39 +00005493 // Need to rewrite the ivar access expression if need be.
5494 if (isa<ObjCIvarRefExpr>(newStmt)) {
5495 bool replaced = false;
5496 newStmt = RewriteObjCNestedIvarRefExpr(newStmt, replaced);
5497 }
5498
Steve Naroffb619d952008-12-09 12:56:34 +00005499 DisableReplaceStmt = false;
Steve Naroff4c3580e2008-12-04 23:50:32 +00005500 //
5501 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
5502 // we changed the RHS of BinOp, the rewriter would fail (since it needs
5503 // to see the original expression). Consider this example:
5504 //
5505 // Foo *obj1, *obj2;
5506 //
5507 // obj1.i = [obj2 rrrr];
5508 //
5509 // 'BinOp' for the previous expression looks like:
5510 //
5511 // (BinaryOperator 0x231ccf0 'int' '='
5512 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
5513 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
5514 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
5515 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
5516 //
5517 // 'newStmt' represents the rewritten message expression. For example:
5518 //
5519 // (CallExpr 0x231d300 'id':'struct objc_object *'
5520 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
5521 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
5522 // (CStyleCastExpr 0x231d220 'void *'
5523 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
5524 //
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005525 // Note that 'newStmt' is passed to RewritePropertyOrImplicitSetter so that it
Steve Naroff4c3580e2008-12-04 23:50:32 +00005526 // can be used as the setter argument. ReplaceStmt() will still 'see'
5527 // the original RHS (since we haven't altered BinOp).
5528 //
Mike Stump1eb44332009-09-09 15:08:12 +00005529 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff4c3580e2008-12-04 23:50:32 +00005530 // node. As a result, we now leak the original AST nodes.
5531 //
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005532 return RewritePropertyOrImplicitSetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroffc77a6362008-12-04 16:24:46 +00005533 } else {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005534 return RewritePropertyOrImplicitGetter(PropOrImplicitRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00005535 }
5536 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005537
Steve Narofffa15fd92008-10-28 20:29:00 +00005538 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5539 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00005540
Steve Narofffa15fd92008-10-28 20:29:00 +00005541 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5542 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00005543
Steve Narofffa15fd92008-10-28 20:29:00 +00005544 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00005545#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00005546 // Before we rewrite it, put the original message expression in a comment.
5547 SourceLocation startLoc = MessExpr->getLocStart();
5548 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00005549
Steve Narofffa15fd92008-10-28 20:29:00 +00005550 const char *startBuf = SM->getCharacterData(startLoc);
5551 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00005552
Steve Narofffa15fd92008-10-28 20:29:00 +00005553 std::string messString;
5554 messString += "// ";
5555 messString.append(startBuf, endBuf-startBuf+1);
5556 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00005557
5558 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00005559 // InsertText(clang::SourceLocation, char const*, unsigned int).
5560 // InsertText(startLoc, messString.c_str(), messString.size());
5561 // Tried this, but it didn't work either...
5562 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00005563#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00005564 return RewriteMessageExpr(MessExpr);
5565 }
Mike Stump1eb44332009-09-09 15:08:12 +00005566
Steve Narofffa15fd92008-10-28 20:29:00 +00005567 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5568 return RewriteObjCTryStmt(StmtTry);
5569
5570 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5571 return RewriteObjCSynchronizedStmt(StmtTry);
5572
5573 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5574 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00005575
Steve Narofffa15fd92008-10-28 20:29:00 +00005576 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5577 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00005578
5579 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00005580 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00005581 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00005582 OrigStmtRange.getEnd());
5583 if (BreakStmt *StmtBreakStmt =
5584 dyn_cast<BreakStmt>(S))
5585 return RewriteBreakStmt(StmtBreakStmt);
5586 if (ContinueStmt *StmtContinueStmt =
5587 dyn_cast<ContinueStmt>(S))
5588 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00005589
5590 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00005591 // and cast exprs.
5592 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5593 // FIXME: What we're doing here is modifying the type-specifier that
5594 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00005595 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00005596 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5597 // the context of an ObjCForCollectionStmt. For example:
5598 // NSArray *someArray;
5599 // for (id <FooProtocol> index in someArray) ;
5600 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5601 // and it depends on the original text locations/positions.
Benjamin Kramerb2041de2009-12-05 22:16:51 +00005602 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroff3d7e7862009-12-05 15:55:59 +00005603 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00005604
Steve Narofffa15fd92008-10-28 20:29:00 +00005605 // Blocks rewrite rules.
5606 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5607 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00005608 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00005609 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005610 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005611 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00005612 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005613 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005614 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005615 if (VD->hasAttr<BlocksAttr>()) {
5616 static unsigned uniqueByrefDeclCount = 0;
5617 assert(!BlockByRefDeclNo.count(ND) &&
5618 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5619 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005620 RewriteByRefVar(VD);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005621 }
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005622 else
5623 RewriteTypeOfDecl(VD);
5624 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005625 }
5626 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005627 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005628 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005629 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005630 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5631 }
5632 }
5633 }
Mike Stump1eb44332009-09-09 15:08:12 +00005634
Steve Narofffa15fd92008-10-28 20:29:00 +00005635 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5636 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00005637
5638 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005639 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5640 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00005641 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5642 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005643 && "Statement stack mismatch");
5644 Stmts.pop_back();
5645 }
5646 // Handle blocks rewriting.
5647 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5648 if (BDRE->isByRef())
Steve Naroff621edce2009-04-29 16:37:50 +00005649 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofffa15fd92008-10-28 20:29:00 +00005650 }
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005651 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5652 ValueDecl *VD = DRE->getDecl();
5653 if (VD->hasAttr<BlocksAttr>())
5654 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005655 if (HasLocalVariableExternalStorage(VD))
5656 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005657 }
5658
Steve Narofffa15fd92008-10-28 20:29:00 +00005659 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005660 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00005661 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005662 ReplaceStmt(S, BlockCall);
5663 return BlockCall;
5664 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005665 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00005666 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005667 RewriteCastExpr(CE);
5668 }
5669#if 0
5670 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redl906082e2010-07-20 04:20:21 +00005671 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5672 ICE->getSubExpr(),
5673 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00005674 // Get the new text.
5675 std::string SStr;
5676 llvm::raw_string_ostream Buf(SStr);
Eli Friedman3a9eb442009-05-30 05:19:26 +00005677 Replacement->printPretty(Buf, *Context);
Steve Narofffa15fd92008-10-28 20:29:00 +00005678 const std::string &Str = Buf.str();
5679
5680 printf("CAST = %s\n", &Str[0]);
5681 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5682 delete S;
5683 return Replacement;
5684 }
5685#endif
5686 // Return this stmt unmodified.
5687 return S;
5688}
5689
Steve Naroff3d7e7862009-12-05 15:55:59 +00005690void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5691 for (RecordDecl::field_iterator i = RD->field_begin(),
5692 e = RD->field_end(); i != e; ++i) {
5693 FieldDecl *FD = *i;
5694 if (isTopLevelBlockPointerType(FD->getType()))
5695 RewriteBlockPointerDecl(FD);
5696 if (FD->getType()->isObjCQualifiedIdType() ||
5697 FD->getType()->isObjCQualifiedInterfaceType())
5698 RewriteObjCQualifiedInterfaceTypes(FD);
5699 }
5700}
5701
Steve Narofffa15fd92008-10-28 20:29:00 +00005702/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5703/// main file of the input.
5704void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5705 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffcb735302008-12-17 00:20:22 +00005706 if (FD->isOverloadedOperator())
5707 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005708
Steve Narofffa15fd92008-10-28 20:29:00 +00005709 // Since function prototypes don't have ParmDecl's, we check the function
5710 // prototype. This enables us to rewrite function declarations and
5711 // definitions using the same code.
Douglas Gregor72564e72009-02-26 23:50:07 +00005712 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005713
Sebastian Redld3a413d2009-04-26 20:35:05 +00005714 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidis5f1bfc12010-07-07 11:31:34 +00005715 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005716 CurFunctionDef = FD;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005717 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005718 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005719 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005720 Body =
5721 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5722 FD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005723 CurrentBody = 0;
5724 if (PropParentMap) {
5725 delete PropParentMap;
5726 PropParentMap = 0;
5727 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005728 // This synthesizes and inserts the block "impl" struct, invoke function,
5729 // and any copy/dispose helper functions.
5730 InsertBlockLiteralsWithinFunction(FD);
5731 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005732 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00005733 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005734 return;
5735 }
5736 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005737 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005738 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005739 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005740 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005741 Body =
5742 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5743 MD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005744 CurrentBody = 0;
5745 if (PropParentMap) {
5746 delete PropParentMap;
5747 PropParentMap = 0;
5748 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005749 InsertBlockLiteralsWithinMethod(MD);
5750 CurMethodDef = 0;
5751 }
5752 }
5753 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5754 ClassImplementation.push_back(CI);
5755 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5756 CategoryImplementation.push_back(CI);
5757 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5758 RewriteForwardClassDecl(CD);
5759 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5760 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005761 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005762 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005763 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005764 CheckFunctionPointerDecl(VD->getType(), VD);
5765 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00005766 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005767 RewriteCastExpr(CE);
5768 }
5769 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00005770 } else if (VD->getType()->isRecordType()) {
5771 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5772 if (RD->isDefinition())
5773 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005774 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005775 if (VD->getInit()) {
5776 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005777 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005778 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005779 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005780 CurrentBody = 0;
5781 if (PropParentMap) {
5782 delete PropParentMap;
5783 PropParentMap = 0;
5784 }
Mike Stump1eb44332009-09-09 15:08:12 +00005785 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00005786 VD->getName());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005787 GlobalVarDecl = 0;
5788
5789 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00005790 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005791 RewriteCastExpr(CE);
5792 }
5793 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005794 return;
5795 }
5796 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005797 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005798 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005799 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005800 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5801 return;
5802 }
5803 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroff3d7e7862009-12-05 15:55:59 +00005804 if (RD->isDefinition())
5805 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005806 return;
5807 }
5808 // Nothing yet.
5809}
5810
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00005811void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005812 if (Diags.hasErrorOccurred())
5813 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005814
Steve Narofffa15fd92008-10-28 20:29:00 +00005815 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00005816
Steve Naroff621edce2009-04-29 16:37:50 +00005817 // Here's a great place to add any extra declarations that may be needed.
5818 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00005819 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00005820 E = ProtocolExprDecls.end(); I != E; ++I)
5821 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5822
Benjamin Kramerd999b372010-02-14 14:14:16 +00005823 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff0aab7962008-11-14 14:10:01 +00005824 if (ClassImplementation.size() || CategoryImplementation.size())
5825 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00005826
Steve Narofffa15fd92008-10-28 20:29:00 +00005827 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5828 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00005829 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00005830 Rewrite.getRewriteBufferFor(MainFileID)) {
5831 //printf("Changed:\n");
5832 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5833 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +00005834 llvm::errs() << "No changes\n";
Steve Narofffa15fd92008-10-28 20:29:00 +00005835 }
Steve Narofface66252008-11-13 20:07:04 +00005836
Steve Naroff621edce2009-04-29 16:37:50 +00005837 if (ClassImplementation.size() || CategoryImplementation.size() ||
5838 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00005839 // Rewrite Objective-c meta data*
5840 std::string ResultStr;
5841 SynthesizeMetaDataIntoBuffer(ResultStr);
5842 // Emit metadata.
5843 *OutFile << ResultStr;
5844 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005845 OutFile->flush();
5846}