blob: 36b8db97349de7c4c64d4baa718941a1841b484e [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 {
Nico Weber59b173d2010-11-22 10:26:41 +000036 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000037 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 */
Nico Weber59b173d2010-11-22 10:26:41 +000041 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000042 helpers */
Nico Weber59b173d2010-11-22 10:26:41 +000043 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000044 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 };
Fariborz Jahanian58457172011-12-05 18:43:13 +000056 static const int OBJC_ABI_VERSION = 7;
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +000057
Chris Lattner2c64b7b2007-10-16 21:07:07 +000058 Rewriter Rewrite;
David Blaikied6471f72011-09-25 23:23:43 +000059 DiagnosticsEngine &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000060 const LangOptions &LangOpts;
Chris Lattner01c57482007-10-17 22:35:30 +000061 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000062 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000063 TranslationUnitDecl *TUDecl;
Chris Lattner2b2453a2009-01-17 06:22:33 +000064 FileID MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000065 const char *MainFileStart, *MainFileEnd;
Fariborz Jahanian58457172011-12-05 18:43:13 +000066 Stmt *CurrentBody;
67 ParentMap *PropParentMap; // created lazily.
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +000068 std::string InFileName;
69 raw_ostream* OutFile;
70 std::string Preamble;
71
72 TypeDecl *ProtocolTypeDecl;
73 VarDecl *GlobalVarDecl;
74 unsigned RewriteFailedDiag;
75 unsigned TryFinallyContainsReturnDiag;
76 // ObjC string constant support.
77 unsigned NumObjCStringLiterals;
78 VarDecl *ConstantStringClassReference;
79 RecordDecl *NSStringRecord;
Fariborz Jahanian58457172011-12-05 18:43:13 +000080
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +000081 // ObjC foreach break/continue generation support.
82 int BcLabelCount;
83
84 // Needed for super.
85 ObjCMethodDecl *CurMethodDef;
86 RecordDecl *SuperStructDecl;
87 RecordDecl *ConstantStringDecl;
88
89 FunctionDecl *MsgSendFunctionDecl;
90 FunctionDecl *MsgSendSuperFunctionDecl;
91 FunctionDecl *MsgSendStretFunctionDecl;
92 FunctionDecl *MsgSendSuperStretFunctionDecl;
93 FunctionDecl *MsgSendFpretFunctionDecl;
94 FunctionDecl *GetClassFunctionDecl;
95 FunctionDecl *GetMetaClassFunctionDecl;
96 FunctionDecl *GetSuperClassFunctionDecl;
97 FunctionDecl *SelGetUidFunctionDecl;
98 FunctionDecl *CFStringFunctionDecl;
99 FunctionDecl *SuperContructorFunctionDecl;
100 FunctionDecl *CurFunctionDef;
101 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Mike Stump1eb44332009-09-09 15:08:12 +0000102
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +0000103 /* Misc. containers needed for meta-data rewrite. */
Chris Lattner5f9e2722011-07-23 10:55:15 +0000104 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
105 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000106 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +0000107 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000108 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
109 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000110 SmallVector<Stmt *, 32> Stmts;
111 SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroff621edce2009-04-29 16:37:50 +0000112 // Remember all the @protocol(<expr>) expressions.
113 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +0000114
115 llvm::DenseSet<uint64_t> CopyDestroyCache;
Steve Naroff54055232008-10-27 17:20:55 +0000116
117 // Block expressions.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000118 SmallVector<BlockExpr *, 32> Blocks;
119 SmallVector<int, 32> InnerDeclRefsCount;
120 SmallVector<BlockDeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000121
Chris Lattner5f9e2722011-07-23 10:55:15 +0000122 SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
Mike Stump1eb44332009-09-09 15:08:12 +0000123
Steve Naroff54055232008-10-27 17:20:55 +0000124 // Block related declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000125 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
Fariborz Jahanianbab71682010-02-11 23:35:57 +0000126 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000127 SmallVector<ValueDecl *, 8> BlockByRefDecls;
Fariborz Jahanianbab71682010-02-11 23:35:57 +0000128 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000129 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff54055232008-10-27 17:20:55 +0000130 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000131 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
132
Steve Naroff54055232008-10-27 17:20:55 +0000133 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
134
Steve Naroff4c3580e2008-12-04 23:50:32 +0000135 // This maps an original source AST to it's rewritten form. This allows
136 // us to avoid rewriting the same node twice (which is very uncommon).
137 // This is needed to support some of the exotic property rewriting.
138 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Naroff15f081d2008-12-03 00:56:33 +0000139
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +0000140 // Needed for header files being rewritten
141 bool IsHeader;
142 bool SilenceRewriteMacroWarning;
143 bool objc_impl_method;
144
Steve Naroffb619d952008-12-09 12:56:34 +0000145 bool DisableReplaceStmt;
John McCall4b9c2d22011-11-06 09:01:30 +0000146 class DisableReplaceStmtScope {
147 RewriteObjC &R;
148 bool SavedValue;
Fariborz Jahanian58457172011-12-05 18:43:13 +0000149
John McCall4b9c2d22011-11-06 09:01:30 +0000150 public:
151 DisableReplaceStmtScope(RewriteObjC &R)
152 : R(R), SavedValue(R.DisableReplaceStmt) {
153 R.DisableReplaceStmt = true;
154 }
155 ~DisableReplaceStmtScope() {
156 R.DisableReplaceStmt = SavedValue;
157 }
158 };
Mike Stump1eb44332009-09-09 15:08:12 +0000159
Chris Lattner77cd2a02007-10-11 00:43:27 +0000160 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000161 virtual void Initialize(ASTContext &context);
162
Chris Lattnerf04da132007-10-24 17:06:59 +0000163 // Top Level Driver code.
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000164 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000165 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
166 if (isa<ObjCClassDecl>((*I))) {
167 RewriteForwardClassDecl(D);
168 break;
169 }
Chris Lattner682bf922009-03-29 16:50:03 +0000170 HandleTopLevelSingleDecl(*I);
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000171 }
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000172 return true;
Chris Lattner682bf922009-03-29 16:50:03 +0000173 }
174 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000175 void HandleDeclInMainFile(Decl *D);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000176 RewriteObjC(std::string inFile, raw_ostream *OS,
David Blaikied6471f72011-09-25 23:23:43 +0000177 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000178 bool silenceMacroWarn);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000179
180 ~RewriteObjC() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000181
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000182 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump1eb44332009-09-09 15:08:12 +0000183
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000184 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000185 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump1eb44332009-09-09 15:08:12 +0000186
Steve Naroff4c3580e2008-12-04 23:50:32 +0000187 if (ReplacingStmt)
188 return; // We can't rewrite the same node twice.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000189
Steve Naroffb619d952008-12-09 12:56:34 +0000190 if (DisableReplaceStmt)
John McCall4b9c2d22011-11-06 09:01:30 +0000191 return;
Steve Naroffb619d952008-12-09 12:56:34 +0000192
Steve Naroff4c3580e2008-12-04 23:50:32 +0000193 // If replacement succeeded or warning disabled return with no warning.
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000194 if (!Rewrite.ReplaceStmt(Old, New)) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000195 ReplacedNodes[Old] = New;
196 return;
197 }
198 if (SilenceRewriteMacroWarning)
199 return;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000200 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
201 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000202 }
Steve Naroffb619d952008-12-09 12:56:34 +0000203
204 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
John McCall4b9c2d22011-11-06 09:01:30 +0000205 if (DisableReplaceStmt)
206 return;
207
Nick Lewycky7e749242010-10-31 21:07:24 +0000208 // Measure the old text.
Steve Naroffb619d952008-12-09 12:56:34 +0000209 int Size = Rewrite.getRangeSize(SrcRange);
210 if (Size == -1) {
211 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
212 << Old->getSourceRange();
213 return;
214 }
215 // Get the new text.
216 std::string SStr;
217 llvm::raw_string_ostream S(SStr);
Chris Lattnere4f21422009-06-30 01:26:17 +0000218 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroffb619d952008-12-09 12:56:34 +0000219 const std::string &Str = S.str();
220
221 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000222 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroffb619d952008-12-09 12:56:34 +0000223 ReplacedNodes[Old] = New;
224 return;
225 }
226 if (SilenceRewriteMacroWarning)
227 return;
228 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
229 << Old->getSourceRange();
230 }
231
Chris Lattner5f9e2722011-07-23 10:55:15 +0000232 void InsertText(SourceLocation Loc, StringRef Str,
Steve Naroffba92b2e2008-03-27 22:29:16 +0000233 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000234 // If insertion succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000235 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000236 SilenceRewriteMacroWarning)
237 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000238
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000239 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
240 }
Mike Stump1eb44332009-09-09 15:08:12 +0000241
Chris Lattneraadaf782008-01-31 19:51:04 +0000242 void ReplaceText(SourceLocation Start, unsigned OrigLength,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000243 StringRef Str) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000244 // If removal succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000245 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
Chris Lattneraadaf782008-01-31 19:51:04 +0000246 SilenceRewriteMacroWarning)
247 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000248
Chris Lattneraadaf782008-01-31 19:51:04 +0000249 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
250 }
Mike Stump1eb44332009-09-09 15:08:12 +0000251
Chris Lattnerf04da132007-10-24 17:06:59 +0000252 // Syntactic Rewriting.
Fariborz Jahanian58457172011-12-05 18:43:13 +0000253 void RewriteRecordBody(RecordDecl *RD);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000254 void RewriteInclude();
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000255 void RewriteForwardClassDecl(DeclGroupRef D);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000256 void RewriteForwardClassDecl(const llvm::SmallVector<Decl*, 8> &DG);
257 void RewriteForwardClassEpilogue(ObjCClassDecl *ClassDecl,
258 const std::string &typedefString);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000259 void RewriteImplementations();
Steve Naroffa0876e82008-12-02 17:36:43 +0000260 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
261 ObjCImplementationDecl *IMD,
262 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000263 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000264 void RewriteImplementationDecl(Decl *Dcl);
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000265 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
266 ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000267 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
268 const FunctionType *&FPRetType);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000269 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +0000270 ValueDecl *VD, bool def=false);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000271 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
272 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
273 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
274 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000275 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff09b266e2007-10-30 23:14:51 +0000276 void RewriteFunctionDecl(FunctionDecl *FD);
Daniel Dunbarfa297fb2010-06-30 19:16:53 +0000277 void RewriteBlockPointerType(std::string& Str, QualType Type);
278 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000279 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000280 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +0000281 void RewriteTypeOfDecl(VarDecl *VD);
Steve Naroff4f95b752008-07-29 18:15:38 +0000282 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000283
Chris Lattnerf04da132007-10-24 17:06:59 +0000284 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000285 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000286 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
John McCall4b9c2d22011-11-06 09:01:30 +0000287 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
288 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
289 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
Steve Naroffb42f8412007-11-05 14:50:49 +0000290 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000291 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000292 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000293 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffb85e77a2009-12-05 21:43:12 +0000294 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);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000301 Stmt *RewriteBreakStmt(BreakStmt *S);
302 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000303 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump1eb44332009-09-09 15:08:12 +0000304
Fariborz Jahanian58457172011-12-05 18:43:13 +0000305 // Metadata Rewriting.
306 void RewriteMetaDataIntoBuffer(std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000307 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000308 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000309
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000310 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000311 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000312
Douglas Gregor653f1b12009-04-23 01:02:12 +0000313 template<typename MethodIterator>
314 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
315 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000316 bool IsInstanceMethod,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000317 StringRef prefix,
318 StringRef ClassName,
Chris Lattner158ecb92007-10-25 17:07:24 +0000319 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000320
Steve Naroff621edce2009-04-29 16:37:50 +0000321 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000322 StringRef prefix,
323 StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +0000324 std::string &Result);
325 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000326 StringRef prefix,
327 StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +0000328 std::string &Result);
Steve Naroff54055232008-10-27 17:20:55 +0000329 // Block rewriting.
Mike Stump1eb44332009-09-09 15:08:12 +0000330 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000331
Mike Stump1eb44332009-09-09 15:08:12 +0000332 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000333 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000334 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +0000335 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000336 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
Steve Naroff54055232008-10-27 17:20:55 +0000337 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000338
339 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
340 std::string &Result);
341 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
342 std::string &Result);
343
344 // Misc. AST transformation routines. Somtimes they end up calling
345 // rewriting routines on the new ASTs.
346 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
347 Expr **args, unsigned nargs,
348 SourceLocation StartLoc=SourceLocation(),
349 SourceLocation EndLoc=SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +0000350
Fariborz Jahanian58457172011-12-05 18:43:13 +0000351 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
352 SourceLocation StartLoc=SourceLocation(),
353 SourceLocation EndLoc=SourceLocation());
354
355 void SynthCountByEnumWithState(std::string &buf);
356 void SynthMsgSendFunctionDecl();
357 void SynthMsgSendSuperFunctionDecl();
358 void SynthMsgSendStretFunctionDecl();
359 void SynthMsgSendFpretFunctionDecl();
360 void SynthMsgSendSuperStretFunctionDecl();
361 void SynthGetClassFunctionDecl();
362 void SynthGetMetaClassFunctionDecl();
363 void SynthGetSuperClassFunctionDecl();
364 void SynthSelGetUidFunctionDecl();
365 void SynthSuperContructorFunctionDecl();
366
367 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Mike Stump1eb44332009-09-09 15:08:12 +0000368 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000369 StringRef funcName, std::string Tag);
Mike Stump1eb44332009-09-09 15:08:12 +0000370 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000371 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,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000376 int i, 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,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000380 StringRef FunName);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000381 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
382 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
383 const SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs);
Mike Stump1eb44332009-09-09 15:08:12 +0000384
Fariborz Jahanian58457172011-12-05 18:43:13 +0000385 // Misc. helper routines.
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +0000386 QualType getProtocolType();
Fariborz Jahanian58457172011-12-05 18:43:13 +0000387 void WarnAboutReturnGotoStmts(Stmt *S);
388 void HasReturnStmts(Stmt *S, bool &hasReturns);
389 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
390 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
391 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
392
393 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
Steve Naroff54055232008-10-27 17:20:55 +0000394 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000395 void GetBlockDeclRefExprs(Stmt *S);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000396 void GetInnerBlockDeclRefExprs(Stmt *S,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000397 SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +0000398 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
Mike Stump1eb44332009-09-09 15:08:12 +0000399
Steve Naroff54055232008-10-27 17:20:55 +0000400 // We avoid calling Type::isBlockPointerType(), since it operates on the
401 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000402 bool isTopLevelBlockPointerType(QualType T) {
403 return isa<BlockPointerType>(T);
404 }
Mike Stump1eb44332009-09-09 15:08:12 +0000405
Fariborz Jahanian4fc84532010-05-25 17:12:52 +0000406 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
407 /// to a function pointer type and upon success, returns true; false
408 /// otherwise.
409 bool convertBlockPointerToFunctionPointer(QualType &T) {
410 if (isTopLevelBlockPointerType(T)) {
411 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
412 T = Context->getPointerType(BPT->getPointeeType());
413 return true;
414 }
415 return false;
416 }
417
Fariborz Jahanian58457172011-12-05 18:43:13 +0000418 bool needToScanForQualifiers(QualType T);
419 QualType getSuperStructType();
420 QualType getConstantStringStructType();
421 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
422 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
423
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +0000424 void convertToUnqualifiedObjCType(QualType &T) {
425 if (T->isObjCQualifiedIdType())
426 T = Context->getObjCIdType();
427 else if (T->isObjCQualifiedClassType())
428 T = Context->getObjCClassType();
429 else if (T->isObjCObjectPointerType() &&
Fariborz Jahanian3a448fb2011-09-10 17:01:56 +0000430 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
431 if (const ObjCObjectPointerType * OBJPT =
432 T->getAsObjCInterfacePointerType()) {
433 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
434 T = QualType(IFaceT, 0);
435 T = Context->getPointerType(T);
436 }
437 }
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +0000438 }
439
Steve Naroff54055232008-10-27 17:20:55 +0000440 // FIXME: This predicate seems like it would be useful to add to ASTContext.
441 bool isObjCType(QualType T) {
442 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
443 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000444
Steve Naroff54055232008-10-27 17:20:55 +0000445 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000446
Steve Naroff54055232008-10-27 17:20:55 +0000447 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
448 OCT == Context->getCanonicalType(Context->getObjCClassType()))
449 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000450
Ted Kremenek6217b802009-07-29 21:53:49 +0000451 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000452 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000453 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff54055232008-10-27 17:20:55 +0000454 return true;
455 }
456 return false;
457 }
458 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Fariborz Jahaniane985d012010-11-03 23:29:24 +0000459 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000460 void GetExtentOfArgList(const char *Name, const char *&LParen,
461 const char *&RParen);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000462
Steve Naroff621edce2009-04-29 16:37:50 +0000463 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump1eb44332009-09-09 15:08:12 +0000464 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroff621edce2009-04-29 16:37:50 +0000465 if (From[i] == '"')
466 To += "\\\"";
467 else
468 To += From[i];
469 }
470 }
John McCalle23cf432010-12-14 08:05:40 +0000471
472 QualType getSimpleFunctionType(QualType result,
473 const QualType *args,
474 unsigned numArgs,
475 bool variadic = false) {
Fariborz Jahanian88914802011-09-09 20:35:22 +0000476 if (result == Context->getObjCInstanceType())
477 result = Context->getObjCIdType();
John McCalle23cf432010-12-14 08:05:40 +0000478 FunctionProtoType::ExtProtoInfo fpi;
479 fpi.Variadic = variadic;
480 return Context->getFunctionType(result, args, numArgs, fpi);
481 }
John McCall9d125032010-01-15 18:39:57 +0000482
Fariborz Jahanian58457172011-12-05 18:43:13 +0000483 // Helper function: create a CStyleCastExpr with trivial type source info.
484 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
485 CastKind Kind, Expr *E) {
486 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
487 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
488 SourceLocation(), SourceLocation());
489 }
490 };
Chris Lattner77cd2a02007-10-11 00:43:27 +0000491}
492
Mike Stump1eb44332009-09-09 15:08:12 +0000493void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
494 NamedDecl *D) {
John McCallf4c73712011-01-19 06:33:43 +0000495 if (const FunctionProtoType *fproto
Abramo Bagnara723df242010-12-14 22:11:44 +0000496 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000497 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000498 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000499 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000500 // All the args are checked/rewritten. Don't call twice!
501 RewriteBlockPointerDecl(D);
502 break;
503 }
504 }
505}
506
507void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000508 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +0000509 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000510 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000511}
512
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000513static bool IsHeaderFile(const std::string &Filename) {
514 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump1eb44332009-09-09 15:08:12 +0000515
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000516 if (DotPos == std::string::npos) {
517 // no file extension
Mike Stump1eb44332009-09-09 15:08:12 +0000518 return false;
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000519 }
Mike Stump1eb44332009-09-09 15:08:12 +0000520
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000521 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
522 // C header: .h
523 // C++ header: .hh or .H;
524 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump1eb44332009-09-09 15:08:12 +0000525}
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000526
Chris Lattner5f9e2722011-07-23 10:55:15 +0000527RewriteObjC::RewriteObjC(std::string inFile, raw_ostream* OS,
David Blaikied6471f72011-09-25 23:23:43 +0000528 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000529 bool silenceMacroWarn)
530 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
531 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000532 IsHeader = IsHeaderFile(inFile);
David Blaikied6471f72011-09-25 23:23:43 +0000533 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000534 "rewriting sub-expression within a macro (may not be correct)");
David Blaikied6471f72011-09-25 23:23:43 +0000535 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
536 DiagnosticsEngine::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000537 "rewriter doesn't support user-specified control flow semantics "
538 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000539}
540
Eli Friedmanbce831b2009-05-18 22:29:17 +0000541ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000542 raw_ostream* OS,
David Blaikied6471f72011-09-25 23:23:43 +0000543 DiagnosticsEngine &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000544 const LangOptions &LOpts,
545 bool SilenceRewriteMacroWarning) {
546 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere365c502007-11-30 22:25:36 +0000547}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000548
Steve Naroffb29b4272008-04-14 22:03:09 +0000549void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000550 Context = &context;
551 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000552 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000553 MsgSendFunctionDecl = 0;
554 MsgSendSuperFunctionDecl = 0;
555 MsgSendStretFunctionDecl = 0;
556 MsgSendSuperStretFunctionDecl = 0;
557 MsgSendFpretFunctionDecl = 0;
558 GetClassFunctionDecl = 0;
559 GetMetaClassFunctionDecl = 0;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000560 GetSuperClassFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000561 SelGetUidFunctionDecl = 0;
562 CFStringFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000563 ConstantStringClassReference = 0;
564 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000565 CurMethodDef = 0;
566 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000567 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000568 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000569 SuperStructDecl = 0;
Steve Naroff621edce2009-04-29 16:37:50 +0000570 ProtocolTypeDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000571 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000572 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000573 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000574 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000575 PropParentMap = 0;
576 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000577 DisableReplaceStmt = false;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000578 objc_impl_method = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000579
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000580 // Get the ID and start/end of the main file.
581 MainFileID = SM->getMainFileID();
582 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
583 MainFileStart = MainBuf->getBufferStart();
584 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000585
Chris Lattner2c78b872009-04-14 23:22:57 +0000586 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump1eb44332009-09-09 15:08:12 +0000587
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000588 // declaring objc_selector outside the parameter list removes a silly
589 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000590 if (IsHeader)
Steve Naroff62c26322009-02-03 20:39:18 +0000591 Preamble = "#pragma once\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000592 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff46a98a72008-12-23 20:11:22 +0000593 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000594 Preamble += "struct objc_object *superClass; ";
Francois Pichet62ec1f22011-09-17 17:15:52 +0000595 if (LangOpts.MicrosoftExt) {
Steve Naroffc0a123c2008-03-11 17:37:02 +0000596 // Add a constructor for creating temporary objects.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000597 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
598 ": ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000599 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000600 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000601 Preamble += "};\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000602 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
603 Preamble += "typedef struct objc_object Protocol;\n";
604 Preamble += "#define _REWRITER_typedef_Protocol\n";
605 Preamble += "#endif\n";
Francois Pichet62ec1f22011-09-17 17:15:52 +0000606 if (LangOpts.MicrosoftExt) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000607 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
608 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
609 } else
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000610 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000611 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000612 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000613 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000614 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Fariborz Jahanian336c8f72011-10-11 23:02:37 +0000615 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000616 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Fariborz Jahanian336c8f72011-10-11 23:02:37 +0000617 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000618 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000619 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000620 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000621 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000622 Preamble += "(const char *);\n";
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000623 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
624 Preamble += "(struct objc_class *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000625 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000626 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000627 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
628 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
629 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
630 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
631 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000632 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000633 // @synchronized hooks.
Steve Naroff4ebd7162008-12-08 17:30:33 +0000634 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
635 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
636 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000637 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
638 Preamble += "struct __objcFastEnumerationState {\n\t";
639 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000640 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000641 Preamble += "unsigned long *mutationsPtr;\n\t";
642 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000643 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000644 Preamble += "#define __FASTENUMERATIONSTATE\n";
645 Preamble += "#endif\n";
646 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
647 Preamble += "struct __NSConstantStringImpl {\n";
648 Preamble += " int *isa;\n";
649 Preamble += " int flags;\n";
650 Preamble += " char *str;\n";
651 Preamble += " long length;\n";
652 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000653 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
654 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
655 Preamble += "#else\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000656 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000657 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000658 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
659 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000660 // Blocks preamble.
661 Preamble += "#ifndef BLOCK_IMPL\n";
662 Preamble += "#define BLOCK_IMPL\n";
663 Preamble += "struct __block_impl {\n";
664 Preamble += " void *isa;\n";
665 Preamble += " int Flags;\n";
Steve Naroff01aec112009-12-06 21:14:13 +0000666 Preamble += " int Reserved;\n";
Steve Naroff54055232008-10-27 17:20:55 +0000667 Preamble += " void *FuncPtr;\n";
668 Preamble += "};\n";
Steve Naroff5bc60d02008-12-16 15:50:30 +0000669 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroffc9c1e9c2009-12-06 01:52:22 +0000670 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000671 Preamble += "extern \"C\" __declspec(dllexport) "
672 "void _Block_object_assign(void *, const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000673 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
674 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
675 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
676 Preamble += "#else\n";
Steve Naroffcd826372010-01-05 18:09:31 +0000677 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
678 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000679 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
680 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
681 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000682 Preamble += "#endif\n";
Francois Pichet62ec1f22011-09-17 17:15:52 +0000683 if (LangOpts.MicrosoftExt) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000684 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
685 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Chris Lattner553e5832010-04-13 17:33:56 +0000686 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
Steve Naroffa48396e2008-10-27 18:50:14 +0000687 Preamble += "#define __attribute__(X)\n";
Chris Lattner553e5832010-04-13 17:33:56 +0000688 Preamble += "#endif\n";
Fariborz Jahanian34204192010-01-15 22:29:39 +0000689 Preamble += "#define __weak\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000690 }
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000691 else {
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000692 Preamble += "#define __block\n";
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000693 Preamble += "#define __weak\n";
694 }
Fariborz Jahaniandf496522010-03-02 01:19:04 +0000695 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
696 // as this avoids warning in any 64bit/32bit compilation model.
697 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000698}
699
700
Chris Lattnerf04da132007-10-24 17:06:59 +0000701//===----------------------------------------------------------------------===//
702// Top Level Driver Code
703//===----------------------------------------------------------------------===//
704
Chris Lattner682bf922009-03-29 16:50:03 +0000705void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremeneke50187a2010-02-05 21:28:51 +0000706 if (Diags.hasErrorOccurred())
707 return;
708
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000709 // Two cases: either the decl could be in the main file, or it could be in a
710 // #included file. If the former, rewrite it now. If the later, check to see
711 // if we rewrote the #include/#import.
712 SourceLocation Loc = D->getLocation();
Chandler Carruth40278532011-07-25 16:49:02 +0000713 Loc = SM->getExpansionLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000714
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000715 // If this is for a builtin, ignore it.
716 if (Loc.isInvalid()) return;
717
Steve Naroffebf2b562007-10-23 23:50:29 +0000718 // Look for built-in declarations that we need to refer during the rewrite.
719 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000720 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000721 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000722 // declared in <Foundation/NSString.h>
Daniel Dunbar4087f272010-08-17 22:39:59 +0000723 if (FVD->getName() == "_NSConstantStringClassReference") {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000724 ConstantStringClassReference = FVD;
725 return;
726 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000727 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000728 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000729 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000730 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000731 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000732 RewriteProtocolDecl(PD);
Mike Stump1eb44332009-09-09 15:08:12 +0000733 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000734 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000735 RewriteForwardProtocolDecl(FP);
Douglas Gregord0434102009-01-09 00:49:46 +0000736 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
737 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000738 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
739 DIEnd = LSD->decls_end();
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000740 DI != DIEnd; ) {
741 if (isa<ObjCClassDecl>((*DI))) {
742 SmallVector<Decl *, 8> DG;
743 Decl *D = (*DI);
744 SourceLocation Loc = D->getLocation();
745 while (DI != DIEnd &&
746 isa<ObjCClassDecl>(D) && D->getLocation() == Loc) {
747 DG.push_back(D);
748 ++DI;
749 D = (*DI);
750 }
751 RewriteForwardClassDecl(DG);
752 continue;
753 }
Chris Lattner682bf922009-03-29 16:50:03 +0000754 HandleTopLevelSingleDecl(*DI);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000755 ++DI;
756 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000757 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000758 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000759 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000760 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000761}
762
Chris Lattnerf04da132007-10-24 17:06:59 +0000763//===----------------------------------------------------------------------===//
764// Syntactic (non-AST) Rewriting Code
765//===----------------------------------------------------------------------===//
766
Steve Naroffb29b4272008-04-14 22:03:09 +0000767void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000768 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000769 StringRef MainBuf = SM->getBufferData(MainFileID);
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000770 const char *MainBufStart = MainBuf.begin();
771 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000772 size_t ImportLen = strlen("import");
Mike Stump1eb44332009-09-09 15:08:12 +0000773
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000774 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000775 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
776 if (*BufPtr == '#') {
777 if (++BufPtr == MainBufEnd)
778 return;
779 while (*BufPtr == ' ' || *BufPtr == '\t')
780 if (++BufPtr == MainBufEnd)
781 return;
782 if (!strncmp(BufPtr, "import", ImportLen)) {
783 // replace import with include
Mike Stump1eb44332009-09-09 15:08:12 +0000784 SourceLocation ImportLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000785 LocStart.getLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000786 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000787 BufPtr += ImportLen;
788 }
789 }
790 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000791}
792
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000793static std::string getIvarAccessString(ObjCIvarDecl *OID) {
794 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000795 std::string S;
796 S = "((struct ";
797 S += ClassDecl->getIdentifier()->getName();
798 S += "_IMPL *)self)->";
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +0000799 S += OID->getName();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000800 return S;
801}
802
Steve Naroffa0876e82008-12-02 17:36:43 +0000803void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
804 ObjCImplementationDecl *IMD,
805 ObjCCategoryImplDecl *CID) {
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000806 static bool objcGetPropertyDefined = false;
807 static bool objcSetPropertyDefined = false;
Steve Naroffd40910b2008-12-01 20:33:01 +0000808 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramerd999b372010-02-14 14:14:16 +0000809 InsertText(startLoc, "// ");
Steve Naroffeb0646c2008-12-02 15:48:25 +0000810 const char *startBuf = SM->getCharacterData(startLoc);
811 assert((*startBuf == '@') && "bogus @synthesize location");
812 const char *semiBuf = strchr(startBuf, ';');
813 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000814 SourceLocation onePastSemiLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000815 startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000816
817 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
818 return; // FIXME: is this correct?
Mike Stump1eb44332009-09-09 15:08:12 +0000819
Steve Naroffeb0646c2008-12-02 15:48:25 +0000820 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000821 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000822 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000823
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000824 if (!OID)
825 return;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000826 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000827 if (!PD->getGetterMethodDecl()->isDefined()) {
828 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
829 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
830 ObjCPropertyDecl::OBJC_PR_copy));
831 std::string Getr;
832 if (GenGetProperty && !objcGetPropertyDefined) {
833 objcGetPropertyDefined = true;
834 // FIXME. Is this attribute correct in all cases?
835 Getr = "\nextern \"C\" __declspec(dllimport) "
836 "id objc_getProperty(id, SEL, long, bool);\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000837 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000838 RewriteObjCMethodDecl(OID->getContainingInterface(),
839 PD->getGetterMethodDecl(), Getr);
840 Getr += "{ ";
841 // Synthesize an explicit cast to gain access to the ivar.
842 // See objc-act.c:objc_synthesize_new_getter() for details.
843 if (GenGetProperty) {
844 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
845 Getr += "typedef ";
846 const FunctionType *FPRetType = 0;
847 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
848 FPRetType);
849 Getr += " _TYPE";
850 if (FPRetType) {
851 Getr += ")"; // close the precedence "scope" for "*".
852
853 // Now, emit the argument types (if any).
854 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
855 Getr += "(";
856 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
857 if (i) Getr += ", ";
858 std::string ParamStr = FT->getArgType(i).getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +0000859 Context->getPrintingPolicy());
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000860 Getr += ParamStr;
861 }
862 if (FT->isVariadic()) {
863 if (FT->getNumArgs()) Getr += ", ";
864 Getr += "...";
865 }
866 Getr += ")";
867 } else
868 Getr += "()";
869 }
870 Getr += ";\n";
871 Getr += "return (_TYPE)";
872 Getr += "objc_getProperty(self, _cmd, ";
Fariborz Jahanian58457172011-12-05 18:43:13 +0000873 RewriteIvarOffsetComputation(OID, Getr);
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000874 Getr += ", 1)";
875 }
876 else
877 Getr += "return " + getIvarAccessString(OID);
878 Getr += "; }";
879 InsertText(onePastSemiLoc, Getr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000880 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000881
882 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
Steve Naroffeb0646c2008-12-02 15:48:25 +0000883 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000884
Steve Naroffeb0646c2008-12-02 15:48:25 +0000885 // Generate the 'setter' function.
886 std::string Setr;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000887 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
888 ObjCPropertyDecl::OBJC_PR_copy);
889 if (GenSetProperty && !objcSetPropertyDefined) {
890 objcSetPropertyDefined = true;
891 // FIXME. Is this attribute correct in all cases?
892 Setr = "\nextern \"C\" __declspec(dllimport) "
893 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
894 }
895
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000896 RewriteObjCMethodDecl(OID->getContainingInterface(),
897 PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000898 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000899 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff15f081d2008-12-03 00:56:33 +0000900 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000901 if (GenSetProperty) {
902 Setr += "objc_setProperty (self, _cmd, ";
Fariborz Jahanian58457172011-12-05 18:43:13 +0000903 RewriteIvarOffsetComputation(OID, Setr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000904 Setr += ", (id)";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000905 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000906 Setr += ", ";
907 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
908 Setr += "0, ";
909 else
910 Setr += "1, ";
911 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
912 Setr += "1)";
913 else
914 Setr += "0)";
915 }
916 else {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000917 Setr += getIvarAccessString(OID) + " = ";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000918 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000919 }
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000920 Setr += "; }";
Benjamin Kramerd999b372010-02-14 14:14:16 +0000921 InsertText(onePastSemiLoc, Setr);
Steve Naroffd40910b2008-12-01 20:33:01 +0000922}
Chris Lattner8a12c272007-10-11 18:38:32 +0000923
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000924static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
925 std::string &typedefString) {
926 typedefString += "#ifndef _REWRITER_typedef_";
927 typedefString += ForwardDecl->getNameAsString();
928 typedefString += "\n";
929 typedefString += "#define _REWRITER_typedef_";
930 typedefString += ForwardDecl->getNameAsString();
931 typedefString += "\n";
932 typedefString += "typedef struct objc_object ";
933 typedefString += ForwardDecl->getNameAsString();
934 typedefString += ";\n#endif\n";
935}
936
937void RewriteObjC::RewriteForwardClassEpilogue(ObjCClassDecl *ClassDecl,
938 const std::string &typedefString) {
939 SourceLocation startLoc = ClassDecl->getLocation();
940 const char *startBuf = SM->getCharacterData(startLoc);
941 const char *semiPtr = strchr(startBuf, ';');
942 // Replace the @class with typedefs corresponding to the classes.
943 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
944}
945
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000946void RewriteObjC::RewriteForwardClassDecl(DeclGroupRef D) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000947 std::string typedefString;
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000948 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
949 ObjCClassDecl *ClassDecl = cast<ObjCClassDecl>(*I);
950 ObjCInterfaceDecl *ForwardDecl = ClassDecl->getForwardInterfaceDecl();
951 if (I == D.begin()) {
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000952 // Translate to typedef's that forward reference structs with the same name
953 // as the class. As a convenience, we include the original declaration
954 // as a comment.
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000955 typedefString += "// @class ";
956 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian91fbd122010-01-11 22:48:40 +0000957 typedefString += ";\n";
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000958 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000959 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
Steve Naroff934f2762007-10-24 22:48:43 +0000960 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000961 DeclGroupRef::iterator I = D.begin();
962 RewriteForwardClassEpilogue(cast<ObjCClassDecl>(*I), typedefString);
963}
Mike Stump1eb44332009-09-09 15:08:12 +0000964
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000965void RewriteObjC::RewriteForwardClassDecl(
966 const llvm::SmallVector<Decl*, 8> &D) {
967 std::string typedefString;
968 for (unsigned i = 0; i < D.size(); i++) {
969 ObjCClassDecl *ClassDecl = cast<ObjCClassDecl>(D[i]);
970 ObjCInterfaceDecl *ForwardDecl = ClassDecl->getForwardInterfaceDecl();
971 if (i == 0) {
972 typedefString += "// @class ";
973 typedefString += ForwardDecl->getNameAsString();
974 typedefString += ";\n";
975 }
976 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
977 }
978 RewriteForwardClassEpilogue(cast<ObjCClassDecl>(D[0]), typedefString);
Chris Lattnerf04da132007-10-24 17:06:59 +0000979}
980
Steve Naroffb29b4272008-04-14 22:03:09 +0000981void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000982 // When method is a synthesized one, such as a getter/setter there is
983 // nothing to rewrite.
Fariborz Jahanian88914802011-09-09 20:35:22 +0000984 if (Method->isImplicit())
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000985 return;
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000986 SourceLocation LocStart = Method->getLocStart();
987 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000988
Chandler Carruth64211622011-07-25 21:09:52 +0000989 if (SM->getExpansionLineNumber(LocEnd) >
990 SM->getExpansionLineNumber(LocStart)) {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000991 InsertText(LocStart, "#if 0\n");
992 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000993 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000994 InsertText(LocStart, "// ");
Steve Naroff423cb562007-10-30 13:30:57 +0000995 }
996}
997
Mike Stump1eb44332009-09-09 15:08:12 +0000998void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000999 SourceLocation Loc = prop->getAtLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001000
Benjamin Kramerd999b372010-02-14 14:14:16 +00001001 ReplaceText(Loc, 0, "// ");
Steve Naroff6327e0d2009-01-11 01:06:09 +00001002 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +00001003}
1004
Steve Naroffb29b4272008-04-14 22:03:09 +00001005void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +00001006 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001007
Steve Naroff423cb562007-10-30 13:30:57 +00001008 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001009 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001010
Fariborz Jahanian13751e32010-02-10 01:15:09 +00001011 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
1012 E = CatDecl->prop_end(); I != E; ++I)
1013 RewriteProperty(*I);
1014
Mike Stump1eb44332009-09-09 15:08:12 +00001015 for (ObjCCategoryDecl::instmeth_iterator
1016 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001017 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001018 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001019 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001020 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001021 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001022 RewriteMethodDeclaration(*I);
1023
Steve Naroff423cb562007-10-30 13:30:57 +00001024 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001025 ReplaceText(CatDecl->getAtEndRange().getBegin(),
1026 strlen("@end"), "/* @end */");
Steve Naroff423cb562007-10-30 13:30:57 +00001027}
1028
Steve Naroffb29b4272008-04-14 22:03:09 +00001029void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Naroff752d6ef2007-10-30 16:42:30 +00001030 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001031
Steve Naroff752d6ef2007-10-30 16:42:30 +00001032 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001033 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001034
1035 for (ObjCProtocolDecl::instmeth_iterator
1036 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001037 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001038 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001039 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001040 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001041 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001042 RewriteMethodDeclaration(*I);
1043
Fariborz Jahanian07acdf42010-09-24 18:36:58 +00001044 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1045 E = PDecl->prop_end(); I != E; ++I)
1046 RewriteProperty(*I);
1047
Steve Naroff752d6ef2007-10-30 16:42:30 +00001048 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +00001049 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001050 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroff8cc764c2007-11-14 15:03:57 +00001051
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001052 // Must comment out @optional/@required
1053 const char *startBuf = SM->getCharacterData(LocStart);
1054 const char *endBuf = SM->getCharacterData(LocEnd);
1055 for (const char *p = startBuf; p < endBuf; p++) {
1056 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001057 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001058 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump1eb44332009-09-09 15:08:12 +00001059
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001060 }
1061 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001062 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001063 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump1eb44332009-09-09 15:08:12 +00001064
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001065 }
1066 }
Steve Naroff752d6ef2007-10-30 16:42:30 +00001067}
1068
Steve Naroffb29b4272008-04-14 22:03:09 +00001069void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001070 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +00001071 if (LocStart.isInvalid())
David Blaikieb219cfc2011-09-23 05:06:16 +00001072 llvm_unreachable("Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001073 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001074 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001075}
1076
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001077void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1078 const FunctionType *&FPRetType) {
1079 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001080 ResultStr += "id";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001081 else if (T->isFunctionPointerType() ||
1082 T->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001083 // needs special handling, since pointer-to-functions have special
1084 // syntax (where a decaration models use).
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001085 QualType retType = T;
Steve Narofff4312dc2008-12-11 19:29:16 +00001086 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001087 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001088 PointeeTy = PT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001089 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001090 PointeeTy = BPT->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001091 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001092 ResultStr += FPRetType->getResultType().getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +00001093 Context->getPrintingPolicy());
Steve Narofff4312dc2008-12-11 19:29:16 +00001094 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +00001095 }
1096 } else
Douglas Gregor30c42402011-09-27 22:38:19 +00001097 ResultStr += T.getAsString(Context->getPrintingPolicy());
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001098}
1099
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001100void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1101 ObjCMethodDecl *OMD,
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001102 std::string &ResultStr) {
1103 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1104 const FunctionType *FPRetType = 0;
1105 ResultStr += "\nstatic ";
1106 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001107 ResultStr += " ";
Mike Stump1eb44332009-09-09 15:08:12 +00001108
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001109 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001110 std::string NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001111
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001112 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001113 NameStr += "_I_";
1114 else
1115 NameStr += "_C_";
Mike Stump1eb44332009-09-09 15:08:12 +00001116
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001117 NameStr += IDecl->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001118 NameStr += "_";
Mike Stump1eb44332009-09-09 15:08:12 +00001119
1120 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +00001121 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001122 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001123 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001124 }
Mike Stump1eb44332009-09-09 15:08:12 +00001125 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +00001126 {
1127 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001128 int len = selString.size();
1129 for (int i = 0; i < len; i++)
1130 if (selString[i] == ':')
1131 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001132 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001133 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001134 // Remember this name for metadata emission
1135 MethodInternalNames[OMD] = NameStr;
1136 ResultStr += NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001137
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001138 // Rewrite arguments
1139 ResultStr += "(";
Mike Stump1eb44332009-09-09 15:08:12 +00001140
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001141 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001142 if (OMD->isInstanceMethod()) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001143 QualType selfTy = Context->getObjCInterfaceType(IDecl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001144 selfTy = Context->getPointerType(selfTy);
Francois Pichet62ec1f22011-09-17 17:15:52 +00001145 if (!LangOpts.MicrosoftExt) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001146 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
Steve Naroff05b8c782008-03-12 00:25:36 +00001147 ResultStr += "struct ";
1148 }
1149 // When rewriting for Microsoft, explicitly omit the structure name.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001150 ResultStr += IDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001151 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001152 }
1153 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001154 ResultStr += Context->getObjCClassType().getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +00001155 Context->getPrintingPolicy());
Mike Stump1eb44332009-09-09 15:08:12 +00001156
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001157 ResultStr += " self, ";
Douglas Gregor30c42402011-09-27 22:38:19 +00001158 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001159 ResultStr += " _cmd";
Mike Stump1eb44332009-09-09 15:08:12 +00001160
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001161 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +00001162 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1163 E = OMD->param_end(); PI != E; ++PI) {
1164 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001165 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +00001166 if (PDecl->getType()->isObjCQualifiedIdType()) {
1167 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001168 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +00001169 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001170 std::string Name = PDecl->getNameAsString();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00001171 QualType QT = PDecl->getType();
1172 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1173 if (convertBlockPointerToFunctionPointer(QT))
Douglas Gregor30c42402011-09-27 22:38:19 +00001174 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00001175 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001176 PDecl->getType().getAsStringInternal(Name, Context->getPrintingPolicy());
Steve Naroff543409e2008-04-18 21:13:19 +00001177 ResultStr += Name;
1178 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001179 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +00001180 if (OMD->isVariadic())
1181 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001182 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +00001183
Steve Naroff76e429d2008-07-16 14:40:40 +00001184 if (FPRetType) {
1185 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +00001186
Steve Naroff76e429d2008-07-16 14:40:40 +00001187 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +00001188 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001189 ResultStr += "(";
1190 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1191 if (i) ResultStr += ", ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001192 std::string ParamStr = FT->getArgType(i).getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +00001193 Context->getPrintingPolicy());
Steve Naroff76e429d2008-07-16 14:40:40 +00001194 ResultStr += ParamStr;
1195 }
1196 if (FT->isVariadic()) {
1197 if (FT->getNumArgs()) ResultStr += ", ";
1198 ResultStr += "...";
1199 }
1200 ResultStr += ")";
1201 } else {
1202 ResultStr += "()";
1203 }
1204 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001205}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001206void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001207 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1208 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001209
Fariborz Jahaniana1352162010-02-15 21:11:41 +00001210 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001211
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001212 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001213 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1214 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001215 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001216 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001217 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001218 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001219 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001220 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001221
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001222 const char *startBuf = SM->getCharacterData(LocStart);
1223 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001224 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001225 }
Mike Stump1eb44332009-09-09 15:08:12 +00001226
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001227 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001228 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1229 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001230 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001231 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001232 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001233 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001234 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001235 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001236
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001237 const char *startBuf = SM->getCharacterData(LocStart);
1238 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001239 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001240 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001241 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001242 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001243 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001244 I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001245 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001246 }
1247
Benjamin Kramerd999b372010-02-14 14:14:16 +00001248 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001249}
1250
Steve Naroffb29b4272008-04-14 22:03:09 +00001251void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001252 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001253 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001254 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001255 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001256 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001257 ResultStr += "\n";
1258 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001259 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001260 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001261 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001262 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001263 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001264 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001265 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001266 }
Fariborz Jahanian58457172011-12-05 18:43:13 +00001267 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001268
1269 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001270 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff6327e0d2009-01-11 01:06:09 +00001271 RewriteProperty(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001272 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001273 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001274 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001275 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001276 for (ObjCInterfaceDecl::classmeth_iterator
1277 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001278 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001279 RewriteMethodDeclaration(*I);
1280
Steve Naroff2feac5e2007-10-30 03:43:13 +00001281 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001282 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1283 "/* @end */");
Steve Naroffbef11852007-10-26 20:53:56 +00001284}
1285
John McCall4b9c2d22011-11-06 09:01:30 +00001286Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1287 SourceRange OldRange = PseudoOp->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001288
John McCall4b9c2d22011-11-06 09:01:30 +00001289 // We just magically know some things about the structure of this
1290 // expression.
1291 ObjCMessageExpr *OldMsg =
1292 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1293 PseudoOp->getNumSemanticExprs() - 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001294
John McCall4b9c2d22011-11-06 09:01:30 +00001295 // Because the rewriter doesn't allow us to rewrite rewritten code,
1296 // we need to suppress rewriting the sub-statements.
1297 Expr *Base, *RHS;
1298 {
1299 DisableReplaceStmtScope S(*this);
1300
1301 // Rebuild the base expression if we have one.
1302 Base = 0;
1303 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1304 Base = OldMsg->getInstanceReceiver();
1305 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1306 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1307 }
1308
1309 // Rebuild the RHS.
1310 RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1311 RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1312 RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1313 }
1314
1315 // TODO: avoid this copy.
1316 SmallVector<SourceLocation, 1> SelLocs;
1317 OldMsg->getSelectorLocs(SelLocs);
1318
1319 ObjCMessageExpr *NewMsg;
1320 switch (OldMsg->getReceiverKind()) {
1321 case ObjCMessageExpr::Class:
1322 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1323 OldMsg->getValueKind(),
1324 OldMsg->getLeftLoc(),
1325 OldMsg->getClassReceiverTypeInfo(),
1326 OldMsg->getSelector(),
1327 SelLocs,
1328 OldMsg->getMethodDecl(),
1329 RHS,
1330 OldMsg->getRightLoc());
1331 break;
1332
1333 case ObjCMessageExpr::Instance:
1334 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1335 OldMsg->getValueKind(),
1336 OldMsg->getLeftLoc(),
1337 Base,
1338 OldMsg->getSelector(),
1339 SelLocs,
1340 OldMsg->getMethodDecl(),
1341 RHS,
1342 OldMsg->getRightLoc());
1343 break;
1344
1345 case ObjCMessageExpr::SuperClass:
1346 case ObjCMessageExpr::SuperInstance:
1347 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1348 OldMsg->getValueKind(),
1349 OldMsg->getLeftLoc(),
1350 OldMsg->getSuperLoc(),
1351 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1352 OldMsg->getSuperType(),
1353 OldMsg->getSelector(),
1354 SelLocs,
1355 OldMsg->getMethodDecl(),
1356 RHS,
1357 OldMsg->getRightLoc());
1358 break;
1359 }
1360
1361 Stmt *Replacement = SynthMessageExpr(NewMsg);
1362 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1363 return Replacement;
Steve Naroff15f081d2008-12-03 00:56:33 +00001364}
1365
John McCall4b9c2d22011-11-06 09:01:30 +00001366Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1367 SourceRange OldRange = PseudoOp->getSourceRange();
1368
1369 // We just magically know some things about the structure of this
1370 // expression.
1371 ObjCMessageExpr *OldMsg =
1372 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1373
1374 // Because the rewriter doesn't allow us to rewrite rewritten code,
1375 // we need to suppress rewriting the sub-statements.
1376 Expr *Base = 0;
1377 {
1378 DisableReplaceStmtScope S(*this);
1379
1380 // Rebuild the base expression if we have one.
1381 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1382 Base = OldMsg->getInstanceReceiver();
1383 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1384 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
John McCall12f78a62010-12-02 01:19:52 +00001385 }
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001386 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001387
John McCall4b9c2d22011-11-06 09:01:30 +00001388 // Intentionally empty.
1389 SmallVector<SourceLocation, 1> SelLocs;
1390 SmallVector<Expr*, 1> Args;
Steve Naroff8599e7a2008-12-08 16:43:47 +00001391
John McCall4b9c2d22011-11-06 09:01:30 +00001392 ObjCMessageExpr *NewMsg;
1393 switch (OldMsg->getReceiverKind()) {
1394 case ObjCMessageExpr::Class:
1395 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1396 OldMsg->getValueKind(),
1397 OldMsg->getLeftLoc(),
1398 OldMsg->getClassReceiverTypeInfo(),
1399 OldMsg->getSelector(),
1400 SelLocs,
1401 OldMsg->getMethodDecl(),
1402 Args,
1403 OldMsg->getRightLoc());
1404 break;
1405
1406 case ObjCMessageExpr::Instance:
1407 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1408 OldMsg->getValueKind(),
1409 OldMsg->getLeftLoc(),
1410 Base,
1411 OldMsg->getSelector(),
1412 SelLocs,
1413 OldMsg->getMethodDecl(),
1414 Args,
1415 OldMsg->getRightLoc());
1416 break;
1417
1418 case ObjCMessageExpr::SuperClass:
1419 case ObjCMessageExpr::SuperInstance:
1420 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1421 OldMsg->getValueKind(),
1422 OldMsg->getLeftLoc(),
1423 OldMsg->getSuperLoc(),
1424 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1425 OldMsg->getSuperType(),
1426 OldMsg->getSelector(),
1427 SelLocs,
1428 OldMsg->getMethodDecl(),
1429 Args,
1430 OldMsg->getRightLoc());
1431 break;
Steve Naroff8599e7a2008-12-08 16:43:47 +00001432 }
John McCall4b9c2d22011-11-06 09:01:30 +00001433
1434 Stmt *Replacement = SynthMessageExpr(NewMsg);
1435 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1436 return Replacement;
Steve Naroff15f081d2008-12-03 00:56:33 +00001437}
1438
John McCall4b9c2d22011-11-06 09:01:30 +00001439Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
1440 SourceRange OldRange = IV->getSourceRange();
1441 Expr *BaseExpr = IV->getBase();
1442
1443 // Rewrite the base, but without actually doing replaces.
1444 {
1445 DisableReplaceStmtScope S(*this);
1446 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
1447 IV->setBase(BaseExpr);
1448 }
1449
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001450 ObjCIvarDecl *D = IV->getDecl();
John McCall4b9c2d22011-11-06 09:01:30 +00001451
1452 Expr *Replacement = IV;
Steve Naroff54055232008-10-27 17:20:55 +00001453 if (CurMethodDef) {
Fariborz Jahanian8f095432010-01-26 18:28:51 +00001454 if (BaseExpr->getType()->isObjCObjectPointerType()) {
John McCallf4c73712011-01-19 06:33:43 +00001455 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001456 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianffbdead2010-01-26 20:37:44 +00001457 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Narofff0757612008-05-08 17:52:16 +00001458 // lookup which class implements the instance variable.
1459 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001460 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001461 clsDeclared);
Steve Narofff0757612008-05-08 17:52:16 +00001462 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001463
Steve Narofff0757612008-05-08 17:52:16 +00001464 // Synthesize an explicit cast to gain access to the ivar.
1465 std::string RecName = clsDeclared->getIdentifier()->getName();
1466 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001467 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001468 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001469 SourceLocation(), SourceLocation(),
1470 II);
Steve Narofff0757612008-05-08 17:52:16 +00001471 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1472 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001473 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCalla5bbc502010-11-15 09:46:46 +00001474 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00001475 IV->getBase());
Steve Narofff0757612008-05-08 17:52:16 +00001476 // Don't forget the parens to enforce the proper binding.
John McCall4b9c2d22011-11-06 09:01:30 +00001477 ParenExpr *PE = new (Context) ParenExpr(OldRange.getBegin(),
1478 OldRange.getEnd(),
John McCallf89e55a2010-11-18 06:31:45 +00001479 castExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001480 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001481 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001482 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
John McCallf89e55a2010-11-18 06:31:45 +00001483 IV->getLocation(),
1484 D->getType(),
1485 VK_LValue, OK_Ordinary);
John McCall4b9c2d22011-11-06 09:01:30 +00001486 Replacement = ME;
1487 } else {
1488 IV->setBase(PE);
Steve Naroffc2a689b2007-11-15 11:33:00 +00001489 }
1490 }
Steve Naroff84472a82008-04-18 21:55:08 +00001491 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001492 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump1eb44332009-09-09 15:08:12 +00001493
Steve Naroff9f525972008-05-06 23:20:07 +00001494 // Explicit ivar refs need to have a cast inserted.
1495 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian26337b22010-01-12 17:31:23 +00001496 if (BaseExpr->getType()->isObjCObjectPointerType()) {
John McCallf4c73712011-01-19 06:33:43 +00001497 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanianc374cd92010-01-11 17:50:35 +00001498 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001499 // lookup which class implements the instance variable.
1500 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001501 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001502 clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001503 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001504
Steve Naroff9f525972008-05-06 23:20:07 +00001505 // Synthesize an explicit cast to gain access to the ivar.
1506 std::string RecName = clsDeclared->getIdentifier()->getName();
1507 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001508 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001509 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001510 SourceLocation(), SourceLocation(),
1511 II);
Steve Naroff9f525972008-05-06 23:20:07 +00001512 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1513 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001514 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCalla5bbc502010-11-15 09:46:46 +00001515 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00001516 IV->getBase());
Steve Naroff9f525972008-05-06 23:20:07 +00001517 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001518 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner8d366162008-05-28 16:38:23 +00001519 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff9f525972008-05-06 23:20:07 +00001520 // Cannot delete IV->getBase(), since PE points to it.
1521 // Replace the old base with the cast. This is important when doing
1522 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001523 IV->setBase(PE);
Steve Naroff9f525972008-05-06 23:20:07 +00001524 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001525 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00001526
John McCall4b9c2d22011-11-06 09:01:30 +00001527 ReplaceStmtWithRange(IV, Replacement, OldRange);
1528 return Replacement;
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001529}
1530
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001531/// SynthCountByEnumWithState - To print:
1532/// ((unsigned int (*)
1533/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001534/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001535/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001536/// "countByEnumeratingWithState:objects:count:"),
1537/// &enumState,
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001538/// (id *)__rw_items, (unsigned int)16)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001539///
Steve Naroffb29b4272008-04-14 22:03:09 +00001540void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001541 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1542 "id *, unsigned int))(void *)objc_msgSend)";
1543 buf += "\n\t\t";
1544 buf += "((id)l_collection,\n\t\t";
1545 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1546 buf += "\n\t\t";
1547 buf += "&enumState, "
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001548 "(id *)__rw_items, (unsigned int)16)";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001549}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001550
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001551/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1552/// statement to exit to its outer synthesized loop.
1553///
Steve Naroffb29b4272008-04-14 22:03:09 +00001554Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001555 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1556 return S;
1557 // replace break with goto __break_label
1558 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001559
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001560 SourceLocation startLoc = S->getLocStart();
1561 buf = "goto __break_label_";
1562 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001563 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001564
1565 return 0;
1566}
1567
1568/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1569/// statement to continue with its inner synthesized loop.
1570///
Steve Naroffb29b4272008-04-14 22:03:09 +00001571Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001572 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1573 return S;
1574 // replace continue with goto __continue_label
1575 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001576
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001577 SourceLocation startLoc = S->getLocStart();
1578 buf = "goto __continue_label_";
1579 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001580 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001581
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001582 return 0;
1583}
1584
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001585/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001586/// It rewrites:
1587/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001588
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001589/// Into:
1590/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001591/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001592/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001593/// id __rw_items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001594/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001595/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001596/// objects:__rw_items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001597/// if (limit) {
1598/// unsigned long startMutations = *enumState.mutationsPtr;
1599/// do {
1600/// unsigned long counter = 0;
1601/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001602/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001603/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001604/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001605/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001606/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001607/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001608/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001609/// objects:__rw_items count:16]);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001610/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001611/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001612/// }
1613/// else
1614/// elem = nil;
1615/// }
1616///
Steve Naroffb29b4272008-04-14 22:03:09 +00001617Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001618 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001619 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001620 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001621 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001622 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001623 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001624
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001625 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001626 const char *startBuf = SM->getCharacterData(startLoc);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001627 StringRef elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001628 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001629 std::string buf;
1630 buf = "\n{\n\t";
1631 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1632 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001633 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001634 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001635 if (ElementType->isObjCQualifiedIdType() ||
1636 ElementType->isObjCQualifiedInterfaceType())
1637 // Simply use 'id' for all qualified types.
1638 elementTypeAsString = "id";
1639 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001640 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001641 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001642 buf += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00001643 elementName = D->getName();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001644 buf += elementName;
1645 buf += ";\n\t";
1646 }
Chris Lattner06767512008-04-08 05:52:18 +00001647 else {
1648 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar4087f272010-08-17 22:39:59 +00001649 elementName = DR->getDecl()->getName();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001650 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1651 if (VD->getType()->isObjCQualifiedIdType() ||
1652 VD->getType()->isObjCQualifiedInterfaceType())
1653 // Simply use 'id' for all qualified types.
1654 elementTypeAsString = "id";
1655 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001656 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001657 }
Mike Stump1eb44332009-09-09 15:08:12 +00001658
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001659 // struct __objcFastEnumerationState enumState = { 0 };
1660 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001661 // id __rw_items[16];
1662 buf += "id __rw_items[16];\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001663 // id l_collection = (id)
1664 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001665 // Find start location of 'collection' the hard way!
1666 const char *startCollectionBuf = startBuf;
1667 startCollectionBuf += 3; // skip 'for'
1668 startCollectionBuf = strchr(startCollectionBuf, '(');
1669 startCollectionBuf++; // skip '('
1670 // find 'in' and skip it.
1671 while (*startCollectionBuf != ' ' ||
1672 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1673 (*(startCollectionBuf+3) != ' ' &&
1674 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1675 startCollectionBuf++;
1676 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001677
1678 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001679 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001680 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001681 SourceLocation rightParenLoc = S->getRParenLoc();
1682 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001683 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001684 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001685
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001686 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001687 // objects:__rw_items count:16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001688 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001689 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001690 // ((unsigned int (*)
1691 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001692 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001693 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001694 // "countByEnumeratingWithState:objects:count:"),
1695 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001696 // (id *)__rw_items, (unsigned int)16);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001697 buf += "unsigned long limit =\n\t\t";
1698 SynthCountByEnumWithState(buf);
1699 buf += ";\n\t";
1700 /// if (limit) {
1701 /// unsigned long startMutations = *enumState.mutationsPtr;
1702 /// do {
1703 /// unsigned long counter = 0;
1704 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001705 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001706 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001707 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001708 buf += "if (limit) {\n\t";
1709 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1710 buf += "do {\n\t\t";
1711 buf += "unsigned long counter = 0;\n\t\t";
1712 buf += "do {\n\t\t\t";
1713 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1714 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1715 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001716 buf += " = (";
1717 buf += elementTypeAsString;
1718 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001719 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001720 ReplaceText(lparenLoc, 1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001721
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001722 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001723 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001724 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001725 /// objects:__rw_items count:16]);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001726 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001727 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001728 /// }
1729 /// else
1730 /// elem = nil;
1731 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001732 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001733 buf = ";\n\t";
1734 buf += "__continue_label_";
1735 buf += utostr(ObjCBcLabelNo.back());
1736 buf += ": ;";
1737 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001738 buf += "} while (counter < limit);\n\t";
1739 buf += "} while (limit = ";
1740 SynthCountByEnumWithState(buf);
1741 buf += ");\n\t";
1742 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001743 buf += " = ((";
1744 buf += elementTypeAsString;
1745 buf += ")0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001746 buf += "__break_label_";
1747 buf += utostr(ObjCBcLabelNo.back());
1748 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001749 buf += "}\n\t";
1750 buf += "else\n\t\t";
1751 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001752 buf += " = ((";
1753 buf += elementTypeAsString;
1754 buf += ")0);\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001755 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001756
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001757 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001758 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001759 if (isa<CompoundStmt>(S->getBody())) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001760 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001761 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001762 } else {
1763 /* Need to treat single statements specially. For example:
1764 *
1765 * for (A *a in b) if (stuff()) break;
1766 * for (A *a in b) xxxyy;
1767 *
1768 * The following code simply scans ahead to the semi to find the actual end.
1769 */
1770 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1771 const char *semiBuf = strchr(stmtBuf, ';');
1772 assert(semiBuf && "Can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001773 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001774 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001775 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001776 Stmts.pop_back();
1777 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001778 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001779}
1780
Mike Stump1eb44332009-09-09 15:08:12 +00001781/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001782/// This routine rewrites @synchronized(expr) stmt;
1783/// into:
1784/// objc_sync_enter(expr);
1785/// @try stmt @finally { objc_sync_exit(expr); }
1786///
Steve Naroffb29b4272008-04-14 22:03:09 +00001787Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001788 // Get the start location and compute the semi location.
1789 SourceLocation startLoc = S->getLocStart();
1790 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001791
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001792 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001793
1794 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001795 buf = "objc_sync_enter((id)";
1796 const char *lparenBuf = startBuf;
1797 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramerd999b372010-02-14 14:14:16 +00001798 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001799 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1800 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001801 // been rewritten! (which implies the SourceLocation's are invalid).
1802 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001803 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001804 while (*endBuf != ')') endBuf--;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001805 SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001806 buf = ");\n";
1807 // declare a new scope with two variables, _stack and _rethrow.
1808 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1809 buf += "int buf[18/*32-bit i386*/];\n";
1810 buf += "char *pointers[4];} _stack;\n";
1811 buf += "id volatile _rethrow = 0;\n";
1812 buf += "objc_exception_try_enter(&_stack);\n";
1813 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001814 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001815 startLoc = S->getSynchBody()->getLocEnd();
1816 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001817
Steve Naroffc7089f12008-08-19 13:04:19 +00001818 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001819 SourceLocation lastCurlyLoc = startLoc;
1820 buf = "}\nelse {\n";
1821 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001822 buf += "}\n";
1823 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001824 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001825
1826 std::string syncBuf;
1827 syncBuf += " objc_sync_exit(";
John McCall1d9b3b22011-09-09 05:25:32 +00001828
1829 Expr *syncExpr = S->getSynchExpr();
1830 CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
1831 ? CK_BitCast :
1832 syncExpr->getType()->isBlockPointerType()
1833 ? CK_BlockPointerToObjCPointerCast
1834 : CK_CPointerToObjCPointerCast;
1835 syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1836 CK, syncExpr);
Ted Kremeneka95d3752008-09-13 05:16:45 +00001837 std::string syncExprBufS;
1838 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00001839 syncExpr->printPretty(syncExprBuf, *Context, 0,
1840 PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001841 syncBuf += syncExprBuf.str();
1842 syncBuf += ");";
1843
1844 buf += syncBuf;
1845 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001846 buf += "}\n";
1847 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001848
Benjamin Kramerd999b372010-02-14 14:14:16 +00001849 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001850
1851 bool hasReturns = false;
1852 HasReturnStmts(S->getSynchBody(), hasReturns);
1853 if (hasReturns)
1854 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1855
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001856 return 0;
1857}
1858
Steve Naroffb85e77a2009-12-05 21:43:12 +00001859void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1860{
Steve Naroff8c565152008-12-05 17:03:39 +00001861 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001862 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff8c565152008-12-05 17:03:39 +00001863 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001864 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001865
Steve Naroffb85e77a2009-12-05 21:43:12 +00001866 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001867 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001868 TryFinallyContainsReturnDiag);
1869 }
1870 return;
1871}
1872
Steve Naroffb85e77a2009-12-05 21:43:12 +00001873void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1874{
1875 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001876 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001877 if (*CI)
1878 HasReturnStmts(*CI, hasReturns);
1879
1880 if (isa<ReturnStmt>(S))
1881 hasReturns = true;
1882 return;
1883}
1884
1885void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1886 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001887 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001888 if (*CI) {
1889 RewriteTryReturnStmts(*CI);
1890 }
1891 if (isa<ReturnStmt>(S)) {
1892 SourceLocation startLoc = S->getLocStart();
1893 const char *startBuf = SM->getCharacterData(startLoc);
1894
1895 const char *semiBuf = strchr(startBuf, ';');
1896 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001897 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001898
1899 std::string buf;
1900 buf = "{ objc_exception_try_exit(&_stack); return";
1901
Benjamin Kramerd999b372010-02-14 14:14:16 +00001902 ReplaceText(startLoc, 6, buf);
1903 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001904 }
1905 return;
1906}
1907
1908void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1909 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001910 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001911 if (*CI) {
1912 RewriteSyncReturnStmts(*CI, syncExitBuf);
1913 }
1914 if (isa<ReturnStmt>(S)) {
1915 SourceLocation startLoc = S->getLocStart();
1916 const char *startBuf = SM->getCharacterData(startLoc);
1917
1918 const char *semiBuf = strchr(startBuf, ';');
1919 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001920 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001921
1922 std::string buf;
1923 buf = "{ objc_exception_try_exit(&_stack);";
1924 buf += syncExitBuf;
1925 buf += " return";
1926
Benjamin Kramerd999b372010-02-14 14:14:16 +00001927 ReplaceText(startLoc, 6, buf);
1928 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001929 }
1930 return;
1931}
1932
Steve Naroffb29b4272008-04-14 22:03:09 +00001933Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001934 // Get the start location and compute the semi location.
1935 SourceLocation startLoc = S->getLocStart();
1936 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001937
Steve Naroff75730982007-11-07 04:08:17 +00001938 assert((*startBuf == '@') && "bogus @try location");
1939
1940 std::string buf;
1941 // declare a new scope with two variables, _stack and _rethrow.
1942 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1943 buf += "int buf[18/*32-bit i386*/];\n";
1944 buf += "char *pointers[4];} _stack;\n";
1945 buf += "id volatile _rethrow = 0;\n";
1946 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001947 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001948
Benjamin Kramerd999b372010-02-14 14:14:16 +00001949 ReplaceText(startLoc, 4, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001950
Steve Naroff75730982007-11-07 04:08:17 +00001951 startLoc = S->getTryBody()->getLocEnd();
1952 startBuf = SM->getCharacterData(startLoc);
1953
1954 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001955
Steve Naroff75730982007-11-07 04:08:17 +00001956 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001957 if (S->getNumCatchStmts()) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001958 startLoc = startLoc.getLocWithOffset(1);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001959 buf = " /* @catch begin */ else {\n";
1960 buf += " id _caught = objc_exception_extract(&_stack);\n";
1961 buf += " objc_exception_try_enter (&_stack);\n";
1962 buf += " if (_setjmp(_stack.buf))\n";
1963 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1964 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00001965
Benjamin Kramerd999b372010-02-14 14:14:16 +00001966 InsertText(startLoc, buf);
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001967 } else { /* no catch list */
1968 buf = "}\nelse {\n";
1969 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1970 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001971 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001972 }
Steve Naroff75730982007-11-07 04:08:17 +00001973 Stmt *lastCatchBody = 0;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001974 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1975 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregorc00d8e12010-04-26 16:46:50 +00001976 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00001977
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001978 if (I == 0)
Steve Naroff75730982007-11-07 04:08:17 +00001979 buf = "if ("; // we are generating code for the first catch clause
1980 else
1981 buf = "else if (";
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001982 startLoc = Catch->getLocStart();
Steve Naroff75730982007-11-07 04:08:17 +00001983 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001984
Steve Naroff75730982007-11-07 04:08:17 +00001985 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00001986
Steve Naroff75730982007-11-07 04:08:17 +00001987 const char *lParenLoc = strchr(startBuf, '(');
1988
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001989 if (Catch->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001990 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001991 lastCatchBody = Catch->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001992 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1993 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001994 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner06767512008-04-08 05:52:18 +00001995 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001996 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001997
Steve Naroffe12e6922008-02-01 20:02:07 +00001998 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00001999 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002000 } else if (catchDecl) {
2001 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002002 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00002003 buf += "1) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002004 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
John McCall506b57e2010-05-17 21:00:27 +00002005 } else if (const ObjCObjectPointerType *Ptr =
2006 t->getAs<ObjCObjectPointerType>()) {
2007 // Should be a pointer to a class.
2008 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
2009 if (IDecl) {
Steve Naroff21867b12007-11-07 18:43:40 +00002010 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall506b57e2010-05-17 21:00:27 +00002011 buf += IDecl->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00002012 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002013 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00002014 }
2015 }
2016 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002017 lastCatchBody = Catch->getCatchBody();
2018 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroff75730982007-11-07 04:08:17 +00002019 SourceLocation bodyLoc = lastCatchBody->getLocStart();
2020 const char *bodyBuf = SM->getCharacterData(bodyLoc);
2021 const char *rParenBuf = SM->getCharacterData(rParenLoc);
2022 assert((*rParenBuf == ')') && "bogus @catch paren location");
2023 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002024
Mike Stump1eb44332009-09-09 15:08:12 +00002025 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00002026 // declares the @catch parameter).
Benjamin Kramerd999b372010-02-14 14:14:16 +00002027 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002028 } else {
David Blaikieb219cfc2011-09-23 05:06:16 +00002029 llvm_unreachable("@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00002030 }
Steve Naroff75730982007-11-07 04:08:17 +00002031 }
2032 // Complete the catch list...
2033 if (lastCatchBody) {
2034 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00002035 assert(*SM->getCharacterData(bodyLoc) == '}' &&
2036 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002037
Steve Naroff378f47a2008-09-11 15:29:03 +00002038 // Insert the last (implicit) else clause *before* the right curly brace.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002039 bodyLoc = bodyLoc.getLocWithOffset(-1);
Steve Naroff378f47a2008-09-11 15:29:03 +00002040 buf = "} /* last catch end */\n";
2041 buf += "else {\n";
2042 buf += " _rethrow = _caught;\n";
2043 buf += " objc_exception_try_exit(&_stack);\n";
2044 buf += "} } /* @catch end */\n";
2045 if (!S->getFinallyStmt())
2046 buf += "}\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002047 InsertText(bodyLoc, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002048
Steve Naroff75730982007-11-07 04:08:17 +00002049 // Set lastCurlyLoc
2050 lastCurlyLoc = lastCatchBody->getLocEnd();
2051 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002052 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00002053 startLoc = finalStmt->getLocStart();
2054 startBuf = SM->getCharacterData(startLoc);
2055 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00002056
Benjamin Kramerd999b372010-02-14 14:14:16 +00002057 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump1eb44332009-09-09 15:08:12 +00002058
Steve Naroff75730982007-11-07 04:08:17 +00002059 Stmt *body = finalStmt->getFinallyBody();
2060 SourceLocation startLoc = body->getLocStart();
2061 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00002062 assert(*SM->getCharacterData(startLoc) == '{' &&
2063 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002064 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00002065 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002066
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002067 startLoc = startLoc.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002068 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002069 endLoc = endLoc.getLocWithOffset(-1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002070 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002071
Steve Naroff75730982007-11-07 04:08:17 +00002072 // Set lastCurlyLoc
2073 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00002074
Steve Naroff8c565152008-12-05 17:03:39 +00002075 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00002076 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00002077 } else { /* no finally clause - make sure we synthesize an implicit one */
2078 buf = "{ /* implicit finally clause */\n";
2079 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
2080 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
2081 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002082 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00002083
2084 // Now check for any return/continue/go statements within the @try.
2085 // The implicit finally clause won't called if the @try contains any
2086 // jump statements.
2087 bool hasReturns = false;
2088 HasReturnStmts(S->getTryBody(), hasReturns);
2089 if (hasReturns)
2090 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00002091 }
2092 // Now emit the final closing curly brace...
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002093 lastCurlyLoc = lastCurlyLoc.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002094 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002095 return 0;
2096}
2097
Mike Stump1eb44332009-09-09 15:08:12 +00002098// This can't be done with ReplaceStmt(S, ThrowExpr), since
2099// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00002100// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00002101Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00002102 // Get the start location and compute the semi location.
2103 SourceLocation startLoc = S->getLocStart();
2104 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00002105
Steve Naroff2bd03922007-11-07 15:32:26 +00002106 assert((*startBuf == '@') && "bogus @throw location");
2107
2108 std::string buf;
2109 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00002110 if (S->getThrowExpr())
2111 buf = "objc_exception_throw(";
2112 else // add an implicit argument
2113 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00002114
Steve Naroff4ba0acb2008-07-25 15:41:30 +00002115 // handle "@ throw" correctly.
2116 const char *wBuf = strchr(startBuf, 'w');
2117 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramerd999b372010-02-14 14:14:16 +00002118 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002119
Steve Naroff2bd03922007-11-07 15:32:26 +00002120 const char *semiBuf = strchr(startBuf, ';');
2121 assert((*semiBuf == ';') && "@throw: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002122 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002123 ReplaceText(semiLoc, 1, ");");
Steve Naroff2bd03922007-11-07 15:32:26 +00002124 return 0;
2125}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002126
Steve Naroffb29b4272008-04-14 22:03:09 +00002127Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00002128 // Create a new string expression.
2129 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002130 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002131 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Jay Foad65aa6882011-06-21 15:13:30 +00002132 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
Douglas Gregor5cee1192011-07-27 05:40:30 +00002133 StringLiteral::Ascii, false,
2134 StrType, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002135 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00002136
Chris Lattner07506182007-11-30 22:53:43 +00002137 // Replace this subexpr in the parent.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002138 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00002139 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00002140}
2141
Steve Naroffb29b4272008-04-14 22:03:09 +00002142Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00002143 if (!SelGetUidFunctionDecl)
2144 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00002145 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2146 // Create a call to sel_registerName("selName").
Chris Lattner5f9e2722011-07-23 10:55:15 +00002147 SmallVector<Expr*, 8> SelExprs;
Steve Naroffb42f8412007-11-05 14:50:49 +00002148 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002149 SelExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002150 Exp->getSelector().getAsString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002151 StringLiteral::Ascii, false,
2152 argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00002153 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2154 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002155 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002156 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00002157 return SelExp;
2158}
2159
Steve Naroffb29b4272008-04-14 22:03:09 +00002160CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002161 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2162 SourceLocation EndLoc) {
Steve Naroffebf2b562007-10-23 23:50:29 +00002163 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00002164 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002165
Steve Naroffebf2b562007-10-23 23:50:29 +00002166 // Create a reference to the objc_msgSend() declaration.
John McCallf89e55a2010-11-18 06:31:45 +00002167 DeclRefExpr *DRE =
2168 new (Context) DeclRefExpr(FD, msgSendType, VK_LValue, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002169
Steve Naroffebf2b562007-10-23 23:50:29 +00002170 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00002171 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson88465d32010-04-23 22:18:37 +00002172 ImplicitCastExpr *ICE =
John McCalla5bbc502010-11-15 09:46:46 +00002173 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00002174 DRE, 0, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00002175
John McCall183700f2009-09-21 23:43:11 +00002176 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002177
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002178 CallExpr *Exp =
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002179 new (Context) CallExpr(*Context, ICE, args, nargs,
John McCallf89e55a2010-11-18 06:31:45 +00002180 FT->getCallResultType(*Context),
2181 VK_RValue, EndLoc);
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002182 return Exp;
Steve Naroff934f2762007-10-24 22:48:43 +00002183}
2184
Steve Naroffd5255f52007-11-01 13:24:47 +00002185static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2186 const char *&startRef, const char *&endRef) {
2187 while (startBuf < endBuf) {
2188 if (*startBuf == '<')
2189 startRef = startBuf; // mark the start.
2190 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00002191 if (startRef && *startRef == '<') {
2192 endRef = startBuf; // mark the end.
2193 return true;
2194 }
2195 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002196 }
2197 startBuf++;
2198 }
2199 return false;
2200}
2201
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002202static void scanToNextArgument(const char *&argRef) {
2203 int angle = 0;
2204 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2205 if (*argRef == '<')
2206 angle++;
2207 else if (*argRef == '>')
2208 angle--;
2209 argRef++;
2210 }
2211 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2212}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002213
Steve Naroffb29b4272008-04-14 22:03:09 +00002214bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian32132a02010-02-03 21:29:28 +00002215 if (T->isObjCQualifiedIdType())
2216 return true;
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002217 if (const PointerType *PT = T->getAs<PointerType>()) {
2218 if (PT->getPointeeType()->isObjCQualifiedIdType())
2219 return true;
2220 }
2221 if (T->isObjCObjectPointerType()) {
2222 T = T->getPointeeType();
2223 return T->isObjCQualifiedInterfaceType();
2224 }
Fariborz Jahanian24f9cab2010-09-30 20:41:32 +00002225 if (T->isArrayType()) {
2226 QualType ElemTy = Context->getBaseElementType(T);
2227 return needToScanForQualifiers(ElemTy);
2228 }
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002229 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002230}
2231
Steve Naroff4f95b752008-07-29 18:15:38 +00002232void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2233 QualType Type = E->getType();
2234 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00002235 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00002236
Steve Naroffcda658e2008-11-19 21:15:47 +00002237 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2238 Loc = ECE->getLParenLoc();
2239 EndLoc = ECE->getRParenLoc();
2240 } else {
2241 Loc = E->getLocStart();
2242 EndLoc = E->getLocEnd();
2243 }
2244 // This will defend against trying to rewrite synthesized expressions.
2245 if (Loc.isInvalid() || EndLoc.isInvalid())
2246 return;
2247
Steve Naroff4f95b752008-07-29 18:15:38 +00002248 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00002249 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00002250 const char *startRef = 0, *endRef = 0;
2251 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2252 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002253 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2254 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
Steve Naroff4f95b752008-07-29 18:15:38 +00002255 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002256 InsertText(LessLoc, "/*");
2257 InsertText(GreaterLoc, "*/");
Steve Naroff4f95b752008-07-29 18:15:38 +00002258 }
2259 }
2260}
2261
Steve Naroffb29b4272008-04-14 22:03:09 +00002262void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002263 SourceLocation Loc;
2264 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00002265 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002266 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2267 Loc = VD->getLocation();
2268 Type = VD->getType();
2269 }
2270 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2271 Loc = FD->getLocation();
2272 // Check for ObjC 'id' and class types that have been adorned with protocol
2273 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002274 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002275 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002276 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002277 if (!proto)
2278 return;
2279 Type = proto->getResultType();
2280 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002281 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2282 Loc = FD->getLocation();
2283 Type = FD->getType();
2284 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002285 else
2286 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002287
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002288 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002289 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002290
Steve Naroffd5255f52007-11-01 13:24:47 +00002291 const char *endBuf = SM->getCharacterData(Loc);
2292 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002293 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002294 startBuf--; // scan backward (from the decl location) for return type.
2295 const char *startRef = 0, *endRef = 0;
2296 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2297 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002298 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2299 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002300 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002301 InsertText(LessLoc, "/*");
2302 InsertText(GreaterLoc, "*/");
Steve Naroff9165ad32007-10-31 04:38:33 +00002303 }
2304 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002305 if (!proto)
2306 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002307 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002308 const char *startBuf = SM->getCharacterData(Loc);
2309 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00002310 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2311 if (needToScanForQualifiers(proto->getArgType(i))) {
2312 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002313
Steve Naroffd5255f52007-11-01 13:24:47 +00002314 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002315 // scan forward (from the decl location) for argument types.
2316 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00002317 const char *startRef = 0, *endRef = 0;
2318 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2319 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002320 SourceLocation LessLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002321 Loc.getLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002322 SourceLocation GreaterLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002323 Loc.getLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002324 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002325 InsertText(LessLoc, "/*");
2326 InsertText(GreaterLoc, "*/");
Steve Naroffd5255f52007-11-01 13:24:47 +00002327 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002328 startBuf = ++endBuf;
2329 }
2330 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002331 // If the function name is derived from a macro expansion, then the
2332 // argument buffer will not follow the name. Need to speak with Chris.
2333 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002334 startBuf++; // scan forward (from the decl location) for argument types.
2335 startBuf++;
2336 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002337 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002338}
2339
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002340void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2341 QualType QT = ND->getType();
2342 const Type* TypePtr = QT->getAs<Type>();
2343 if (!isa<TypeOfExprType>(TypePtr))
2344 return;
2345 while (isa<TypeOfExprType>(TypePtr)) {
2346 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2347 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2348 TypePtr = QT->getAs<Type>();
2349 }
2350 // FIXME. This will not work for multiple declarators; as in:
2351 // __typeof__(a) b,c,d;
Douglas Gregor30c42402011-09-27 22:38:19 +00002352 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002353 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2354 const char *startBuf = SM->getCharacterData(DeclLoc);
2355 if (ND->getInit()) {
2356 std::string Name(ND->getNameAsString());
2357 TypeAsString += " " + Name + " = ";
2358 Expr *E = ND->getInit();
2359 SourceLocation startLoc;
2360 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2361 startLoc = ECE->getLParenLoc();
2362 else
2363 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00002364 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002365 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002366 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002367 }
2368 else {
2369 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00002370 X = SM->getExpansionLoc(X);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002371 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002372 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002373 }
2374}
2375
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002376// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002377void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002378 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002379 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002380 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002381 QualType getFuncType =
2382 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002383 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002384 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002385 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002386 SelGetUidIdent, getFuncType, 0,
John McCalld931b082010-08-26 03:08:43 +00002387 SC_Extern,
2388 SC_None, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002389}
2390
Steve Naroffb29b4272008-04-14 22:03:09 +00002391void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002392 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002393 if (FD->getIdentifier() &&
Daniel Dunbar4087f272010-08-17 22:39:59 +00002394 FD->getName() == "sel_registerName") {
Steve Naroff09b266e2007-10-30 23:14:51 +00002395 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002396 return;
2397 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002398 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002399}
2400
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002401void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
Douglas Gregor30c42402011-09-27 22:38:19 +00002402 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002403 const char *argPtr = TypeString.c_str();
2404 if (!strchr(argPtr, '^')) {
2405 Str += TypeString;
2406 return;
2407 }
2408 while (*argPtr) {
2409 Str += (*argPtr == '^' ? '*' : *argPtr);
2410 argPtr++;
2411 }
2412}
2413
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002414// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002415void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2416 ValueDecl *VD) {
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002417 QualType Type = VD->getType();
Douglas Gregor30c42402011-09-27 22:38:19 +00002418 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002419 const char *argPtr = TypeString.c_str();
2420 int paren = 0;
2421 while (*argPtr) {
2422 switch (*argPtr) {
2423 case '(':
2424 Str += *argPtr;
2425 paren++;
2426 break;
2427 case ')':
2428 Str += *argPtr;
2429 paren--;
2430 break;
2431 case '^':
2432 Str += '*';
2433 if (paren == 1)
2434 Str += VD->getNameAsString();
2435 break;
2436 default:
2437 Str += *argPtr;
2438 break;
2439 }
2440 argPtr++;
2441 }
2442}
2443
2444
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002445void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2446 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2447 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2448 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2449 if (!proto)
2450 return;
2451 QualType Type = proto->getResultType();
Douglas Gregor30c42402011-09-27 22:38:19 +00002452 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002453 FdStr += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00002454 FdStr += FD->getName();
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002455 FdStr += "(";
2456 unsigned numArgs = proto->getNumArgs();
2457 for (unsigned i = 0; i < numArgs; i++) {
2458 QualType ArgType = proto->getArgType(i);
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002459 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002460 if (i+1 < numArgs)
2461 FdStr += ", ";
2462 }
2463 FdStr += ");\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002464 InsertText(FunLocStart, FdStr);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002465 CurFunctionDeclToDeclareForBlock = 0;
2466}
2467
Steve Naroffc0a123c2008-03-11 17:37:02 +00002468// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002469void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002470 if (SuperContructorFunctionDecl)
2471 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002472 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002473 SmallVector<QualType, 16> ArgTys;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002474 QualType argT = Context->getObjCIdType();
2475 assert(!argT.isNull() && "Can't find 'id' type");
2476 ArgTys.push_back(argT);
2477 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002478 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2479 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002480 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002481 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002482 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002483 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002484 SC_Extern,
2485 SC_None, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002486}
2487
Steve Naroff09b266e2007-10-30 23:14:51 +00002488// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002489void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002490 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002491 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002492 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002493 assert(!argT.isNull() && "Can't find 'id' type");
2494 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002495 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002496 assert(!argT.isNull() && "Can't find 'SEL' type");
2497 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002498 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2499 &ArgTys[0], ArgTys.size(),
2500 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002501 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002502 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002503 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002504 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002505 SC_Extern,
2506 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002507}
2508
Steve Naroff874e2322007-11-15 10:28:18 +00002509// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002510void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002511 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002512 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002513 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002514 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002515 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002516 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2517 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2518 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002519 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002520 assert(!argT.isNull() && "Can't find 'SEL' type");
2521 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002522 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2523 &ArgTys[0], ArgTys.size(),
2524 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002525 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002526 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002527 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002528 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002529 SC_Extern,
2530 SC_None, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002531}
2532
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002533// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002534void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002535 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002536 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002537 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002538 assert(!argT.isNull() && "Can't find 'id' type");
2539 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002540 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002541 assert(!argT.isNull() && "Can't find 'SEL' type");
2542 ArgTys.push_back(argT);
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002543 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
John McCalle23cf432010-12-14 08:05:40 +00002544 &ArgTys[0], ArgTys.size(),
2545 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002546 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002547 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002548 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002549 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002550 SC_Extern,
2551 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002552}
2553
Mike Stump1eb44332009-09-09 15:08:12 +00002554// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002555// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002556void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002557 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002558 &Context->Idents.get("objc_msgSendSuper_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002559 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002560 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002561 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002562 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002563 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2564 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2565 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002566 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002567 assert(!argT.isNull() && "Can't find 'SEL' type");
2568 ArgTys.push_back(argT);
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002569 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
John McCalle23cf432010-12-14 08:05:40 +00002570 &ArgTys[0], ArgTys.size(),
2571 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002572 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002573 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002574 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002575 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002576 SC_Extern,
2577 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002578}
2579
Steve Naroff1284db82008-05-08 22:02:18 +00002580// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002581void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002582 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002583 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002584 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002585 assert(!argT.isNull() && "Can't find 'id' type");
2586 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002587 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002588 assert(!argT.isNull() && "Can't find 'SEL' type");
2589 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002590 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2591 &ArgTys[0], ArgTys.size(),
2592 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002593 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002594 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002595 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002596 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002597 SC_Extern,
2598 SC_None, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002599}
2600
Steve Naroff09b266e2007-10-30 23:14:51 +00002601// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002602void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002603 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002604 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002605 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002606 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2607 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002608 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002609 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002610 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002611 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002612 SC_Extern,
2613 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002614}
2615
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002616// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2617void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2618 IdentifierInfo *getSuperClassIdent =
2619 &Context->Idents.get("class_getSuperclass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002620 SmallVector<QualType, 16> ArgTys;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002621 ArgTys.push_back(Context->getObjCClassType());
John McCalle23cf432010-12-14 08:05:40 +00002622 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2623 &ArgTys[0], ArgTys.size());
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002624 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002625 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002626 SourceLocation(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00002627 getSuperClassIdent,
2628 getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002629 SC_Extern,
2630 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002631 false);
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002632}
2633
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002634// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002635void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002636 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002637 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002638 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002639 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2640 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002641 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002642 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002643 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002644 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002645 SC_Extern,
2646 SC_None, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002647}
2648
Steve Naroffb29b4272008-04-14 22:03:09 +00002649Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002650 QualType strType = getConstantStringStructType();
2651
2652 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002653
2654 std::string tmpName = InFileName;
2655 unsigned i;
2656 for (i=0; i < tmpName.length(); i++) {
2657 char c = tmpName.at(i);
2658 // replace any non alphanumeric characters with '_'.
2659 if (!isalpha(c) && (c < '0' || c > '9'))
2660 tmpName[i] = '_';
2661 }
2662 S += tmpName;
2663 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002664 S += utostr(NumObjCStringLiterals++);
2665
Steve Naroffba92b2e2008-03-27 22:29:16 +00002666 Preamble += "static __NSConstantStringImpl " + S;
2667 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2668 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002669 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002670 std::string prettyBufS;
2671 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00002672 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2673 PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002674 Preamble += prettyBuf.str();
2675 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002676 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002677
2678 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002679 SourceLocation(), &Context->Idents.get(S),
2680 strType, 0, SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00002681 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, VK_LValue,
2682 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00002683 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002684 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002685 VK_RValue, OK_Ordinary,
2686 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002687 // cast to NSConstantString *
John McCall9d125032010-01-15 18:39:57 +00002688 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002689 CK_CPointerToObjCPointerCast, Unop);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002690 ReplaceStmt(Exp, cast);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002691 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002692 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002693}
2694
Steve Naroff874e2322007-11-15 10:28:18 +00002695// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002696QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002697 if (!SuperStructDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002698 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002699 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002700 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002701 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002702
Steve Naroff874e2322007-11-15 10:28:18 +00002703 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002704 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002705 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002706 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002707
Steve Naroff874e2322007-11-15 10:28:18 +00002708 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002709 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002710 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002711 SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00002712 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002713 FieldTypes[i], 0,
2714 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00002715 /*Mutable=*/false,
2716 /*HasInit=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002717 }
Mike Stump1eb44332009-09-09 15:08:12 +00002718
Douglas Gregor838db382010-02-11 01:19:42 +00002719 SuperStructDecl->completeDefinition();
Steve Naroff874e2322007-11-15 10:28:18 +00002720 }
2721 return Context->getTagDeclType(SuperStructDecl);
2722}
2723
Steve Naroffb29b4272008-04-14 22:03:09 +00002724QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002725 if (!ConstantStringDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002726 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002727 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002728 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002729 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002730
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002731 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002732 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002733 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002734 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002735 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002736 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002737 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002738 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002739
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002740 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002741 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002742 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2743 ConstantStringDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002744 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00002745 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002746 FieldTypes[i], 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00002747 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00002748 /*Mutable=*/true,
2749 /*HasInit=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002750 }
2751
Douglas Gregor838db382010-02-11 01:19:42 +00002752 ConstantStringDecl->completeDefinition();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002753 }
2754 return Context->getTagDeclType(ConstantStringDecl);
2755}
2756
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002757Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2758 SourceLocation StartLoc,
2759 SourceLocation EndLoc) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002760 if (!SelGetUidFunctionDecl)
2761 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002762 if (!MsgSendFunctionDecl)
2763 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002764 if (!MsgSendSuperFunctionDecl)
2765 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002766 if (!MsgSendStretFunctionDecl)
2767 SynthMsgSendStretFunctionDecl();
2768 if (!MsgSendSuperStretFunctionDecl)
2769 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002770 if (!MsgSendFpretFunctionDecl)
2771 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002772 if (!GetClassFunctionDecl)
2773 SynthGetClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002774 if (!GetSuperClassFunctionDecl)
2775 SynthGetSuperClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002776 if (!GetMetaClassFunctionDecl)
2777 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002778
Steve Naroff874e2322007-11-15 10:28:18 +00002779 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002780 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2781 // May need to use objc_msgSend_stret() as well.
2782 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002783 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2784 QualType resultType = mDecl->getResultType();
Douglas Gregorfb87b892010-04-26 21:31:17 +00002785 if (resultType->isRecordType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002786 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002787 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002788 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002789 }
Mike Stump1eb44332009-09-09 15:08:12 +00002790
Steve Naroff934f2762007-10-24 22:48:43 +00002791 // Synthesize a call to objc_msgSend().
Chris Lattner5f9e2722011-07-23 10:55:15 +00002792 SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002793 switch (Exp->getReceiverKind()) {
2794 case ObjCMessageExpr::SuperClass: {
2795 MsgSendFlavor = MsgSendSuperFunctionDecl;
2796 if (MsgSendStretFlavor)
2797 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2798 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002799
Douglas Gregor04badcf2010-04-21 00:45:42 +00002800 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00002801
Chris Lattner5f9e2722011-07-23 10:55:15 +00002802 SmallVector<Expr*, 4> InitExprs;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002803
Douglas Gregor04badcf2010-04-21 00:45:42 +00002804 // set the receiver to self, the first argument to all methods.
2805 InitExprs.push_back(
2806 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002807 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002808 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf89e55a2010-11-18 06:31:45 +00002809 Context->getObjCIdType(),
2810 VK_RValue,
2811 SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002812 ); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002813
Douglas Gregor04badcf2010-04-21 00:45:42 +00002814 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002815 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002816 QualType argType = Context->getPointerType(Context->CharTy);
2817 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002818 ClassDecl->getIdentifier()->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002819 StringLiteral::Ascii, false,
2820 argType, SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002821 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2822 &ClsExprs[0],
2823 ClsExprs.size(),
2824 StartLoc,
2825 EndLoc);
2826 // (Class)objc_getClass("CurrentClass")
2827 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2828 Context->getObjCClassType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002829 CK_CPointerToObjCPointerCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002830 ClsExprs.clear();
2831 ClsExprs.push_back(ArgExpr);
2832 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2833 &ClsExprs[0], ClsExprs.size(),
2834 StartLoc, EndLoc);
2835
2836 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2837 // To turn off a warning, type-cast to 'id'
2838 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2839 NoTypeInfoCStyleCastExpr(Context,
2840 Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002841 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002842 // struct objc_super
2843 QualType superType = getSuperStructType();
2844 Expr *SuperRep;
Steve Naroff621edce2009-04-29 16:37:50 +00002845
Francois Pichet62ec1f22011-09-17 17:15:52 +00002846 if (LangOpts.MicrosoftExt) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002847 SynthSuperContructorFunctionDecl();
2848 // Simulate a contructor call...
2849 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf89e55a2010-11-18 06:31:45 +00002850 superType, VK_LValue,
2851 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002852 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2853 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002854 superType, VK_LValue,
2855 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002856 // The code for super is a little tricky to prevent collision with
2857 // the structure definition in the header. The rewriter has it's own
2858 // internal definition (__rw_objc_super) that is uses. This is why
2859 // we need the cast below. For example:
2860 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2861 //
John McCall2de56d12010-08-25 11:45:40 +00002862 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002863 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002864 VK_RValue, OK_Ordinary,
2865 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002866 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2867 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002868 CK_BitCast, SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002869 } else {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002870 // (struct objc_super) { <exprs from above> }
2871 InitListExpr *ILE =
2872 new (Context) InitListExpr(*Context, SourceLocation(),
2873 &InitExprs[0], InitExprs.size(),
2874 SourceLocation());
2875 TypeSourceInfo *superTInfo
2876 = Context->getTrivialTypeSourceInfo(superType);
2877 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002878 superType, VK_LValue,
2879 ILE, false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002880 // struct objc_super *
John McCall2de56d12010-08-25 11:45:40 +00002881 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002882 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002883 VK_RValue, OK_Ordinary,
2884 SourceLocation());
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002885 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002886 MsgExprs.push_back(SuperRep);
2887 break;
Steve Naroff6568d4d2007-11-14 23:54:14 +00002888 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002889
2890 case ObjCMessageExpr::Class: {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002891 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002892 QualType argType = Context->getPointerType(Context->CharTy);
2893 ObjCInterfaceDecl *Class
John McCall506b57e2010-05-17 21:00:27 +00002894 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00002895 IdentifierInfo *clsName = Class->getIdentifier();
2896 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002897 clsName->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002898 StringLiteral::Ascii, false,
Anders Carlsson3e2193c2011-04-14 00:40:03 +00002899 argType, SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002900 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2901 &ClsExprs[0],
2902 ClsExprs.size(),
2903 StartLoc, EndLoc);
2904 MsgExprs.push_back(Cls);
2905 break;
2906 }
2907
2908 case ObjCMessageExpr::SuperInstance:{
2909 MsgSendFlavor = MsgSendSuperFunctionDecl;
2910 if (MsgSendStretFlavor)
2911 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2912 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2913 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Chris Lattner5f9e2722011-07-23 10:55:15 +00002914 SmallVector<Expr*, 4> InitExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002915
2916 InitExprs.push_back(
2917 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002918 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002919 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf89e55a2010-11-18 06:31:45 +00002920 Context->getObjCIdType(),
2921 VK_RValue, SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002922 ); // set the 'receiver'.
2923
2924 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002925 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002926 QualType argType = Context->getPointerType(Context->CharTy);
2927 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002928 ClassDecl->getIdentifier()->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002929 StringLiteral::Ascii, false, argType,
2930 SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002931 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2932 &ClsExprs[0],
2933 ClsExprs.size(),
2934 StartLoc, EndLoc);
2935 // (Class)objc_getClass("CurrentClass")
2936 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2937 Context->getObjCClassType(),
John McCalla5bbc502010-11-15 09:46:46 +00002938 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002939 ClsExprs.clear();
2940 ClsExprs.push_back(ArgExpr);
2941 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2942 &ClsExprs[0], ClsExprs.size(),
2943 StartLoc, EndLoc);
2944
2945 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2946 // To turn off a warning, type-cast to 'id'
2947 InitExprs.push_back(
2948 // set 'super class', using class_getSuperclass().
2949 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002950 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002951 // struct objc_super
2952 QualType superType = getSuperStructType();
2953 Expr *SuperRep;
2954
Francois Pichet62ec1f22011-09-17 17:15:52 +00002955 if (LangOpts.MicrosoftExt) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002956 SynthSuperContructorFunctionDecl();
2957 // Simulate a contructor call...
2958 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf89e55a2010-11-18 06:31:45 +00002959 superType, VK_LValue,
2960 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002961 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2962 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002963 superType, VK_LValue, SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002964 // The code for super is a little tricky to prevent collision with
2965 // the structure definition in the header. The rewriter has it's own
2966 // internal definition (__rw_objc_super) that is uses. This is why
2967 // we need the cast below. For example:
2968 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2969 //
John McCall2de56d12010-08-25 11:45:40 +00002970 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002971 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002972 VK_RValue, OK_Ordinary,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002973 SourceLocation());
2974 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2975 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002976 CK_BitCast, SuperRep);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002977 } else {
2978 // (struct objc_super) { <exprs from above> }
2979 InitListExpr *ILE =
2980 new (Context) InitListExpr(*Context, SourceLocation(),
2981 &InitExprs[0], InitExprs.size(),
2982 SourceLocation());
2983 TypeSourceInfo *superTInfo
2984 = Context->getTrivialTypeSourceInfo(superType);
2985 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002986 superType, VK_RValue, ILE,
2987 false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002988 }
2989 MsgExprs.push_back(SuperRep);
2990 break;
2991 }
2992
2993 case ObjCMessageExpr::Instance: {
2994 // Remove all type-casts because it may contain objc-style types; e.g.
2995 // Foo<Proto> *.
2996 Expr *recExpr = Exp->getInstanceReceiver();
2997 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2998 recExpr = CE->getSubExpr();
Fariborz Jahanianbaac1ea2011-10-07 17:17:45 +00002999 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3000 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3001 ? CK_BlockPointerToObjCPointerCast
3002 : CK_CPointerToObjCPointerCast;
3003
Douglas Gregor04badcf2010-04-21 00:45:42 +00003004 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
Fariborz Jahanianbaac1ea2011-10-07 17:17:45 +00003005 CK, recExpr);
Douglas Gregor04badcf2010-04-21 00:45:42 +00003006 MsgExprs.push_back(recExpr);
3007 break;
3008 }
3009 }
3010
Steve Naroffbeaf2992007-11-03 11:27:19 +00003011 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003012 SmallVector<Expr*, 8> SelExprs;
Steve Naroff934f2762007-10-24 22:48:43 +00003013 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00003014 SelExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00003015 Exp->getSelector().getAsString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00003016 StringLiteral::Ascii, false,
3017 argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00003018 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003019 &SelExprs[0], SelExprs.size(),
3020 StartLoc,
3021 EndLoc);
Steve Naroff934f2762007-10-24 22:48:43 +00003022 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00003023
Steve Naroff934f2762007-10-24 22:48:43 +00003024 // Now push any user supplied arguments.
3025 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00003026 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00003027 // Make all implicit casts explicit...ICE comes in handy:-)
3028 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3029 // Reuse the ICE type, it is exactly what the doctor ordered.
Fariborz Jahaniandff3f012011-02-26 01:31:36 +00003030 QualType type = ICE->getType();
3031 if (needToScanForQualifiers(type))
3032 type = Context->getObjCIdType();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003033 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003034 (void)convertBlockPointerToFunctionPointer(type);
Fariborz Jahanian1a38b462011-08-04 23:58:03 +00003035 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
John McCall1d9b3b22011-09-09 05:25:32 +00003036 CastKind CK;
3037 if (SubExpr->getType()->isIntegralType(*Context) &&
3038 type->isBooleanType()) {
3039 CK = CK_IntegralToBoolean;
3040 } else if (type->isObjCObjectPointerType()) {
3041 if (SubExpr->getType()->isBlockPointerType()) {
3042 CK = CK_BlockPointerToObjCPointerCast;
3043 } else if (SubExpr->getType()->isPointerType()) {
3044 CK = CK_CPointerToObjCPointerCast;
3045 } else {
3046 CK = CK_BitCast;
3047 }
3048 } else {
3049 CK = CK_BitCast;
3050 }
3051
3052 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003053 }
3054 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003055 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003056 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003057 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003058 userExpr = CE->getSubExpr();
John McCall1d9b3b22011-09-09 05:25:32 +00003059 CastKind CK;
3060 if (userExpr->getType()->isIntegralType(*Context)) {
3061 CK = CK_IntegralToPointer;
3062 } else if (userExpr->getType()->isBlockPointerType()) {
3063 CK = CK_BlockPointerToObjCPointerCast;
3064 } else if (userExpr->getType()->isPointerType()) {
3065 CK = CK_CPointerToObjCPointerCast;
3066 } else {
3067 CK = CK_BitCast;
3068 }
John McCall9d125032010-01-15 18:39:57 +00003069 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall1d9b3b22011-09-09 05:25:32 +00003070 CK, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003071 }
Mike Stump1eb44332009-09-09 15:08:12 +00003072 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00003073 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003074 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3075 // out the argument in the original expression (since we aren't deleting
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003076 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003077 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00003078 }
Steve Naroffab972d32007-11-04 22:37:50 +00003079 // Generate the funky cast.
3080 CastExpr *cast;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003081 SmallVector<QualType, 8> ArgTypes;
Steve Naroffab972d32007-11-04 22:37:50 +00003082 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00003083
Steve Naroffab972d32007-11-04 22:37:50 +00003084 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00003085 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3086 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3087 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003088 ArgTypes.push_back(Context->getObjCIdType());
3089 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00003090 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00003091 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00003092 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3093 E = OMD->param_end(); PI != E; ++PI) {
3094 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00003095 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00003096 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00003097 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003098 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff352336b2007-11-05 14:36:37 +00003099 ArgTypes.push_back(t);
3100 }
Fariborz Jahanian3a448fb2011-09-10 17:01:56 +00003101 returnType = Exp->getType();
3102 convertToUnqualifiedObjCType(returnType);
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003103 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Naroffab972d32007-11-04 22:37:50 +00003104 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003105 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00003106 }
3107 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00003108 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003109
Steve Naroffab972d32007-11-04 22:37:50 +00003110 // Create a reference to the objc_msgSend() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003111 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00003112 VK_LValue, SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00003113
Mike Stump1eb44332009-09-09 15:08:12 +00003114 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00003115 // If we don't do this cast, we get the following bizarre warning/note:
3116 // xx.m:13: warning: function called through a non-compatible type
3117 // xx.m:13: note: if this code is reached, the program will abort
John McCall9d125032010-01-15 18:39:57 +00003118 cast = NoTypeInfoCStyleCastExpr(Context,
3119 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00003120 CK_BitCast, DRE);
Mike Stump1eb44332009-09-09 15:08:12 +00003121
Steve Naroffab972d32007-11-04 22:37:50 +00003122 // Now do the "normal" pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003123 QualType castType =
3124 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3125 // If we don't have a method decl, force a variadic cast.
3126 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Naroffab972d32007-11-04 22:37:50 +00003127 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003128 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003129 cast);
Steve Naroffab972d32007-11-04 22:37:50 +00003130
3131 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003132 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003133
John McCall183700f2009-09-21 23:43:11 +00003134 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003135 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003136 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003137 FT->getResultType(), VK_RValue,
3138 EndLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003139 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003140 if (MsgSendStretFlavor) {
3141 // We have the method which returns a struct/union. Must also generate
3142 // call to objc_msgSend_stret and hang both varieties on a conditional
3143 // expression which dictate which one to envoke depending on size of
3144 // method's return type.
Mike Stump1eb44332009-09-09 15:08:12 +00003145
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003146 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003147 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00003148 VK_LValue, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003149 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall9d125032010-01-15 18:39:57 +00003150 cast = NoTypeInfoCStyleCastExpr(Context,
3151 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00003152 CK_BitCast, STDRE);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003153 // Now do the "normal" pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003154 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3155 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003156 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003157 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003158 cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003159
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003160 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003161 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003162
John McCall183700f2009-09-21 23:43:11 +00003163 FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003164 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003165 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003166 FT->getResultType(), VK_RValue,
3167 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00003168
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003169 // Build sizeof(returnType)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003170 UnaryExprOrTypeTraitExpr *sizeofExpr =
3171 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3172 Context->getTrivialTypeSourceInfo(returnType),
3173 Context->getSizeType(), SourceLocation(),
3174 SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003175 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3176 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3177 // For X86 it is more complicated and some kind of target specific routine
3178 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00003179 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00003180 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00003181 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3182 llvm::APInt(IntSize, 8),
3183 Context->IntTy,
3184 SourceLocation());
John McCallf89e55a2010-11-18 06:31:45 +00003185 BinaryOperator *lessThanExpr =
3186 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3187 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003188 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00003189 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003190 new (Context) ConditionalOperator(lessThanExpr,
3191 SourceLocation(), CE,
John McCall56ca35d2011-02-17 10:25:35 +00003192 SourceLocation(), STCE,
John McCall09431682010-11-18 19:01:18 +00003193 returnType, VK_RValue, OK_Ordinary);
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003194 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3195 CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003196 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003197 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003198 return ReplacingStmt;
3199}
3200
Steve Naroffb29b4272008-04-14 22:03:09 +00003201Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003202 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3203 Exp->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00003204
Steve Naroff934f2762007-10-24 22:48:43 +00003205 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00003206 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00003207
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003208 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003209 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00003210}
3211
Steve Naroff621edce2009-04-29 16:37:50 +00003212// typedef struct objc_object Protocol;
3213QualType RewriteObjC::getProtocolType() {
3214 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00003215 TypeSourceInfo *TInfo
3216 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00003217 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Abramo Bagnara344577e2011-03-06 15:48:19 +00003218 SourceLocation(), SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00003219 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00003220 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00003221 }
3222 return Context->getTypeDeclType(ProtocolTypeDecl);
3223}
3224
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003225/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00003226/// a synthesized/forward data reference (to the protocol's metadata).
3227/// The forward references (and metadata) are generated in
3228/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00003229Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00003230 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3231 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00003232 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003233 SourceLocation(), ID, getProtocolType(), 0,
John McCalld931b082010-08-26 03:08:43 +00003234 SC_Extern, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00003235 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), VK_LValue,
3236 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00003237 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroff621edce2009-04-29 16:37:50 +00003238 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00003239 VK_RValue, OK_Ordinary, SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00003240 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCalla5bbc502010-11-15 09:46:46 +00003241 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003242 DerefExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003243 ReplaceStmt(Exp, castExpr);
3244 ProtocolExprDecls.insert(Exp->getProtocol());
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003245 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003246 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003247
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003248}
3249
Mike Stump1eb44332009-09-09 15:08:12 +00003250bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00003251 const char *endBuf) {
3252 while (startBuf < endBuf) {
3253 if (*startBuf == '#') {
3254 // Skip whitespace.
3255 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3256 ;
3257 if (!strncmp(startBuf, "if", strlen("if")) ||
3258 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3259 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3260 !strncmp(startBuf, "define", strlen("define")) ||
3261 !strncmp(startBuf, "undef", strlen("undef")) ||
3262 !strncmp(startBuf, "else", strlen("else")) ||
3263 !strncmp(startBuf, "elif", strlen("elif")) ||
3264 !strncmp(startBuf, "endif", strlen("endif")) ||
3265 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3266 !strncmp(startBuf, "include", strlen("include")) ||
3267 !strncmp(startBuf, "import", strlen("import")) ||
3268 !strncmp(startBuf, "include_next", strlen("include_next")))
3269 return true;
3270 }
3271 startBuf++;
3272 }
3273 return false;
3274}
3275
Fariborz Jahanian58457172011-12-05 18:43:13 +00003276/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003277/// an objective-c class with ivars.
Fariborz Jahanian58457172011-12-05 18:43:13 +00003278void RewriteObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003279 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003280 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar4087f272010-08-17 22:39:59 +00003281 assert(CDecl->getName() != "" &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003282 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003283 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003284 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003285 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003286 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003287 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00003288 SourceLocation LocStart = CDecl->getLocStart();
3289 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00003290
Steve Narofffea763e82007-11-14 19:25:57 +00003291 const char *startBuf = SM->getCharacterData(LocStart);
3292 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00003293
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003294 // If no ivars and no root or if its root, directly or indirectly,
3295 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003296 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
3297 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00003298 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003299 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003300 return;
3301 }
Mike Stump1eb44332009-09-09 15:08:12 +00003302
3303 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003304 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003305 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003306 Result += CDecl->getNameAsString();
Francois Pichet62ec1f22011-09-17 17:15:52 +00003307 if (LangOpts.MicrosoftExt)
Steve Naroff61ed9ca2008-03-10 23:16:54 +00003308 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00003309
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003310 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00003311 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00003312 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003313 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00003314 // If the buffer contains preprocessor directives, we do more fine-grained
3315 // rewrites. This is intended to fix code that looks like (which occurs in
3316 // NSURL.h, for example):
3317 //
3318 // #ifdef XYZ
3319 // @interface Foo : NSObject
3320 // #else
3321 // @interface FooBar : NSObject
3322 // #endif
3323 // {
3324 // int i;
3325 // }
3326 // @end
3327 //
3328 // This clause is segregated to avoid breaking the common case.
3329 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003330 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Argyrios Kyrtzidis1711fc92011-10-04 04:48:02 +00003331 CDecl->getAtStartLoc();
Steve Naroffbaf58c32008-05-31 14:15:04 +00003332 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00003333 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003334
Chris Lattnercafeb352009-02-20 18:18:36 +00003335 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00003336 // advance to the end of the referenced protocols.
3337 while (endHeader < cursor && *endHeader != '>') endHeader++;
3338 endHeader++;
3339 }
3340 // rewrite the original header
Benjamin Kramerd999b372010-02-14 14:14:16 +00003341 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003342 } else {
3343 // rewrite the original header *without* disturbing the '{'
Benjamin Kramerd999b372010-02-14 14:14:16 +00003344 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003345 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003346 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00003347 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003348 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003349 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003350 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003351 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003352
Steve Narofffea763e82007-11-14 19:25:57 +00003353 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00003354 SourceLocation OnePastCurly =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003355 LocStart.getLocWithOffset(cursor-startBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003356 InsertText(OnePastCurly, Result);
Steve Narofffea763e82007-11-14 19:25:57 +00003357 }
3358 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00003359
Steve Narofffea763e82007-11-14 19:25:57 +00003360 // Now comment out any visibility specifiers.
3361 while (cursor < endBuf) {
3362 if (*cursor == '@') {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003363 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00003364 // Skip whitespace.
3365 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3366 /*scan*/;
3367
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003368 // FIXME: presence of @public, etc. inside comment results in
3369 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00003370 if (!strncmp(cursor, "public", strlen("public")) ||
3371 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00003372 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00003373 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramerd999b372010-02-14 14:14:16 +00003374 InsertText(atLoc, "// ");
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003375 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00003376 // FIXME: If there are cases where '<' is used in ivar declaration part
3377 // of user code, then scan the ivar list and use needToScanForQualifiers
3378 // for type checking.
3379 else if (*cursor == '<') {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003380 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003381 InsertText(atLoc, "/* ");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003382 cursor = strchr(cursor, '>');
3383 cursor++;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003384 atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003385 InsertText(atLoc, " */");
Steve Naroffced80a82008-10-30 12:09:33 +00003386 } else if (*cursor == '^') { // rewrite block specifier.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003387 SourceLocation caretLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003388 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003389 }
Steve Narofffea763e82007-11-14 19:25:57 +00003390 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003391 }
Steve Narofffea763e82007-11-14 19:25:57 +00003392 // Don't forget to add a ';'!!
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003393 InsertText(LocEnd.getLocWithOffset(1), ";");
Steve Narofffea763e82007-11-14 19:25:57 +00003394 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00003395 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00003396 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003397 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003398 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003399 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003400 Result += "_IVARS;\n};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00003401 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003402 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003403 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003404 if (!ObjCSynthesizedStructs.insert(CDecl))
David Blaikieb219cfc2011-09-23 05:06:16 +00003405 llvm_unreachable("struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003406}
3407
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003408// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003409/// class methods.
Douglas Gregor653f1b12009-04-23 01:02:12 +00003410template<typename MethodIterator>
3411void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3412 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00003413 bool IsInstanceMethod,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003414 StringRef prefix,
3415 StringRef ClassName,
Chris Lattner158ecb92007-10-25 17:07:24 +00003416 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003417 if (MethodBegin == MethodEnd) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003418
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003419 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003420 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003421 SEL _cmd;
3422 char *method_types;
3423 void *_imp;
3424 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003425 */
Chris Lattner158ecb92007-10-25 17:07:24 +00003426 Result += "\nstruct _objc_method {\n";
3427 Result += "\tSEL _cmd;\n";
3428 Result += "\tchar *method_types;\n";
3429 Result += "\tvoid *_imp;\n";
3430 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003431
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003432 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00003433 }
Mike Stump1eb44332009-09-09 15:08:12 +00003434
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003435 // Build _objc_method_list for class's methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003436
Steve Naroff946a6932008-03-11 00:12:29 +00003437 /* struct {
3438 struct _objc_method_list *next_method;
3439 int method_count;
3440 struct _objc_method method_list[];
3441 }
3442 */
Douglas Gregor653f1b12009-04-23 01:02:12 +00003443 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroff946a6932008-03-11 00:12:29 +00003444 Result += "\nstatic struct {\n";
3445 Result += "\tstruct _objc_method_list *next_method;\n";
3446 Result += "\tint method_count;\n";
3447 Result += "\tstruct _objc_method method_list[";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003448 Result += utostr(NumMethods);
Steve Naroff946a6932008-03-11 00:12:29 +00003449 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003450 Result += prefix;
3451 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3452 Result += "_METHODS_";
3453 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003454 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003455 Result += IsInstanceMethod ? "inst" : "cls";
3456 Result += "_meth\")))= ";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003457 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003458
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003459 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003460 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003461 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003462 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003463 Result += "\", \"";
3464 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003465 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003466 Result += MethodInternalNames[*MethodBegin];
3467 Result += "}\n";
3468 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3469 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003470 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003471 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003472 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003473 Result += "\", \"";
3474 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003475 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003476 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00003477 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003478 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003479 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003480}
3481
Steve Naroff621edce2009-04-29 16:37:50 +00003482/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00003483void RewriteObjC::
Chris Lattner5f9e2722011-07-23 10:55:15 +00003484RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, StringRef prefix,
3485 StringRef ClassName, std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003486 static bool objc_protocol_methods = false;
Steve Naroff621edce2009-04-29 16:37:50 +00003487
3488 // Output struct protocol_methods holder of method selector and type.
3489 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3490 /* struct protocol_methods {
3491 SEL _cmd;
3492 char *method_types;
3493 }
3494 */
3495 Result += "\nstruct _protocol_methods {\n";
3496 Result += "\tstruct objc_selector *_cmd;\n";
3497 Result += "\tchar *method_types;\n";
3498 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003499
Steve Naroff621edce2009-04-29 16:37:50 +00003500 objc_protocol_methods = true;
3501 }
3502 // Do not synthesize the protocol more than once.
3503 if (ObjCSynthesizedProtocols.count(PDecl))
3504 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003505
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003506 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3507 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3508 PDecl->instmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003509 /* struct _objc_protocol_method_list {
3510 int protocol_method_count;
3511 struct protocol_methods protocols[];
3512 }
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003513 */
Steve Naroff621edce2009-04-29 16:37:50 +00003514 Result += "\nstatic struct {\n";
3515 Result += "\tint protocol_method_count;\n";
3516 Result += "\tstruct _protocol_methods protocol_methods[";
3517 Result += utostr(NumMethods);
3518 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3519 Result += PDecl->getNameAsString();
3520 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3521 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003522
Steve Naroff621edce2009-04-29 16:37:50 +00003523 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003524 for (ObjCProtocolDecl::instmeth_iterator
3525 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003526 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003527 if (I == PDecl->instmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003528 Result += "\t ,{{(struct objc_selector *)\"";
3529 else
3530 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar4087f272010-08-17 22:39:59 +00003531 Result += (*I)->getSelector().getAsString();
Steve Naroff621edce2009-04-29 16:37:50 +00003532 std::string MethodTypeString;
3533 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3534 Result += "\", \"";
3535 Result += MethodTypeString;
3536 Result += "\"}\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003537 }
Steve Naroff621edce2009-04-29 16:37:50 +00003538 Result += "\t }\n};\n";
3539 }
Mike Stump1eb44332009-09-09 15:08:12 +00003540
Steve Naroff621edce2009-04-29 16:37:50 +00003541 // Output class methods declared in this protocol.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003542 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3543 PDecl->classmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003544 if (NumMethods > 0) {
3545 /* struct _objc_protocol_method_list {
3546 int protocol_method_count;
3547 struct protocol_methods protocols[];
3548 }
3549 */
3550 Result += "\nstatic struct {\n";
3551 Result += "\tint protocol_method_count;\n";
3552 Result += "\tstruct _protocol_methods protocol_methods[";
3553 Result += utostr(NumMethods);
3554 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3555 Result += PDecl->getNameAsString();
3556 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3557 "{\n\t";
3558 Result += utostr(NumMethods);
3559 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003560
Steve Naroff621edce2009-04-29 16:37:50 +00003561 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003562 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003563 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003564 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003565 if (I == PDecl->classmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003566 Result += "\t ,{{(struct objc_selector *)\"";
3567 else
3568 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar4087f272010-08-17 22:39:59 +00003569 Result += (*I)->getSelector().getAsString();
Steve Naroff621edce2009-04-29 16:37:50 +00003570 std::string MethodTypeString;
3571 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3572 Result += "\", \"";
3573 Result += MethodTypeString;
3574 Result += "\"}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003575 }
Steve Naroff621edce2009-04-29 16:37:50 +00003576 Result += "\t }\n};\n";
3577 }
3578
3579 // Output:
3580 /* struct _objc_protocol {
3581 // Objective-C 1.0 extensions
3582 struct _objc_protocol_extension *isa;
3583 char *protocol_name;
3584 struct _objc_protocol **protocol_list;
3585 struct _objc_protocol_method_list *instance_methods;
3586 struct _objc_protocol_method_list *class_methods;
Mike Stump1eb44332009-09-09 15:08:12 +00003587 };
Steve Naroff621edce2009-04-29 16:37:50 +00003588 */
3589 static bool objc_protocol = false;
3590 if (!objc_protocol) {
3591 Result += "\nstruct _objc_protocol {\n";
3592 Result += "\tstruct _objc_protocol_extension *isa;\n";
3593 Result += "\tchar *protocol_name;\n";
3594 Result += "\tstruct _objc_protocol **protocol_list;\n";
3595 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3596 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003597 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003598
Steve Naroff621edce2009-04-29 16:37:50 +00003599 objc_protocol = true;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003600 }
Mike Stump1eb44332009-09-09 15:08:12 +00003601
Steve Naroff621edce2009-04-29 16:37:50 +00003602 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3603 Result += PDecl->getNameAsString();
3604 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3605 "{\n\t0, \"";
3606 Result += PDecl->getNameAsString();
3607 Result += "\", 0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003608 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003609 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3610 Result += PDecl->getNameAsString();
3611 Result += ", ";
3612 }
3613 else
3614 Result += "0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003615 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003616 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3617 Result += PDecl->getNameAsString();
3618 Result += "\n";
3619 }
3620 else
3621 Result += "0\n";
3622 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003623
Steve Naroff621edce2009-04-29 16:37:50 +00003624 // Mark this protocol as having been generated.
3625 if (!ObjCSynthesizedProtocols.insert(PDecl))
David Blaikieb219cfc2011-09-23 05:06:16 +00003626 llvm_unreachable("protocol already synthesized");
Steve Naroff621edce2009-04-29 16:37:50 +00003627
3628}
3629
3630void RewriteObjC::
3631RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003632 StringRef prefix, StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +00003633 std::string &Result) {
3634 if (Protocols.empty()) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003635
Steve Naroff621edce2009-04-29 16:37:50 +00003636 for (unsigned i = 0; i != Protocols.size(); i++)
3637 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3638
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003639 // Output the top lovel protocol meta-data for the class.
3640 /* struct _objc_protocol_list {
3641 struct _objc_protocol_list *next;
3642 int protocol_count;
3643 struct _objc_protocol *class_protocols[];
3644 }
3645 */
3646 Result += "\nstatic struct {\n";
3647 Result += "\tstruct _objc_protocol_list *next;\n";
3648 Result += "\tint protocol_count;\n";
3649 Result += "\tstruct _objc_protocol *class_protocols[";
3650 Result += utostr(Protocols.size());
3651 Result += "];\n} _OBJC_";
3652 Result += prefix;
3653 Result += "_PROTOCOLS_";
3654 Result += ClassName;
3655 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3656 "{\n\t0, ";
3657 Result += utostr(Protocols.size());
3658 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003659
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003660 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003661 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003662 Result += " \n";
Mike Stump1eb44332009-09-09 15:08:12 +00003663
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003664 for (unsigned i = 1; i != Protocols.size(); i++) {
3665 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003666 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003667 Result += "\n";
3668 }
3669 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003670}
3671
Steve Naroff621edce2009-04-29 16:37:50 +00003672
Mike Stump1eb44332009-09-09 15:08:12 +00003673/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003674/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003675void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003676 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003677 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003678 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003679 ObjCCategoryDecl *CDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00003680 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003681 CDecl = CDecl->getNextClassCategory())
3682 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3683 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003684
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003685 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003686 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003687 FullCategoryName += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003688
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003689 // Build _objc_method_list for class's instance methods if needed
Chris Lattner5f9e2722011-07-23 10:55:15 +00003690 SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003691 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003692
3693 // If any of our property implementations have associated getters or
3694 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003695 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3696 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003697 Prop != PropEnd; ++Prop) {
3698 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3699 continue;
3700 if (!(*Prop)->getPropertyIvarDecl())
3701 continue;
3702 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3703 if (!PD)
3704 continue;
3705 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3706 InstanceMethods.push_back(Getter);
3707 if (PD->isReadOnly())
3708 continue;
3709 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3710 InstanceMethods.push_back(Setter);
3711 }
3712 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003713 true, "CATEGORY_", FullCategoryName.c_str(),
3714 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003715
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003716 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003717 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003718 false, "CATEGORY_", FullCategoryName.c_str(),
3719 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003720
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003721 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003722 // Null CDecl is case of a category implementation with no category interface
3723 if (CDecl)
Steve Naroff621edce2009-04-29 16:37:50 +00003724 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Daniel Dunbar4087f272010-08-17 22:39:59 +00003725 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003726 /* struct _objc_category {
3727 char *category_name;
3728 char *class_name;
3729 struct _objc_method_list *instance_methods;
3730 struct _objc_method_list *class_methods;
3731 struct _objc_protocol_list *protocols;
3732 // Objective-C 1.0 extensions
3733 uint32_t size; // sizeof (struct _objc_category)
Mike Stump1eb44332009-09-09 15:08:12 +00003734 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003735 // @property decl.
Mike Stump1eb44332009-09-09 15:08:12 +00003736 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003737 */
Mike Stump1eb44332009-09-09 15:08:12 +00003738
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003739 static bool objc_category = false;
3740 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003741 Result += "\nstruct _objc_category {\n";
3742 Result += "\tchar *category_name;\n";
3743 Result += "\tchar *class_name;\n";
3744 Result += "\tstruct _objc_method_list *instance_methods;\n";
3745 Result += "\tstruct _objc_method_list *class_methods;\n";
3746 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003747 Result += "\tunsigned int size;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003748 Result += "\tstruct _objc_property_list *instance_properties;\n";
3749 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003750 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003751 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003752 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3753 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003754 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003755 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003756 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003757 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003758 Result += "\"\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003759
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003760 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003761 Result += "\t, (struct _objc_method_list *)"
3762 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3763 Result += FullCategoryName;
3764 Result += "\n";
3765 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003766 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003767 Result += "\t, 0\n";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003768 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003769 Result += "\t, (struct _objc_method_list *)"
3770 "&_OBJC_CATEGORY_CLASS_METHODS_";
3771 Result += FullCategoryName;
3772 Result += "\n";
3773 }
3774 else
3775 Result += "\t, 0\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003776
Chris Lattnercafeb352009-02-20 18:18:36 +00003777 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003778 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003779 Result += FullCategoryName;
3780 Result += "\n";
3781 }
3782 else
3783 Result += "\t, 0\n";
3784 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003785}
3786
Fariborz Jahanian58457172011-12-05 18:43:13 +00003787/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003788/// ivar offset.
Fariborz Jahanian58457172011-12-05 18:43:13 +00003789void RewriteObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003790 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003791 if (ivar->isBitField()) {
3792 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3793 // place all bitfields at offset 0.
3794 Result += "0";
3795 } else {
3796 Result += "__OFFSETOFIVAR__(struct ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003797 Result += ivar->getContainingInterface()->getNameAsString();
Francois Pichet62ec1f22011-09-17 17:15:52 +00003798 if (LangOpts.MicrosoftExt)
Steve Naroff8f3b2652008-07-16 18:22:22 +00003799 Result += "_IMPL";
3800 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003801 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003802 Result += ")";
3803 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003804}
3805
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003806//===----------------------------------------------------------------------===//
3807// Meta Data Emission
3808//===----------------------------------------------------------------------===//
3809
Steve Naroffb29b4272008-04-14 22:03:09 +00003810void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003811 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003812 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00003813
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00003814 // Explicitly declared @interface's are already synthesized.
Steve Naroff33feeb02009-04-20 20:09:33 +00003815 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003816 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003817 // produce correct synthesis as yet.
Fariborz Jahanian58457172011-12-05 18:43:13 +00003818 RewriteObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003819 }
Mike Stump1eb44332009-09-09 15:08:12 +00003820
Chris Lattnerbe6df082007-12-12 07:56:42 +00003821 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003822 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump1eb44332009-09-09 15:08:12 +00003823 ? IDecl->ivar_size()
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003824 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003825 if (NumIvars > 0) {
3826 static bool objc_ivar = false;
3827 if (!objc_ivar) {
3828 /* struct _objc_ivar {
3829 char *ivar_name;
3830 char *ivar_type;
3831 int ivar_offset;
Mike Stump1eb44332009-09-09 15:08:12 +00003832 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003833 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003834 Result += "\nstruct _objc_ivar {\n";
3835 Result += "\tchar *ivar_name;\n";
3836 Result += "\tchar *ivar_type;\n";
3837 Result += "\tint ivar_offset;\n";
3838 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003839
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003840 objc_ivar = true;
3841 }
3842
Steve Naroff946a6932008-03-11 00:12:29 +00003843 /* struct {
3844 int ivar_count;
3845 struct _objc_ivar ivar_list[nIvars];
Mike Stump1eb44332009-09-09 15:08:12 +00003846 };
Steve Naroff946a6932008-03-11 00:12:29 +00003847 */
Mike Stump1eb44332009-09-09 15:08:12 +00003848 Result += "\nstatic struct {\n";
Steve Naroff946a6932008-03-11 00:12:29 +00003849 Result += "\tint ivar_count;\n";
3850 Result += "\tstruct _objc_ivar ivar_list[";
3851 Result += utostr(NumIvars);
3852 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003853 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003854 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003855 "{\n\t";
3856 Result += utostr(NumIvars);
3857 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003858
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003859 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003860 SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003861 if (!IDecl->ivar_empty()) {
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003862 for (ObjCInterfaceDecl::ivar_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003863 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003864 IV != IVEnd; ++IV)
3865 IVars.push_back(*IV);
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003866 IVI = IDecl->ivar_begin();
3867 IVE = IDecl->ivar_end();
Chris Lattnerbe6df082007-12-12 07:56:42 +00003868 } else {
3869 IVI = CDecl->ivar_begin();
3870 IVE = CDecl->ivar_end();
3871 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003872 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003873 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003874 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003875 std::string TmpString, StrEncoding;
3876 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3877 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003878 Result += StrEncoding;
3879 Result += "\", ";
Fariborz Jahanian58457172011-12-05 18:43:13 +00003880 RewriteIvarOffsetComputation(*IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003881 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003882 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003883 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003884 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003885 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003886 std::string TmpString, StrEncoding;
3887 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3888 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003889 Result += StrEncoding;
3890 Result += "\", ";
Fariborz Jahanian58457172011-12-05 18:43:13 +00003891 RewriteIvarOffsetComputation((*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003892 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003893 }
Mike Stump1eb44332009-09-09 15:08:12 +00003894
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003895 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003896 }
Mike Stump1eb44332009-09-09 15:08:12 +00003897
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003898 // Build _objc_method_list for class's instance methods if needed
Chris Lattner5f9e2722011-07-23 10:55:15 +00003899 SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003900 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003901
3902 // If any of our property implementations have associated getters or
3903 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003904 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3905 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003906 Prop != PropEnd; ++Prop) {
3907 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3908 continue;
3909 if (!(*Prop)->getPropertyIvarDecl())
3910 continue;
3911 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3912 if (!PD)
3913 continue;
3914 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanianec3683b2010-10-19 23:47:54 +00003915 if (!Getter->isDefined())
3916 InstanceMethods.push_back(Getter);
Douglas Gregor653f1b12009-04-23 01:02:12 +00003917 if (PD->isReadOnly())
3918 continue;
3919 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanianec3683b2010-10-19 23:47:54 +00003920 if (!Setter->isDefined())
3921 InstanceMethods.push_back(Setter);
Douglas Gregor653f1b12009-04-23 01:02:12 +00003922 }
3923 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003924 true, "", IDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003925
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003926 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003927 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003928 false, "", IDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003929
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003930 // Protocols referenced in class declaration?
Steve Naroff621edce2009-04-29 16:37:50 +00003931 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003932 "CLASS", CDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003933
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003934 // Declaration of class/meta-class metadata
3935 /* struct _objc_class {
3936 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003937 const char *super_class_name;
3938 char *name;
3939 long version;
3940 long info;
3941 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003942 struct _objc_ivar_list *ivars;
3943 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003944 struct objc_cache *cache;
3945 struct objc_protocol_list *protocols;
3946 const char *ivar_layout;
3947 struct _objc_class_ext *ext;
Mike Stump1eb44332009-09-09 15:08:12 +00003948 };
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003949 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003950 static bool objc_class = false;
3951 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003952 Result += "\nstruct _objc_class {\n";
3953 Result += "\tstruct _objc_class *isa;\n";
3954 Result += "\tconst char *super_class_name;\n";
3955 Result += "\tchar *name;\n";
3956 Result += "\tlong version;\n";
3957 Result += "\tlong info;\n";
3958 Result += "\tlong instance_size;\n";
3959 Result += "\tstruct _objc_ivar_list *ivars;\n";
3960 Result += "\tstruct _objc_method_list *methods;\n";
3961 Result += "\tstruct objc_cache *cache;\n";
3962 Result += "\tstruct _objc_protocol_list *protocols;\n";
3963 Result += "\tconst char *ivar_layout;\n";
3964 Result += "\tstruct _objc_class_ext *ext;\n";
3965 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003966 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003967 }
Mike Stump1eb44332009-09-09 15:08:12 +00003968
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003969 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003970 ObjCInterfaceDecl *RootClass = 0;
3971 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003972 while (SuperClass) {
3973 RootClass = SuperClass;
3974 SuperClass = SuperClass->getSuperClass();
3975 }
3976 SuperClass = CDecl->getSuperClass();
Mike Stump1eb44332009-09-09 15:08:12 +00003977
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003978 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003979 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003980 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003981 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003982 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003983 Result += "\"";
3984
3985 if (SuperClass) {
3986 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003987 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003988 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003989 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003990 Result += "\"";
3991 }
3992 else {
3993 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003994 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003995 Result += "\"";
3996 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003997 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003998 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003999 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004000 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff23f41272008-03-11 18:14:26 +00004001 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004002 Result += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00004003 Result += "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004004 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00004005 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004006 Result += ", 0\n";
Chris Lattnercafeb352009-02-20 18:18:36 +00004007 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00004008 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004009 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004010 Result += ",0,0\n";
4011 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00004012 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004013 Result += "\t,0,0,0,0\n";
4014 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004015
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004016 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004017 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004018 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00004019 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004020 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004021 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004022 if (SuperClass) {
4023 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004024 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004025 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004026 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004027 Result += "\"";
4028 }
4029 else {
4030 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004031 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004032 Result += "\"";
4033 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004034 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00004035 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004036 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00004037 Result += ",0";
4038 else {
4039 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00004040 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004041 Result += CDecl->getNameAsString();
Francois Pichet62ec1f22011-09-17 17:15:52 +00004042 if (LangOpts.MicrosoftExt)
Steve Naroffba9ac4e2008-03-10 23:33:22 +00004043 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00004044 Result += ")";
4045 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004046 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00004047 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004048 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004049 Result += "\n\t";
4050 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004051 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004052 Result += ",0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004053 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroff946a6932008-03-11 00:12:29 +00004054 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004055 Result += CDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00004056 Result += ", 0\n\t";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004057 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004058 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004059 Result += ",0,0";
Chris Lattnercafeb352009-02-20 18:18:36 +00004060 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00004061 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004062 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004063 Result += ", 0,0\n";
4064 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004065 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004066 Result += ",0,0,0\n";
4067 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00004068}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00004069
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00004070/// RewriteImplementations - This routine rewrites all method implementations
4071/// and emits meta-data.
4072
Steve Narofface66252008-11-13 20:07:04 +00004073void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004074 int ClsDefCount = ClassImplementation.size();
4075 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00004076
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00004077 // Rewrite implemented methods
4078 for (int i = 0; i < ClsDefCount; i++)
4079 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00004080
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00004081 for (int i = 0; i < CatDefCount; i++)
4082 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00004083}
Mike Stump1eb44332009-09-09 15:08:12 +00004084
Fariborz Jahanian58457172011-12-05 18:43:13 +00004085void RewriteObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
Steve Narofface66252008-11-13 20:07:04 +00004086 int ClsDefCount = ClassImplementation.size();
4087 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00004088
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00004089 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00004090 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004091 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump1eb44332009-09-09 15:08:12 +00004092
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00004093 // For each implemented category, write out all its meta data.
4094 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004095 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroff621edce2009-04-29 16:37:50 +00004096
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004097 // Write objc_symtab metadata
4098 /*
4099 struct _objc_symtab
4100 {
4101 long sel_ref_cnt;
4102 SEL *refs;
4103 short cls_def_cnt;
4104 short cat_def_cnt;
4105 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump1eb44332009-09-09 15:08:12 +00004106 };
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004107 */
Mike Stump1eb44332009-09-09 15:08:12 +00004108
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004109 Result += "\nstruct _objc_symtab {\n";
4110 Result += "\tlong sel_ref_cnt;\n";
4111 Result += "\tSEL *refs;\n";
4112 Result += "\tshort cls_def_cnt;\n";
4113 Result += "\tshort cat_def_cnt;\n";
4114 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
4115 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004116
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004117 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00004118 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004119 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004120 + ", " + utostr(CatDefCount) + "\n";
4121 for (int i = 0; i < ClsDefCount; i++) {
4122 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004123 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004124 Result += "\n";
4125 }
Mike Stump1eb44332009-09-09 15:08:12 +00004126
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004127 for (int i = 0; i < CatDefCount; i++) {
4128 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004129 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004130 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004131 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004132 Result += "\n";
4133 }
Mike Stump1eb44332009-09-09 15:08:12 +00004134
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004135 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004136
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004137 // Write objc_module metadata
Mike Stump1eb44332009-09-09 15:08:12 +00004138
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004139 /*
4140 struct _objc_module {
4141 long version;
4142 long size;
4143 const char *name;
4144 struct _objc_symtab *symtab;
4145 }
4146 */
Mike Stump1eb44332009-09-09 15:08:12 +00004147
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004148 Result += "\nstruct _objc_module {\n";
4149 Result += "\tlong version;\n";
4150 Result += "\tlong size;\n";
4151 Result += "\tconst char *name;\n";
4152 Result += "\tstruct _objc_symtab *symtab;\n";
4153 Result += "};\n\n";
4154 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00004155 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004156 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00004157 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004158 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004159
Francois Pichet62ec1f22011-09-17 17:15:52 +00004160 if (LangOpts.MicrosoftExt) {
Steve Naroff621edce2009-04-29 16:37:50 +00004161 if (ProtocolExprDecls.size()) {
4162 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
4163 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004164 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00004165 E = ProtocolExprDecls.end(); I != E; ++I) {
4166 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
4167 Result += (*I)->getNameAsString();
4168 Result += " = &_OBJC_PROTOCOL_";
4169 Result += (*I)->getNameAsString();
4170 Result += ";\n";
4171 }
4172 Result += "#pragma data_seg(pop)\n\n";
4173 }
Steve Naroff4f943c22008-03-10 20:43:59 +00004174 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00004175 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004176 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
4177 Result += "&_OBJC_MODULES;\n";
4178 Result += "#pragma data_seg(pop)\n\n";
4179 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004180}
Chris Lattner311ff022007-10-16 22:36:42 +00004181
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004182void RewriteObjC::RewriteByRefString(std::string &ResultStr,
4183 const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004184 ValueDecl *VD, bool def) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004185 assert(BlockByRefDeclNo.count(VD) &&
4186 "RewriteByRefString: ByRef decl missing");
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004187 if (def)
4188 ResultStr += "struct ";
4189 ResultStr += "__Block_byref_" + Name +
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004190 "_" + utostr(BlockByRefDeclNo[VD]) ;
4191}
4192
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004193static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4194 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4195 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4196 return false;
4197}
4198
Steve Naroff54055232008-10-27 17:20:55 +00004199std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004200 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00004201 std::string Tag) {
4202 const FunctionType *AFT = CE->getFunctionType();
4203 QualType RT = AFT->getResultType();
4204 std::string StructRef = "struct " + Tag;
Douglas Gregor30c42402011-09-27 22:38:19 +00004205 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Daniel Dunbar4087f272010-08-17 22:39:59 +00004206 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00004207
Steve Naroff54055232008-10-27 17:20:55 +00004208 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00004209
Douglas Gregor72564e72009-02-26 23:50:07 +00004210 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004211 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00004212 // block (to reference imported block decl refs).
4213 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00004214 } else if (BD->param_empty()) {
4215 S += "(" + StructRef + " *__cself)";
4216 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00004217 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00004218 assert(FT && "SynthesizeBlockFunc: No function proto");
4219 S += '(';
4220 // first add the implicit argument.
4221 S += StructRef + " *__cself, ";
4222 std::string ParamStr;
4223 for (BlockDecl::param_iterator AI = BD->param_begin(),
4224 E = BD->param_end(); AI != E; ++AI) {
4225 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004226 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004227 QualType QT = (*AI)->getType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004228 if (convertBlockPointerToFunctionPointer(QT))
Douglas Gregor30c42402011-09-27 22:38:19 +00004229 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004230 else
Douglas Gregor30c42402011-09-27 22:38:19 +00004231 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Steve Naroff54055232008-10-27 17:20:55 +00004232 S += ParamStr;
4233 }
4234 if (FT->isVariadic()) {
4235 if (!BD->param_empty()) S += ", ";
4236 S += "...";
4237 }
4238 S += ')';
4239 }
4240 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004241
Steve Naroff54055232008-10-27 17:20:55 +00004242 // Create local declarations to avoid rewriting all closure decl ref exprs.
4243 // First, emit a declaration for all "by ref" decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004244 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004245 E = BlockByRefDecls.end(); I != E; ++I) {
4246 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004247 std::string Name = (*I)->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004248 std::string TypeString;
4249 RewriteByRefString(TypeString, Name, (*I));
4250 TypeString += " *";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004251 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004252 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004253 }
Steve Naroff54055232008-10-27 17:20:55 +00004254 // Next, emit a declaration for all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004255 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004256 E = BlockByCopyDecls.end(); I != E; ++I) {
4257 S += " ";
Steve Naroff54055232008-10-27 17:20:55 +00004258 // Handle nested closure invocation. For example:
4259 //
4260 // void (^myImportedClosure)(void);
4261 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004262 //
Steve Naroff54055232008-10-27 17:20:55 +00004263 // void (^anotherClosure)(void);
4264 // anotherClosure = ^(void) {
4265 // myImportedClosure(); // import and invoke the closure
4266 // };
4267 //
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004268 if (isTopLevelBlockPointerType((*I)->getType())) {
4269 RewriteBlockPointerTypeVariable(S, (*I));
4270 S += " = (";
4271 RewriteBlockPointerType(S, (*I)->getType());
4272 S += ")";
4273 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4274 }
4275 else {
Fariborz Jahanian210c2482010-02-16 17:26:03 +00004276 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004277 QualType QT = (*I)->getType();
4278 if (HasLocalVariableExternalStorage(*I))
4279 QT = Context->getPointerType(QT);
Douglas Gregor30c42402011-09-27 22:38:19 +00004280 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004281 S += Name + " = __cself->" +
4282 (*I)->getNameAsString() + "; // bound by copy\n";
4283 }
Steve Naroff54055232008-10-27 17:20:55 +00004284 }
4285 std::string RewrittenStr = RewrittenBlockExprs[CE];
4286 const char *cstr = RewrittenStr.c_str();
4287 while (*cstr++ != '{') ;
4288 S += cstr;
4289 S += "\n";
4290 return S;
4291}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00004292
Steve Naroff54055232008-10-27 17:20:55 +00004293std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004294 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00004295 std::string Tag) {
4296 std::string StructRef = "struct " + Tag;
4297 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00004298
Steve Naroff54055232008-10-27 17:20:55 +00004299 S += funcName;
4300 S += "_block_copy_" + utostr(i);
4301 S += "(" + StructRef;
4302 S += "*dst, " + StructRef;
4303 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004304 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004305 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004306 ValueDecl *VD = (*I);
Steve Naroff5bc60d02008-12-16 15:50:30 +00004307 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004308 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00004309 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004310 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004311 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004312 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004313 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00004314 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004315 else
4316 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004317 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004318 S += "}\n";
4319
Steve Naroff54055232008-10-27 17:20:55 +00004320 S += "\nstatic void __";
4321 S += funcName;
4322 S += "_block_dispose_" + utostr(i);
4323 S += "(" + StructRef;
4324 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004325 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004326 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004327 ValueDecl *VD = (*I);
Steve Naroff5bc60d02008-12-16 15:50:30 +00004328 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004329 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004330 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004331 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004332 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00004333 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004334 else
4335 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004336 }
Mike Stump1eb44332009-09-09 15:08:12 +00004337 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00004338 return S;
4339}
4340
Steve Naroff01aec112009-12-06 21:14:13 +00004341std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4342 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00004343 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00004344 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00004345
Steve Naroff54055232008-10-27 17:20:55 +00004346 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004347 S += " struct " + Desc;
4348 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004349
Steve Naroff01aec112009-12-06 21:14:13 +00004350 Constructor += "(void *fp, "; // Invoke function pointer.
4351 Constructor += "struct " + Desc; // Descriptor pointer.
4352 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00004353
Steve Naroff54055232008-10-27 17:20:55 +00004354 if (BlockDeclRefs.size()) {
4355 // Output all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004356 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004357 E = BlockByCopyDecls.end(); I != E; ++I) {
4358 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004359 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004360 std::string ArgName = "_" + FieldName;
4361 // Handle nested closure invocation. For example:
4362 //
4363 // void (^myImportedBlock)(void);
4364 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004365 //
Steve Naroff54055232008-10-27 17:20:55 +00004366 // void (^anotherBlock)(void);
4367 // anotherBlock = ^(void) {
4368 // myImportedBlock(); // import and invoke the closure
4369 // };
4370 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004371 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00004372 S += "struct __block_impl *";
4373 Constructor += ", void *" + ArgName;
4374 } else {
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004375 QualType QT = (*I)->getType();
4376 if (HasLocalVariableExternalStorage(*I))
4377 QT = Context->getPointerType(QT);
Douglas Gregor30c42402011-09-27 22:38:19 +00004378 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4379 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
Steve Naroff54055232008-10-27 17:20:55 +00004380 Constructor += ", " + ArgName;
4381 }
4382 S += FieldName + ";\n";
4383 }
4384 // Output all "by ref" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004385 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004386 E = BlockByRefDecls.end(); I != E; ++I) {
4387 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004388 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004389 std::string ArgName = "_" + FieldName;
Fariborz Jahanian651ba522011-04-01 23:08:13 +00004390 {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004391 std::string TypeString;
4392 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004393 TypeString += " *";
4394 FieldName = TypeString + FieldName;
4395 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00004396 Constructor += ", " + ArgName;
4397 }
4398 S += FieldName + "; // by ref\n";
4399 }
4400 // Finish writing the constructor.
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004401 Constructor += ", int flags=0)";
4402 // Initialize all "by copy" arguments.
4403 bool firsTime = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004404 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004405 E = BlockByCopyDecls.end(); I != E; ++I) {
4406 std::string Name = (*I)->getNameAsString();
4407 if (firsTime) {
4408 Constructor += " : ";
4409 firsTime = false;
4410 }
4411 else
4412 Constructor += ", ";
4413 if (isTopLevelBlockPointerType((*I)->getType()))
4414 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4415 else
4416 Constructor += Name + "(_" + Name + ")";
4417 }
4418 // Initialize all "by ref" arguments.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004419 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004420 E = BlockByRefDecls.end(); I != E; ++I) {
4421 std::string Name = (*I)->getNameAsString();
4422 if (firsTime) {
4423 Constructor += " : ";
4424 firsTime = false;
4425 }
4426 else
4427 Constructor += ", ";
Fariborz Jahanian651ba522011-04-01 23:08:13 +00004428 Constructor += Name + "(_" + Name + "->__forwarding)";
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004429 }
4430
4431 Constructor += " {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004432 if (GlobalVarDecl)
4433 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4434 else
4435 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004436 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004437
Steve Naroff01aec112009-12-06 21:14:13 +00004438 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004439 } else {
4440 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00004441 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004442 if (GlobalVarDecl)
4443 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4444 else
4445 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004446 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4447 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004448 }
4449 Constructor += " ";
4450 Constructor += "}\n";
4451 S += Constructor;
4452 S += "};\n";
4453 return S;
4454}
4455
Steve Naroff01aec112009-12-06 21:14:13 +00004456std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4457 std::string ImplTag, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004458 StringRef FunName,
Steve Naroff01aec112009-12-06 21:14:13 +00004459 unsigned hasCopy) {
4460 std::string S = "\nstatic struct " + DescTag;
4461
4462 S += " {\n unsigned long reserved;\n";
4463 S += " unsigned long Block_size;\n";
4464 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004465 S += " void (*copy)(struct ";
4466 S += ImplTag; S += "*, struct ";
4467 S += ImplTag; S += "*);\n";
4468
4469 S += " void (*dispose)(struct ";
4470 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004471 }
4472 S += "} ";
4473
4474 S += DescTag + "_DATA = { 0, sizeof(struct ";
4475 S += ImplTag + ")";
4476 if (hasCopy) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00004477 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4478 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff01aec112009-12-06 21:14:13 +00004479 }
4480 S += "};\n";
4481 return S;
4482}
4483
Steve Naroff54055232008-10-27 17:20:55 +00004484void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004485 StringRef FunName) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004486 // Insert declaration for the function in which block literal is used.
Fariborz Jahanianbf070122010-01-15 18:14:52 +00004487 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004488 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004489 bool RewriteSC = (GlobalVarDecl &&
4490 !Blocks.empty() &&
John McCalld931b082010-08-26 03:08:43 +00004491 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004492 GlobalVarDecl->getType().getCVRQualifiers());
4493 if (RewriteSC) {
4494 std::string SC(" void __");
4495 SC += GlobalVarDecl->getNameAsString();
4496 SC += "() {}";
4497 InsertText(FunLocStart, SC);
4498 }
4499
Steve Naroff54055232008-10-27 17:20:55 +00004500 // Insert closures that were part of the function.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004501 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4502 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004503 // Need to copy-in the inner copied-in variables not actually used in this
4504 // block.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004505 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4506 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
4507 ValueDecl *VD = Exp->getDecl();
4508 BlockDeclRefs.push_back(Exp);
4509 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
4510 BlockByCopyDeclsPtrSet.insert(VD);
4511 BlockByCopyDecls.push_back(VD);
4512 }
4513 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4514 BlockByRefDeclsPtrSet.insert(VD);
4515 BlockByRefDecls.push_back(VD);
4516 }
Fariborz Jahanian92c85682010-10-05 18:05:06 +00004517 // imported objects in the inner blocks not used in the outer
4518 // blocks must be copied/disposed in the outer block as well.
4519 if (Exp->isByRef() ||
4520 VD->getType()->isObjCObjectPointerType() ||
4521 VD->getType()->isBlockPointerType())
4522 ImportedBlockDecls.insert(VD);
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004523 }
Steve Naroff54055232008-10-27 17:20:55 +00004524
Daniel Dunbar4087f272010-08-17 22:39:59 +00004525 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4526 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00004527
Steve Naroff01aec112009-12-06 21:14:13 +00004528 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00004529
Benjamin Kramerd999b372010-02-14 14:14:16 +00004530 InsertText(FunLocStart, CI);
Steve Naroff54055232008-10-27 17:20:55 +00004531
Steve Naroff01aec112009-12-06 21:14:13 +00004532 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00004533
Benjamin Kramerd999b372010-02-14 14:14:16 +00004534 InsertText(FunLocStart, CF);
Steve Naroff54055232008-10-27 17:20:55 +00004535
4536 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00004537 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004538 InsertText(FunLocStart, HF);
Steve Naroff54055232008-10-27 17:20:55 +00004539 }
Steve Naroff01aec112009-12-06 21:14:13 +00004540 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4541 ImportedBlockDecls.size() > 0);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004542 InsertText(FunLocStart, BD);
Mike Stump1eb44332009-09-09 15:08:12 +00004543
Steve Naroff54055232008-10-27 17:20:55 +00004544 BlockDeclRefs.clear();
4545 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004546 BlockByRefDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004547 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004548 BlockByCopyDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004549 ImportedBlockDecls.clear();
4550 }
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004551 if (RewriteSC) {
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004552 // Must insert any 'const/volatile/static here. Since it has been
4553 // removed as result of rewriting of block literals.
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004554 std::string SC;
John McCalld931b082010-08-26 03:08:43 +00004555 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004556 SC = "static ";
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004557 if (GlobalVarDecl->getType().isConstQualified())
4558 SC += "const ";
4559 if (GlobalVarDecl->getType().isVolatileQualified())
4560 SC += "volatile ";
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004561 if (GlobalVarDecl->getType().isRestrictQualified())
4562 SC += "restrict ";
4563 InsertText(FunLocStart, SC);
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004564 }
4565
Steve Naroff54055232008-10-27 17:20:55 +00004566 Blocks.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004567 InnerDeclRefsCount.clear();
4568 InnerDeclRefs.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004569 RewrittenBlockExprs.clear();
4570}
4571
4572void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4573 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00004574 StringRef FuncName = FD->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00004575
Steve Naroff54055232008-10-27 17:20:55 +00004576 SynthesizeBlockLiterals(FunLocStart, FuncName);
4577}
4578
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004579static void BuildUniqueMethodName(std::string &Name,
4580 ObjCMethodDecl *MD) {
4581 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar4087f272010-08-17 22:39:59 +00004582 Name = IFace->getName();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004583 Name += "__" + MD->getSelector().getAsString();
4584 // Convert colons to underscores.
4585 std::string::size_type loc = 0;
4586 while ((loc = Name.find(":", loc)) != std::string::npos)
4587 Name.replace(loc, 1, "_");
4588}
4589
Steve Naroff54055232008-10-27 17:20:55 +00004590void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00004591 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4592 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanian0e1c99a2010-01-29 01:55:49 +00004593 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004594 std::string FuncName;
4595 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar4087f272010-08-17 22:39:59 +00004596 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff54055232008-10-27 17:20:55 +00004597}
4598
4599void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +00004600 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff54055232008-10-27 17:20:55 +00004601 if (*CI) {
4602 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4603 GetBlockDeclRefExprs(CBE->getBody());
4604 else
4605 GetBlockDeclRefExprs(*CI);
4606 }
4607 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004608 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Steve Naroff54055232008-10-27 17:20:55 +00004609 // FIXME: Handle enums.
4610 if (!isa<FunctionDecl>(CDRE->getDecl()))
4611 BlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004612 }
4613 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4614 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
4615 BlockDeclRefExpr *BDRE =
John McCall6b5a61b2011-02-07 10:33:21 +00004616 new (Context)BlockDeclRefExpr(cast<VarDecl>(DRE->getDecl()),
4617 DRE->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00004618 VK_LValue, DRE->getLocation(), false);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004619 BlockDeclRefs.push_back(BDRE);
4620 }
4621
Steve Naroff54055232008-10-27 17:20:55 +00004622 return;
4623}
4624
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004625void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004626 SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004627 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
John McCall7502c1d2011-02-13 04:07:26 +00004628 for (Stmt::child_range CI = S->children(); CI; ++CI)
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004629 if (*CI) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004630 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4631 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004632 GetInnerBlockDeclRefExprs(CBE->getBody(),
4633 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004634 InnerContexts);
4635 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004636 else
4637 GetInnerBlockDeclRefExprs(*CI,
4638 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004639 InnerContexts);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004640
4641 }
4642 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004643 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004644 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004645 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004646 InnerBlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004647 }
4648 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4649 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4650 if (Var->isFunctionOrMethodVarDecl())
4651 ImportedLocalExternalDecls.insert(Var);
4652 }
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004653
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004654 return;
4655}
4656
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004657/// convertFunctionTypeOfBlocks - This routine converts a function type
4658/// whose result type may be a block pointer or whose argument type(s)
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00004659/// might be block pointers to an equivalent function type replacing
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004660/// all block pointers to function pointers.
4661QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4662 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4663 // FTP will be null for closures that don't take arguments.
4664 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004665 SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004666 QualType Res = FT->getResultType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004667 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004668
4669 if (FTP) {
4670 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4671 E = FTP->arg_type_end(); I && (I != E); ++I) {
4672 QualType t = *I;
4673 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004674 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004675 HasBlockType = true;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004676 ArgTypes.push_back(t);
4677 }
4678 }
4679 QualType FuncType;
4680 // FIXME. Does this work if block takes no argument but has a return type
4681 // which is of block type?
4682 if (HasBlockType)
John McCalle23cf432010-12-14 08:05:40 +00004683 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004684 else FuncType = QualType(FT, 0);
4685 return FuncType;
4686}
4687
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004688Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00004689 // Navigate to relevant type information.
Steve Naroff54055232008-10-27 17:20:55 +00004690 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004691
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004692 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004693 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004694 } else if (const BlockDeclRefExpr *CDRE =
4695 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004696 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004697 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004698 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004699 }
4700 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4701 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4702 }
4703 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4704 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4705 else if (const ConditionalOperator *CEXPR =
4706 dyn_cast<ConditionalOperator>(BlockExp)) {
4707 Expr *LHSExp = CEXPR->getLHS();
4708 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4709 Expr *RHSExp = CEXPR->getRHS();
4710 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4711 Expr *CONDExp = CEXPR->getCond();
4712 ConditionalOperator *CondExpr =
4713 new (Context) ConditionalOperator(CONDExp,
4714 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00004715 SourceLocation(), cast<Expr>(RHSStmt),
John McCall09431682010-11-18 19:01:18 +00004716 Exp->getType(), VK_RValue, OK_Ordinary);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004717 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00004718 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4719 CPT = IRE->getType()->getAs<BlockPointerType>();
John McCall4b9c2d22011-11-06 09:01:30 +00004720 } else if (const PseudoObjectExpr *POE
4721 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4722 CPT = POE->getType()->castAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004723 } else {
4724 assert(1 && "RewriteBlockClass: Bad type");
4725 }
4726 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00004727 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00004728 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00004729 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00004730 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004731
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004732 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004733 SourceLocation(), SourceLocation(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004734 &Context->Idents.get("__block_impl"));
4735 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00004736
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004737 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004738 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004739
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004740 // Push the block argument type.
4741 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00004742 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004743 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004744 E = FTP->arg_type_end(); I && (I != E); ++I) {
4745 QualType t = *I;
4746 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00004747 if (!convertBlockPointerToFunctionPointer(t))
4748 convertToUnqualifiedObjCType(t);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004749 ArgTypes.push_back(t);
4750 }
Steve Naroff54055232008-10-27 17:20:55 +00004751 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004752 // Now do the pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00004753 QualType PtrToFuncCastType
4754 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
Mike Stump1eb44332009-09-09 15:08:12 +00004755
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004756 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00004757
John McCall9d125032010-01-15 18:39:57 +00004758 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCalla5bbc502010-11-15 09:46:46 +00004759 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00004760 const_cast<Expr*>(BlockExp));
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004761 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004762 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4763 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004764 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00004765
Douglas Gregor44b43212008-12-11 16:49:14 +00004766 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004767 SourceLocation(),
4768 &Context->Idents.get("FuncPtr"),
4769 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00004770 /*BitWidth=*/0, /*Mutable=*/true,
4771 /*HasInit=*/false);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004772 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004773 FD->getType(), VK_LValue,
4774 OK_Ordinary);
Mike Stump1eb44332009-09-09 15:08:12 +00004775
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00004776
John McCall9d125032010-01-15 18:39:57 +00004777 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
John McCalla5bbc502010-11-15 09:46:46 +00004778 CK_BitCast, ME);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004779 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00004780
Chris Lattner5f9e2722011-07-23 10:55:15 +00004781 SmallVector<Expr*, 8> BlkExprs;
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004782 // Add the implicit argument.
4783 BlkExprs.push_back(BlkCast);
4784 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004785 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004786 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004787 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00004788 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004789 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4790 BlkExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00004791 Exp->getType(), VK_RValue,
4792 SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004793 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00004794}
4795
Steve Naroff621edce2009-04-29 16:37:50 +00004796// We need to return the rewritten expression to handle cases where the
4797// BlockDeclRefExpr is embedded in another expression being rewritten.
4798// For example:
4799//
4800// int main() {
4801// __block Foo *f;
4802// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00004803//
Steve Naroff621edce2009-04-29 16:37:50 +00004804// void (^myblock)() = ^() {
4805// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4806// i = 77;
4807// };
4808//}
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004809Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00004810 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004811 // for each DeclRefExp where BYREFVAR is name of the variable.
4812 ValueDecl *VD;
4813 bool isArrow = true;
4814 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4815 VD = BDRE->getDecl();
4816 else {
4817 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4818 isArrow = false;
4819 }
4820
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004821 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004822 SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004823 &Context->Idents.get("__forwarding"),
4824 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00004825 /*BitWidth=*/0, /*Mutable=*/true,
4826 /*HasInit=*/false);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004827 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4828 FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004829 FD->getType(), VK_LValue,
4830 OK_Ordinary);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004831
Chris Lattner5f9e2722011-07-23 10:55:15 +00004832 StringRef Name = VD->getName();
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004833 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004834 &Context->Idents.get(Name),
4835 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00004836 /*BitWidth=*/0, /*Mutable=*/true,
4837 /*HasInit=*/false);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004838 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004839 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004840
4841
4842
Steve Naroffdf8570d2009-02-02 17:19:26 +00004843 // Need parens to enforce precedence.
Fariborz Jahanian380ee502011-04-01 19:19:28 +00004844 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4845 DeclRefExp->getExprLoc(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004846 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004847 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00004848 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00004849}
4850
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004851// Rewrites the imported local variable V with external storage
4852// (static, extern, etc.) as *V
4853//
4854Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4855 ValueDecl *VD = DRE->getDecl();
4856 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4857 if (!ImportedLocalExternalDecls.count(Var))
4858 return DRE;
John McCallf89e55a2010-11-18 06:31:45 +00004859 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4860 VK_LValue, OK_Ordinary,
4861 DRE->getLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004862 // Need parens to enforce precedence.
4863 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4864 Exp);
4865 ReplaceStmt(DRE, PE);
4866 return PE;
4867}
4868
Steve Naroffb2f9e512008-11-03 23:29:32 +00004869void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4870 SourceLocation LocStart = CE->getLParenLoc();
4871 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00004872
4873 // Need to avoid trying to rewrite synthesized casts.
4874 if (LocStart.isInvalid())
4875 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00004876 // Need to avoid trying to rewrite casts contained in macros.
4877 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4878 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004879
Steve Naroff54055232008-10-27 17:20:55 +00004880 const char *startBuf = SM->getCharacterData(LocStart);
4881 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004882 QualType QT = CE->getType();
4883 const Type* TypePtr = QT->getAs<Type>();
4884 if (isa<TypeOfExprType>(TypePtr)) {
4885 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4886 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4887 std::string TypeAsString = "(";
Fariborz Jahanianafad76f2010-02-18 01:20:22 +00004888 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004889 TypeAsString += ")";
Benjamin Kramerd999b372010-02-14 14:14:16 +00004890 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004891 return;
4892 }
Steve Naroff54055232008-10-27 17:20:55 +00004893 // advance the location to startArgList.
4894 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00004895
Steve Naroff54055232008-10-27 17:20:55 +00004896 while (*argPtr++ && (argPtr < endBuf)) {
4897 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004898 case '^':
4899 // Replace the '^' with '*'.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004900 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004901 ReplaceText(LocStart, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004902 break;
Steve Naroff54055232008-10-27 17:20:55 +00004903 }
4904 }
4905 return;
4906}
4907
4908void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4909 SourceLocation DeclLoc = FD->getLocation();
4910 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004911
Steve Naroff54055232008-10-27 17:20:55 +00004912 // We have 1 or more arguments that have closure pointers.
4913 const char *startBuf = SM->getCharacterData(DeclLoc);
4914 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00004915
Steve Naroff54055232008-10-27 17:20:55 +00004916 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004917
Steve Naroff54055232008-10-27 17:20:55 +00004918 parenCount++;
4919 // advance the location to startArgList.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004920 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
Steve Naroff54055232008-10-27 17:20:55 +00004921 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00004922
Steve Naroff54055232008-10-27 17:20:55 +00004923 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00004924
Steve Naroff54055232008-10-27 17:20:55 +00004925 while (*argPtr++ && parenCount) {
4926 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004927 case '^':
4928 // Replace the '^' with '*'.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004929 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004930 ReplaceText(DeclLoc, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004931 break;
4932 case '(':
4933 parenCount++;
4934 break;
4935 case ')':
4936 parenCount--;
4937 break;
Steve Naroff54055232008-10-27 17:20:55 +00004938 }
4939 }
4940 return;
4941}
4942
4943bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004944 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004945 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004946 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004947 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004948 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004949 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004950 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004951 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004952 }
4953 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004954 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004955 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004956 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004957 return true;
4958 }
4959 return false;
4960}
4961
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004962bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4963 const FunctionProtoType *FTP;
4964 const PointerType *PT = QT->getAs<PointerType>();
4965 if (PT) {
4966 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4967 } else {
4968 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4969 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4970 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4971 }
4972 if (FTP) {
4973 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004974 E = FTP->arg_type_end(); I != E; ++I) {
4975 if ((*I)->isObjCQualifiedIdType())
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004976 return true;
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004977 if ((*I)->isObjCObjectPointerType() &&
4978 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4979 return true;
4980 }
4981
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004982 }
4983 return false;
4984}
4985
Ted Kremenek8189cde2009-02-07 01:47:29 +00004986void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4987 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00004988 const char *argPtr = strchr(Name, '(');
4989 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004990
Steve Naroff54055232008-10-27 17:20:55 +00004991 LParen = argPtr; // output the start.
4992 argPtr++; // skip past the left paren.
4993 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004994
Steve Naroff54055232008-10-27 17:20:55 +00004995 while (*argPtr && parenCount) {
4996 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004997 case '(': parenCount++; break;
4998 case ')': parenCount--; break;
4999 default: break;
Steve Naroff54055232008-10-27 17:20:55 +00005000 }
5001 if (parenCount) argPtr++;
5002 }
5003 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
5004 RParen = argPtr; // output the end
5005}
5006
5007void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
5008 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5009 RewriteBlockPointerFunctionArgs(FD);
5010 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005011 }
Steve Naroff54055232008-10-27 17:20:55 +00005012 // Handle Variables and Typedefs.
5013 SourceLocation DeclLoc = ND->getLocation();
5014 QualType DeclT;
5015 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
5016 DeclT = VD->getType();
Richard Smith162e1c12011-04-15 14:24:37 +00005017 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
Steve Naroff54055232008-10-27 17:20:55 +00005018 DeclT = TDD->getUnderlyingType();
5019 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
5020 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00005021 else
David Blaikieb219cfc2011-09-23 05:06:16 +00005022 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00005023
Steve Naroff54055232008-10-27 17:20:55 +00005024 const char *startBuf = SM->getCharacterData(DeclLoc);
5025 const char *endBuf = startBuf;
5026 // scan backward (from the decl location) for the end of the previous decl.
5027 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
5028 startBuf--;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00005029 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005030 std::string buf;
5031 unsigned OrigLength=0;
Steve Naroff54055232008-10-27 17:20:55 +00005032 // *startBuf != '^' if we are dealing with a pointer to function that
5033 // may take block argument types (which will be handled below).
5034 if (*startBuf == '^') {
5035 // Replace the '^' with '*', computing a negative offset.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005036 buf = '*';
5037 startBuf++;
5038 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00005039 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005040 while (*startBuf != ')') {
5041 buf += *startBuf;
5042 startBuf++;
5043 OrigLength++;
5044 }
5045 buf += ')';
5046 OrigLength++;
5047
5048 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
5049 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
Steve Naroff54055232008-10-27 17:20:55 +00005050 // Replace the '^' with '*' for arguments.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005051 // Replace id<P> with id/*<>*/
Steve Naroff54055232008-10-27 17:20:55 +00005052 DeclLoc = ND->getLocation();
5053 startBuf = SM->getCharacterData(DeclLoc);
5054 const char *argListBegin, *argListEnd;
5055 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
5056 while (argListBegin < argListEnd) {
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005057 if (*argListBegin == '^')
5058 buf += '*';
5059 else if (*argListBegin == '<') {
5060 buf += "/*";
5061 buf += *argListBegin++;
5062 OrigLength++;;
5063 while (*argListBegin != '>') {
5064 buf += *argListBegin++;
5065 OrigLength++;
5066 }
5067 buf += *argListBegin;
5068 buf += "*/";
Steve Naroff54055232008-10-27 17:20:55 +00005069 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005070 else
5071 buf += *argListBegin;
Steve Naroff54055232008-10-27 17:20:55 +00005072 argListBegin++;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005073 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00005074 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005075 buf += ')';
5076 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00005077 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005078 ReplaceText(Start, OrigLength, buf);
5079
Steve Naroff54055232008-10-27 17:20:55 +00005080 return;
5081}
5082
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005083
5084/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5085/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5086/// struct Block_byref_id_object *src) {
5087/// _Block_object_assign (&_dest->object, _src->object,
5088/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5089/// [|BLOCK_FIELD_IS_WEAK]) // object
5090/// _Block_object_assign(&_dest->object, _src->object,
5091/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5092/// [|BLOCK_FIELD_IS_WEAK]) // block
5093/// }
5094/// And:
5095/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5096/// _Block_object_dispose(_src->object,
5097/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5098/// [|BLOCK_FIELD_IS_WEAK]) // object
5099/// _Block_object_dispose(_src->object,
5100/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5101/// [|BLOCK_FIELD_IS_WEAK]) // block
5102/// }
5103
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005104std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5105 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005106 std::string S;
Benjamin Kramer1211a712010-01-10 19:57:50 +00005107 if (CopyDestroyCache.count(flag))
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005108 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005109 CopyDestroyCache.insert(flag);
5110 S = "static void __Block_byref_id_object_copy_";
5111 S += utostr(flag);
5112 S += "(void *dst, void *src) {\n";
5113
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005114 // offset into the object pointer is computed as:
5115 // void * + void* + int + int + void* + void *
5116 unsigned IntSize =
5117 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5118 unsigned VoidPtrSize =
5119 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5120
Ken Dyck0c4e5d62011-04-30 16:08:27 +00005121 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005122 S += " _Block_object_assign((char*)dst + ";
5123 S += utostr(offset);
5124 S += ", *(void * *) ((char*)src + ";
5125 S += utostr(offset);
5126 S += "), ";
5127 S += utostr(flag);
5128 S += ");\n}\n";
5129
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005130 S += "static void __Block_byref_id_object_dispose_";
5131 S += utostr(flag);
5132 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005133 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5134 S += utostr(offset);
5135 S += "), ";
5136 S += utostr(flag);
5137 S += ");\n}\n";
5138 return S;
5139}
5140
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005141/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5142/// the declaration into:
5143/// struct __Block_byref_ND {
5144/// void *__isa; // NULL for everything except __weak pointers
5145/// struct __Block_byref_ND *__forwarding;
5146/// int32_t __flags;
5147/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005148/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5149/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005150/// typex ND;
5151/// };
5152///
5153/// It then replaces declaration of ND variable with:
5154/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5155/// __size=sizeof(struct __Block_byref_ND),
5156/// ND=initializer-if-any};
5157///
5158///
5159void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005160 // Insert declaration for the function in which block literal is
5161 // used.
5162 if (CurFunctionDeclToDeclareForBlock)
5163 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005164 int flag = 0;
5165 int isa = 0;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005166 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahaniand64a4f42010-02-26 22:49:11 +00005167 if (DeclLoc.isInvalid())
5168 // If type location is missing, it is because of missing type (a warning).
5169 // Use variable's location which is good for this case.
5170 DeclLoc = ND->getLocation();
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005171 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00005172 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00005173 X = SM->getExpansionLoc(X);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00005174 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005175 std::string Name(ND->getNameAsString());
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005176 std::string ByrefType;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00005177 RewriteByRefString(ByrefType, Name, ND, true);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005178 ByrefType += " {\n";
5179 ByrefType += " void *__isa;\n";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005180 RewriteByRefString(ByrefType, Name, ND);
5181 ByrefType += " *__forwarding;\n";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005182 ByrefType += " int __flags;\n";
5183 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005184 // Add void *__Block_byref_id_object_copy;
5185 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005186 QualType Ty = ND->getType();
5187 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
5188 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005189 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5190 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005191 }
Fariborz Jahanian822ac872011-03-31 22:49:32 +00005192
5193 QualType T = Ty;
5194 (void)convertBlockPointerToFunctionPointer(T);
Douglas Gregor30c42402011-09-27 22:38:19 +00005195 T.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian822ac872011-03-31 22:49:32 +00005196
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005197 ByrefType += " " + Name + ";\n";
5198 ByrefType += "};\n";
5199 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005200 SourceLocation FunLocStart;
5201 if (CurFunctionDef)
5202 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
5203 else {
5204 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5205 FunLocStart = CurMethodDef->getLocStart();
5206 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00005207 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005208 if (Ty.isObjCGCWeak()) {
5209 flag |= BLOCK_FIELD_IS_WEAK;
5210 isa = 1;
5211 }
5212
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005213 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005214 flag = BLOCK_BYREF_CALLER;
5215 QualType Ty = ND->getType();
5216 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5217 if (Ty->isBlockPointerType())
5218 flag |= BLOCK_FIELD_IS_BLOCK;
5219 else
5220 flag |= BLOCK_FIELD_IS_OBJECT;
5221 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005222 if (!HF.empty())
Benjamin Kramerd999b372010-02-14 14:14:16 +00005223 InsertText(FunLocStart, HF);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005224 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005225
5226 // struct __Block_byref_ND ND =
5227 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5228 // initializer-if-any};
5229 bool hasInit = (ND->getInit() != 0);
Fariborz Jahaniane1f84f82010-01-05 18:15:57 +00005230 unsigned flags = 0;
5231 if (HasCopyAndDispose)
5232 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005233 Name = ND->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005234 ByrefType.clear();
5235 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005236 std::string ForwardingCastType("(");
5237 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005238 if (!hasInit) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005239 ByrefType += " " + Name + " = {(void*)";
5240 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005241 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005242 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005243 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005244 ByrefType += "sizeof(";
5245 RewriteByRefString(ByrefType, Name, ND);
5246 ByrefType += ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005247 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005248 ByrefType += ", __Block_byref_id_object_copy_";
5249 ByrefType += utostr(flag);
5250 ByrefType += ", __Block_byref_id_object_dispose_";
5251 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005252 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005253 ByrefType += "};\n";
Fariborz Jahanian822ac872011-03-31 22:49:32 +00005254 unsigned nameSize = Name.size();
5255 // for block or function pointer declaration. Name is aleady
5256 // part of the declaration.
5257 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5258 nameSize = 1;
5259 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005260 }
5261 else {
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005262 SourceLocation startLoc;
5263 Expr *E = ND->getInit();
5264 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5265 startLoc = ECE->getLParenLoc();
5266 else
5267 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00005268 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005269 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005270 ByrefType += " " + Name;
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005271 ByrefType += " = {(void*)";
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005272 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005273 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005274 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005275 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005276 ByrefType += "sizeof(";
5277 RewriteByRefString(ByrefType, Name, ND);
5278 ByrefType += "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005279 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005280 ByrefType += "__Block_byref_id_object_copy_";
5281 ByrefType += utostr(flag);
5282 ByrefType += ", __Block_byref_id_object_dispose_";
5283 ByrefType += utostr(flag);
5284 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005285 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00005286 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroffc5143c52009-12-23 17:24:33 +00005287
5288 // Complete the newly synthesized compound expression by inserting a right
5289 // curly brace before the end of the declaration.
5290 // FIXME: This approach avoids rewriting the initializer expression. It
5291 // also assumes there is only one declarator. For example, the following
5292 // isn't currently supported by this routine (in general):
5293 //
5294 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
5295 //
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00005296 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5297 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroffc5143c52009-12-23 17:24:33 +00005298 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
5299 SourceLocation semiLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00005300 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroffc5143c52009-12-23 17:24:33 +00005301
Benjamin Kramerd999b372010-02-14 14:14:16 +00005302 InsertText(semiLoc, "}");
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005303 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00005304 return;
5305}
5306
Mike Stump1eb44332009-09-09 15:08:12 +00005307void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00005308 // Add initializers for any closure decl refs.
5309 GetBlockDeclRefExprs(Exp->getBody());
5310 if (BlockDeclRefs.size()) {
5311 // Unique all "by copy" declarations.
5312 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005313 if (!BlockDeclRefs[i]->isByRef()) {
5314 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5315 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5316 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5317 }
5318 }
Steve Naroff54055232008-10-27 17:20:55 +00005319 // Unique all "by ref" declarations.
5320 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5321 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005322 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5323 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5324 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5325 }
Steve Naroff54055232008-10-27 17:20:55 +00005326 }
5327 // Find any imported blocks...they will need special attention.
5328 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00005329 if (BlockDeclRefs[i]->isByRef() ||
5330 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian5b011b02010-02-26 21:46:27 +00005331 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff54055232008-10-27 17:20:55 +00005332 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff54055232008-10-27 17:20:55 +00005333 }
5334}
5335
Chris Lattner5f9e2722011-07-23 10:55:15 +00005336FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(StringRef name) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005337 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00005338 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005339 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5340 SourceLocation(), ID, FType, 0, SC_Extern,
John McCalld931b082010-08-26 03:08:43 +00005341 SC_None, false, false);
Steve Narofffa15fd92008-10-28 20:29:00 +00005342}
5343
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005344Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005345 const SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahanian05318d82011-02-16 22:37:10 +00005346 const BlockDecl *block = Exp->getBlockDecl();
Steve Narofffa15fd92008-10-28 20:29:00 +00005347 Blocks.push_back(Exp);
5348
5349 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005350
5351 // Add inner imported variables now used in current block.
5352 int countOfInnerDecls = 0;
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005353 if (!InnerBlockDeclRefs.empty()) {
5354 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5355 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
5356 ValueDecl *VD = Exp->getDecl();
5357 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005358 // We need to save the copied-in variables in nested
5359 // blocks because it is needed at the end for some of the API generations.
5360 // See SynthesizeBlockLiterals routine.
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005361 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5362 BlockDeclRefs.push_back(Exp);
5363 BlockByCopyDeclsPtrSet.insert(VD);
5364 BlockByCopyDecls.push_back(VD);
5365 }
5366 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
5367 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5368 BlockDeclRefs.push_back(Exp);
5369 BlockByRefDeclsPtrSet.insert(VD);
5370 BlockByRefDecls.push_back(VD);
5371 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005372 }
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005373 // Find any imported blocks...they will need special attention.
5374 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5375 if (InnerBlockDeclRefs[i]->isByRef() ||
5376 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5377 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5378 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005379 }
5380 InnerDeclRefsCount.push_back(countOfInnerDecls);
5381
Steve Narofffa15fd92008-10-28 20:29:00 +00005382 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00005383
Steve Narofffa15fd92008-10-28 20:29:00 +00005384 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00005385 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00005386 else if (CurMethodDef)
5387 BuildUniqueMethodName(FuncName, CurMethodDef);
5388 else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005389 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00005390
Steve Narofffa15fd92008-10-28 20:29:00 +00005391 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00005392
Steve Narofffa15fd92008-10-28 20:29:00 +00005393 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
5394 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00005395
Steve Narofffa15fd92008-10-28 20:29:00 +00005396 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian1f906222010-05-25 15:56:08 +00005397 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5398 QualType FType = Context->getPointerType(BFT);
Steve Narofffa15fd92008-10-28 20:29:00 +00005399
5400 FunctionDecl *FD;
5401 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00005402
Steve Narofffa15fd92008-10-28 20:29:00 +00005403 // Simulate a contructor call...
Daniel Dunbar4087f272010-08-17 22:39:59 +00005404 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf89e55a2010-11-18 06:31:45 +00005405 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, VK_RValue,
5406 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00005407
Chris Lattner5f9e2722011-07-23 10:55:15 +00005408 SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00005409
Steve Narofffdc03722008-10-29 21:23:59 +00005410 // Initialize the block function.
Daniel Dunbar4087f272010-08-17 22:39:59 +00005411 FD = SynthBlockInitFunctionDecl(Func);
John McCallf89e55a2010-11-18 06:31:45 +00005412 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
Ted Kremenek8189cde2009-02-07 01:47:29 +00005413 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005414 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00005415 CK_BitCast, Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00005416 InitExprs.push_back(castExpr);
5417
Steve Naroff01aec112009-12-06 21:14:13 +00005418 // Initialize the block descriptor.
5419 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00005420
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005421 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5422 SourceLocation(), SourceLocation(),
5423 &Context->Idents.get(DescData.c_str()),
5424 Context->VoidPtrTy, 0,
5425 SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00005426 UnaryOperator *DescRefExpr =
5427 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD,
5428 Context->VoidPtrTy,
5429 VK_LValue,
5430 SourceLocation()),
5431 UO_AddrOf,
5432 Context->getPointerType(Context->VoidPtrTy),
5433 VK_RValue, OK_Ordinary,
5434 SourceLocation());
Steve Naroff01aec112009-12-06 21:14:13 +00005435 InitExprs.push_back(DescRefExpr);
5436
Steve Narofffa15fd92008-10-28 20:29:00 +00005437 // Add initializers for any closure decl refs.
5438 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00005439 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00005440 // Output all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00005441 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005442 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005443 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00005444 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar4087f272010-08-17 22:39:59 +00005445 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005446 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5447 SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00005448 if (HasLocalVariableExternalStorage(*I)) {
5449 QualType QT = (*I)->getType();
5450 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00005451 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5452 OK_Ordinary, SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00005453 }
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005454 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00005455 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005456 Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5457 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005458 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00005459 CK_BitCast, Arg);
Steve Narofffa15fd92008-10-28 20:29:00 +00005460 } else {
Daniel Dunbar4087f272010-08-17 22:39:59 +00005461 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005462 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5463 SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005464 if (HasLocalVariableExternalStorage(*I)) {
5465 QualType QT = (*I)->getType();
5466 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00005467 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5468 OK_Ordinary, SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005469 }
5470
Steve Narofffa15fd92008-10-28 20:29:00 +00005471 }
Mike Stump1eb44332009-09-09 15:08:12 +00005472 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005473 }
5474 // Output all "by ref" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00005475 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005476 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005477 ValueDecl *ND = (*I);
5478 std::string Name(ND->getNameAsString());
5479 std::string RecName;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00005480 RewriteByRefString(RecName, Name, ND, true);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005481 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5482 + sizeof("struct"));
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005483 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00005484 SourceLocation(), SourceLocation(),
5485 II);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005486 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5487 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5488
Daniel Dunbar4087f272010-08-17 22:39:59 +00005489 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005490 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5491 SourceLocation());
Fariborz Jahanian05318d82011-02-16 22:37:10 +00005492 bool isNestedCapturedVar = false;
5493 if (block)
5494 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5495 ce = block->capture_end(); ci != ce; ++ci) {
5496 const VarDecl *variable = ci->getVariable();
5497 if (variable == ND && ci->isNested()) {
5498 assert (ci->isByRef() &&
5499 "SynthBlockInitExpr - captured block variable is not byref");
5500 isNestedCapturedVar = true;
5501 break;
5502 }
5503 }
5504 // captured nested byref variable has its address passed. Do not take
5505 // its address again.
5506 if (!isNestedCapturedVar)
5507 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
John McCallf89e55a2010-11-18 06:31:45 +00005508 Context->getPointerType(Exp->getType()),
5509 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00005510 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00005511 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005512 }
5513 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00005514 if (ImportedBlockDecls.size()) {
5515 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5516 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00005517 unsigned IntSize =
5518 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005519 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5520 Context->IntTy, SourceLocation());
Fariborz Jahanianff127882009-12-23 21:52:32 +00005521 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00005522 }
Ted Kremenek668bf912009-02-09 20:51:47 +00005523 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00005524 FType, VK_LValue, SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00005525 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00005526 Context->getPointerType(NewRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00005527 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00005528 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00005529 NewRep);
Steve Narofffa15fd92008-10-28 20:29:00 +00005530 BlockDeclRefs.clear();
5531 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005532 BlockByRefDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005533 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005534 BlockByCopyDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005535 ImportedBlockDecls.clear();
5536 return NewRep;
5537}
5538
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00005539bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5540 if (const ObjCForCollectionStmt * CS =
5541 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5542 return CS->getElement() == DS;
5543 return false;
5544}
5545
Steve Narofffa15fd92008-10-28 20:29:00 +00005546//===----------------------------------------------------------------------===//
5547// Function Body / Expression rewriting
5548//===----------------------------------------------------------------------===//
5549
5550Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00005551 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005552 isa<DoStmt>(S) || isa<ForStmt>(S))
5553 Stmts.push_back(S);
5554 else if (isa<ObjCForCollectionStmt>(S)) {
5555 Stmts.push_back(S);
Chris Lattner4824fcd2010-01-09 21:45:57 +00005556 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00005557 }
Mike Stump1eb44332009-09-09 15:08:12 +00005558
John McCall4b9c2d22011-11-06 09:01:30 +00005559 // Pseudo-object operations and ivar references need special
5560 // treatment because we're going to recursively rewrite them.
5561 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5562 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5563 return RewritePropertyOrImplicitSetter(PseudoOp);
5564 } else {
5565 return RewritePropertyOrImplicitGetter(PseudoOp);
5566 }
5567 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5568 return RewriteObjCIvarRefExpr(IvarRefExpr);
5569 }
5570
Steve Narofffa15fd92008-10-28 20:29:00 +00005571 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005572
Steve Narofffa15fd92008-10-28 20:29:00 +00005573 // Perform a bottom up rewrite of all children.
John McCall7502c1d2011-02-13 04:07:26 +00005574 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Narofffa15fd92008-10-28 20:29:00 +00005575 if (*CI) {
John McCall4b9c2d22011-11-06 09:01:30 +00005576 Stmt *childStmt = (*CI);
5577 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005578 if (newStmt) {
John McCall4b9c2d22011-11-06 09:01:30 +00005579 *CI = newStmt;
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005580 }
Nick Lewycky7e749242010-10-31 21:07:24 +00005581 }
Mike Stump1eb44332009-09-09 15:08:12 +00005582
Steve Narofffa15fd92008-10-28 20:29:00 +00005583 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005584 SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005585 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5586 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005587 ImportedLocalExternalDecls.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005588 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005589 InnerBlockDeclRefs, InnerContexts);
Steve Narofffa15fd92008-10-28 20:29:00 +00005590 // Rewrite the block body in place.
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00005591 Stmt *SaveCurrentBody = CurrentBody;
5592 CurrentBody = BE->getBody();
5593 PropParentMap = 0;
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00005594 // block literal on rhs of a property-dot-sytax assignment
5595 // must be replaced by its synthesize ast so getRewrittenText
5596 // works as expected. In this case, what actually ends up on RHS
5597 // is the blockTranscribed which is the helper function for the
5598 // block literal; as in: self.c = ^() {[ace ARR];};
5599 bool saveDisableReplaceStmt = DisableReplaceStmt;
5600 DisableReplaceStmt = false;
Steve Narofffa15fd92008-10-28 20:29:00 +00005601 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00005602 DisableReplaceStmt = saveDisableReplaceStmt;
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00005603 CurrentBody = SaveCurrentBody;
5604 PropParentMap = 0;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005605 ImportedLocalExternalDecls.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005606 // Now we snarf the rewritten text and stash it away for later use.
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00005607 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005608 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00005609
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005610 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5611
Steve Narofffa15fd92008-10-28 20:29:00 +00005612 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005613 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00005614 return blockTranscribed;
5615 }
5616 // Handle specific things.
5617 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5618 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00005619
Steve Narofffa15fd92008-10-28 20:29:00 +00005620 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5621 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00005622
Steve Narofffa15fd92008-10-28 20:29:00 +00005623 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5624 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00005625
Steve Narofffa15fd92008-10-28 20:29:00 +00005626 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00005627#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00005628 // Before we rewrite it, put the original message expression in a comment.
5629 SourceLocation startLoc = MessExpr->getLocStart();
5630 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00005631
Steve Narofffa15fd92008-10-28 20:29:00 +00005632 const char *startBuf = SM->getCharacterData(startLoc);
5633 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00005634
Steve Narofffa15fd92008-10-28 20:29:00 +00005635 std::string messString;
5636 messString += "// ";
5637 messString.append(startBuf, endBuf-startBuf+1);
5638 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00005639
5640 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00005641 // InsertText(clang::SourceLocation, char const*, unsigned int).
5642 // InsertText(startLoc, messString.c_str(), messString.size());
5643 // Tried this, but it didn't work either...
5644 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00005645#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00005646 return RewriteMessageExpr(MessExpr);
5647 }
Mike Stump1eb44332009-09-09 15:08:12 +00005648
Steve Narofffa15fd92008-10-28 20:29:00 +00005649 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5650 return RewriteObjCTryStmt(StmtTry);
5651
5652 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5653 return RewriteObjCSynchronizedStmt(StmtTry);
5654
5655 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5656 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00005657
Steve Narofffa15fd92008-10-28 20:29:00 +00005658 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5659 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00005660
5661 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00005662 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00005663 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00005664 OrigStmtRange.getEnd());
5665 if (BreakStmt *StmtBreakStmt =
5666 dyn_cast<BreakStmt>(S))
5667 return RewriteBreakStmt(StmtBreakStmt);
5668 if (ContinueStmt *StmtContinueStmt =
5669 dyn_cast<ContinueStmt>(S))
5670 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00005671
5672 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00005673 // and cast exprs.
5674 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5675 // FIXME: What we're doing here is modifying the type-specifier that
5676 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00005677 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00005678 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5679 // the context of an ObjCForCollectionStmt. For example:
5680 // NSArray *someArray;
5681 // for (id <FooProtocol> index in someArray) ;
5682 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5683 // and it depends on the original text locations/positions.
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00005684 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
Steve Naroff3d7e7862009-12-05 15:55:59 +00005685 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00005686
Steve Narofffa15fd92008-10-28 20:29:00 +00005687 // Blocks rewrite rules.
5688 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5689 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00005690 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00005691 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005692 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005693 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00005694 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005695 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005696 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005697 if (VD->hasAttr<BlocksAttr>()) {
5698 static unsigned uniqueByrefDeclCount = 0;
5699 assert(!BlockByRefDeclNo.count(ND) &&
5700 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5701 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005702 RewriteByRefVar(VD);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005703 }
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005704 else
5705 RewriteTypeOfDecl(VD);
5706 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005707 }
Richard Smith162e1c12011-04-15 14:24:37 +00005708 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005709 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005710 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005711 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005712 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5713 }
5714 }
5715 }
Mike Stump1eb44332009-09-09 15:08:12 +00005716
Steve Narofffa15fd92008-10-28 20:29:00 +00005717 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5718 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00005719
5720 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005721 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5722 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00005723 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5724 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005725 && "Statement stack mismatch");
5726 Stmts.pop_back();
5727 }
5728 // Handle blocks rewriting.
5729 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5730 if (BDRE->isByRef())
Steve Naroff621edce2009-04-29 16:37:50 +00005731 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofffa15fd92008-10-28 20:29:00 +00005732 }
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005733 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5734 ValueDecl *VD = DRE->getDecl();
5735 if (VD->hasAttr<BlocksAttr>())
5736 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005737 if (HasLocalVariableExternalStorage(VD))
5738 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005739 }
5740
Steve Narofffa15fd92008-10-28 20:29:00 +00005741 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005742 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00005743 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005744 ReplaceStmt(S, BlockCall);
5745 return BlockCall;
5746 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005747 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00005748 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005749 RewriteCastExpr(CE);
5750 }
5751#if 0
5752 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redl906082e2010-07-20 04:20:21 +00005753 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5754 ICE->getSubExpr(),
5755 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00005756 // Get the new text.
5757 std::string SStr;
5758 llvm::raw_string_ostream Buf(SStr);
Eli Friedman3a9eb442009-05-30 05:19:26 +00005759 Replacement->printPretty(Buf, *Context);
Steve Narofffa15fd92008-10-28 20:29:00 +00005760 const std::string &Str = Buf.str();
5761
5762 printf("CAST = %s\n", &Str[0]);
5763 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5764 delete S;
5765 return Replacement;
5766 }
5767#endif
5768 // Return this stmt unmodified.
5769 return S;
5770}
5771
Steve Naroff3d7e7862009-12-05 15:55:59 +00005772void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5773 for (RecordDecl::field_iterator i = RD->field_begin(),
5774 e = RD->field_end(); i != e; ++i) {
5775 FieldDecl *FD = *i;
5776 if (isTopLevelBlockPointerType(FD->getType()))
5777 RewriteBlockPointerDecl(FD);
5778 if (FD->getType()->isObjCQualifiedIdType() ||
5779 FD->getType()->isObjCQualifiedInterfaceType())
5780 RewriteObjCQualifiedInterfaceTypes(FD);
5781 }
5782}
5783
Steve Narofffa15fd92008-10-28 20:29:00 +00005784/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5785/// main file of the input.
5786void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5787 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffcb735302008-12-17 00:20:22 +00005788 if (FD->isOverloadedOperator())
5789 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005790
Steve Narofffa15fd92008-10-28 20:29:00 +00005791 // Since function prototypes don't have ParmDecl's, we check the function
5792 // prototype. This enables us to rewrite function declarations and
5793 // definitions using the same code.
Douglas Gregor72564e72009-02-26 23:50:07 +00005794 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005795
Sebastian Redld3a413d2009-04-26 20:35:05 +00005796 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidis5f1bfc12010-07-07 11:31:34 +00005797 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005798 CurFunctionDef = FD;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005799 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroff8599e7a2008-12-08 16:43:47 +00005800 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005801 Body =
5802 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5803 FD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005804 CurrentBody = 0;
5805 if (PropParentMap) {
5806 delete PropParentMap;
5807 PropParentMap = 0;
5808 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005809 // This synthesizes and inserts the block "impl" struct, invoke function,
5810 // and any copy/dispose helper functions.
5811 InsertBlockLiteralsWithinFunction(FD);
5812 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005813 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00005814 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005815 return;
5816 }
5817 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005818 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005819 CurMethodDef = MD;
Steve Naroff8599e7a2008-12-08 16:43:47 +00005820 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005821 Body =
5822 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5823 MD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005824 CurrentBody = 0;
5825 if (PropParentMap) {
5826 delete PropParentMap;
5827 PropParentMap = 0;
5828 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005829 InsertBlockLiteralsWithinMethod(MD);
5830 CurMethodDef = 0;
5831 }
5832 }
5833 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5834 ClassImplementation.push_back(CI);
5835 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5836 CategoryImplementation.push_back(CI);
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00005837 else if (isa<ObjCClassDecl>(D))
David Blaikieb219cfc2011-09-23 05:06:16 +00005838 llvm_unreachable("RewriteObjC::HandleDeclInMainFile - ObjCClassDecl");
Steve Narofffa15fd92008-10-28 20:29:00 +00005839 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5840 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005841 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005842 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005843 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005844 CheckFunctionPointerDecl(VD->getType(), VD);
5845 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00005846 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005847 RewriteCastExpr(CE);
5848 }
5849 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00005850 } else if (VD->getType()->isRecordType()) {
5851 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
John McCall5e1cdac2011-10-07 06:10:15 +00005852 if (RD->isCompleteDefinition())
Steve Naroff3d7e7862009-12-05 15:55:59 +00005853 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005854 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005855 if (VD->getInit()) {
5856 GlobalVarDecl = VD;
Steve Naroff8599e7a2008-12-08 16:43:47 +00005857 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005858 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005859 CurrentBody = 0;
5860 if (PropParentMap) {
5861 delete PropParentMap;
5862 PropParentMap = 0;
5863 }
Mike Stump1eb44332009-09-09 15:08:12 +00005864 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00005865 VD->getName());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005866 GlobalVarDecl = 0;
5867
5868 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00005869 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005870 RewriteCastExpr(CE);
5871 }
5872 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005873 return;
5874 }
Richard Smith162e1c12011-04-15 14:24:37 +00005875 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005876 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005877 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005878 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005879 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5880 return;
5881 }
5882 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
John McCall5e1cdac2011-10-07 06:10:15 +00005883 if (RD->isCompleteDefinition())
Steve Naroff3d7e7862009-12-05 15:55:59 +00005884 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005885 return;
5886 }
5887 // Nothing yet.
5888}
5889
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00005890void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005891 if (Diags.hasErrorOccurred())
5892 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005893
Steve Narofffa15fd92008-10-28 20:29:00 +00005894 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00005895
Steve Naroff621edce2009-04-29 16:37:50 +00005896 // Here's a great place to add any extra declarations that may be needed.
5897 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00005898 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00005899 E = ProtocolExprDecls.end(); I != E; ++I)
5900 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5901
Benjamin Kramerd999b372010-02-14 14:14:16 +00005902 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff0aab7962008-11-14 14:10:01 +00005903 if (ClassImplementation.size() || CategoryImplementation.size())
5904 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00005905
Steve Narofffa15fd92008-10-28 20:29:00 +00005906 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5907 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00005908 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00005909 Rewrite.getRewriteBufferFor(MainFileID)) {
5910 //printf("Changed:\n");
5911 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5912 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +00005913 llvm::errs() << "No changes\n";
Steve Narofffa15fd92008-10-28 20:29:00 +00005914 }
Steve Narofface66252008-11-13 20:07:04 +00005915
Steve Naroff621edce2009-04-29 16:37:50 +00005916 if (ClassImplementation.size() || CategoryImplementation.size() ||
5917 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00005918 // Rewrite Objective-c meta data*
5919 std::string ResultStr;
Fariborz Jahanian58457172011-12-05 18:43:13 +00005920 RewriteMetaDataIntoBuffer(ResultStr);
Steve Naroff0aab7962008-11-14 14:10:01 +00005921 // Emit metadata.
5922 *OutFile << ResultStr;
5923 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005924 OutFile->flush();
5925}