blob: cd5963d9f4462c42378bb0c1329fdd961dc386d9 [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
Eli Friedman39d7c4d2009-05-18 22:50:54 +000014#include "clang/Frontend/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"
Chris Lattner77cd2a02007-10-11 00:43:27 +000029using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000030using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000031
Chris Lattner77cd2a02007-10-11 00:43:27 +000032namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000033 class RewriteObjC : public ASTConsumer {
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000034 enum {
35 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
36 block, ... */
37 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
38 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
39 __block variable */
40 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
41 helpers */
42 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
43 support routines */
44 BLOCK_BYREF_CURRENT_MAX = 256
45 };
46
47 enum {
48 BLOCK_NEEDS_FREE = (1 << 24),
49 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
50 BLOCK_HAS_CXX_OBJ = (1 << 26),
51 BLOCK_IS_GC = (1 << 27),
52 BLOCK_IS_GLOBAL = (1 << 28),
53 BLOCK_HAS_DESCRIPTOR = (1 << 29)
54 };
55
Chris Lattner2c64b7b2007-10-16 21:07:07 +000056 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000057 Diagnostic &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000058 const LangOptions &LangOpts;
Steve Narofff69cc5d2008-01-30 19:17:43 +000059 unsigned RewriteFailedDiag;
Steve Naroff8c565152008-12-05 17:03:39 +000060 unsigned TryFinallyContainsReturnDiag;
Mike Stump1eb44332009-09-09 15:08:12 +000061
Chris Lattner01c57482007-10-17 22:35:30 +000062 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000063 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000064 TranslationUnitDecl *TUDecl;
Chris Lattner2b2453a2009-01-17 06:22:33 +000065 FileID MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000066 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000067 SourceLocation LastIncLoc;
Mike Stump1eb44332009-09-09 15:08:12 +000068
Ted Kremeneka526c5c2008-01-07 19:49:32 +000069 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
70 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
71 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +000072 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000073 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
74 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000075 llvm::SmallVector<Stmt *, 32> Stmts;
76 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroff621edce2009-04-29 16:37:50 +000077 // Remember all the @protocol(<expr>) expressions.
78 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +000079
80 llvm::DenseSet<uint64_t> CopyDestroyCache;
81
Steve Naroffd82a9ab2008-03-15 00:55:56 +000082 unsigned NumObjCStringLiterals;
Mike Stump1eb44332009-09-09 15:08:12 +000083
Steve Naroffebf2b562007-10-23 23:50:29 +000084 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000085 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000086 FunctionDecl *MsgSendStretFunctionDecl;
87 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000088 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000089 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000090 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000091 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000092 FunctionDecl *CFStringFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000093 FunctionDecl *SuperContructorFunctionDecl;
Mike Stump1eb44332009-09-09 15:08:12 +000094
Steve Naroffbeaf2992007-11-03 11:27:19 +000095 // ObjC string constant support.
Steve Naroff248a7532008-04-15 22:42:06 +000096 VarDecl *ConstantStringClassReference;
Steve Naroffbeaf2992007-11-03 11:27:19 +000097 RecordDecl *NSStringRecord;
Mike Stump1eb44332009-09-09 15:08:12 +000098
Fariborz Jahanianb586cce2008-01-16 00:09:11 +000099 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000100 int BcLabelCount;
Mike Stump1eb44332009-09-09 15:08:12 +0000101
Steve Naroff874e2322007-11-15 10:28:18 +0000102 // Needed for super.
Steve Naroff54055232008-10-27 17:20:55 +0000103 ObjCMethodDecl *CurMethodDef;
Steve Naroff874e2322007-11-15 10:28:18 +0000104 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000105 RecordDecl *ConstantStringDecl;
Mike Stump1eb44332009-09-09 15:08:12 +0000106
Steve Naroff621edce2009-04-29 16:37:50 +0000107 TypeDecl *ProtocolTypeDecl;
108 QualType getProtocolType();
Mike Stump1eb44332009-09-09 15:08:12 +0000109
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000110 // Needed for header files being rewritten
111 bool IsHeader;
Mike Stump1eb44332009-09-09 15:08:12 +0000112
Steve Naroffa7b402d2008-03-28 22:26:09 +0000113 std::string InFileName;
Eli Friedman66d6f042009-05-18 22:20:00 +0000114 llvm::raw_ostream* OutFile;
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000115
116 bool SilenceRewriteMacroWarning;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000117 bool objc_impl_method;
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000118
Steve Naroffba92b2e2008-03-27 22:29:16 +0000119 std::string Preamble;
Steve Naroff54055232008-10-27 17:20:55 +0000120
121 // Block expressions.
122 llvm::SmallVector<BlockExpr *, 32> Blocks;
123 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
124 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
Mike Stump1eb44332009-09-09 15:08:12 +0000125
Steve Naroff54055232008-10-27 17:20:55 +0000126 // Block related declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +0000127 llvm::SmallVector<ValueDecl *, 8> BlockByCopyDecls;
128 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
129 llvm::SmallVector<ValueDecl *, 8> BlockByRefDecls;
130 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000131 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff54055232008-10-27 17:20:55 +0000132 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
133
134 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
135
Steve Naroffc77a6362008-12-04 16:24:46 +0000136 // This maps a property to it's assignment statement.
137 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
Steve Naroff8599e7a2008-12-08 16:43:47 +0000138 // This maps a property to it's synthesied message expression.
139 // This allows us to rewrite chained getters (e.g. o.a.b.c).
140 llvm::DenseMap<ObjCPropertyRefExpr *, Stmt *> PropGetters;
Mike Stump1eb44332009-09-09 15:08:12 +0000141
Steve Naroff4c3580e2008-12-04 23:50:32 +0000142 // This maps an original source AST to it's rewritten form. This allows
143 // us to avoid rewriting the same node twice (which is very uncommon).
144 // This is needed to support some of the exotic property rewriting.
145 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Naroff15f081d2008-12-03 00:56:33 +0000146
Steve Naroff54055232008-10-27 17:20:55 +0000147 FunctionDecl *CurFunctionDef;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000148 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000149 VarDecl *GlobalVarDecl;
Mike Stump1eb44332009-09-09 15:08:12 +0000150
Steve Naroffb619d952008-12-09 12:56:34 +0000151 bool DisableReplaceStmt;
Mike Stump1eb44332009-09-09 15:08:12 +0000152
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000153 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000154 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000155 virtual void Initialize(ASTContext &context);
156
Chris Lattnerf04da132007-10-24 17:06:59 +0000157 // Top Level Driver code.
Chris Lattner682bf922009-03-29 16:50:03 +0000158 virtual void HandleTopLevelDecl(DeclGroupRef D) {
159 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
160 HandleTopLevelSingleDecl(*I);
161 }
162 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000163 void HandleDeclInMainFile(Decl *D);
Eli Friedman66d6f042009-05-18 22:20:00 +0000164 RewriteObjC(std::string inFile, llvm::raw_ostream *OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000165 Diagnostic &D, const LangOptions &LOpts,
166 bool silenceMacroWarn);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000167
168 ~RewriteObjC() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000169
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000170 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump1eb44332009-09-09 15:08:12 +0000171
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000172 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000173 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump1eb44332009-09-09 15:08:12 +0000174
Steve Naroff4c3580e2008-12-04 23:50:32 +0000175 if (ReplacingStmt)
176 return; // We can't rewrite the same node twice.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000177
Steve Naroffb619d952008-12-09 12:56:34 +0000178 if (DisableReplaceStmt)
179 return; // Used when rewriting the assignment of a property setter.
180
Steve Naroff4c3580e2008-12-04 23:50:32 +0000181 // If replacement succeeded or warning disabled return with no warning.
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000182 if (!Rewrite.ReplaceStmt(Old, New)) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000183 ReplacedNodes[Old] = New;
184 return;
185 }
186 if (SilenceRewriteMacroWarning)
187 return;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000188 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
189 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000190 }
Steve Naroffb619d952008-12-09 12:56:34 +0000191
192 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
193 // Measaure the old text.
194 int Size = Rewrite.getRangeSize(SrcRange);
195 if (Size == -1) {
196 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
197 << Old->getSourceRange();
198 return;
199 }
200 // Get the new text.
201 std::string SStr;
202 llvm::raw_string_ostream S(SStr);
Chris Lattnere4f21422009-06-30 01:26:17 +0000203 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroffb619d952008-12-09 12:56:34 +0000204 const std::string &Str = S.str();
205
206 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000207 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroffb619d952008-12-09 12:56:34 +0000208 ReplacedNodes[Old] = New;
209 return;
210 }
211 if (SilenceRewriteMacroWarning)
212 return;
213 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
214 << Old->getSourceRange();
215 }
216
Benjamin Kramerd999b372010-02-14 14:14:16 +0000217 void InsertText(SourceLocation Loc, llvm::StringRef Str,
Steve Naroffba92b2e2008-03-27 22:29:16 +0000218 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000219 // If insertion succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000220 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000221 SilenceRewriteMacroWarning)
222 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000223
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000224 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
225 }
Mike Stump1eb44332009-09-09 15:08:12 +0000226
Chris Lattneraadaf782008-01-31 19:51:04 +0000227 void RemoveText(SourceLocation Loc, unsigned StrLen) {
228 // If removal succeeded or warning disabled return with no warning.
229 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
230 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000231
Chris Lattneraadaf782008-01-31 19:51:04 +0000232 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
233 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000234
Chris Lattneraadaf782008-01-31 19:51:04 +0000235 void ReplaceText(SourceLocation Start, unsigned OrigLength,
Benjamin Kramerd999b372010-02-14 14:14:16 +0000236 llvm::StringRef Str) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000237 // If removal succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000238 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
Chris Lattneraadaf782008-01-31 19:51:04 +0000239 SilenceRewriteMacroWarning)
240 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000241
Chris Lattneraadaf782008-01-31 19:51:04 +0000242 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
243 }
Mike Stump1eb44332009-09-09 15:08:12 +0000244
Chris Lattnerf04da132007-10-24 17:06:59 +0000245 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000246 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000247 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000248 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000249 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffa0876e82008-12-02 17:36:43 +0000250 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
251 ObjCImplementationDecl *IMD,
252 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000253 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000254 void RewriteImplementationDecl(Decl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000255 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000256 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
257 ValueDecl *VD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000258 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
259 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
260 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
261 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000262 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff09b266e2007-10-30 23:14:51 +0000263 void RewriteFunctionDecl(FunctionDecl *FD);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000264 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000265 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +0000266 void RewriteTypeOfDecl(VarDecl *VD);
Steve Naroff4f95b752008-07-29 18:15:38 +0000267 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000268 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000269 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000270 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000271 QualType getConstantStringStructType();
Steve Naroffbaf58c32008-05-31 14:15:04 +0000272 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump1eb44332009-09-09 15:08:12 +0000273
Chris Lattnerf04da132007-10-24 17:06:59 +0000274 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000275 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroffc77a6362008-12-04 16:24:46 +0000276 void CollectPropertySetters(Stmt *S);
Mike Stump1eb44332009-09-09 15:08:12 +0000277
Steve Naroff8599e7a2008-12-08 16:43:47 +0000278 Stmt *CurrentBody;
279 ParentMap *PropParentMap; // created lazily.
Mike Stump1eb44332009-09-09 15:08:12 +0000280
Chris Lattnere64b7772007-10-24 16:57:36 +0000281 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +0000282 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart,
283 bool &replaced);
284 Stmt *RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced);
Steve Naroffc77a6362008-12-04 16:24:46 +0000285 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Mike Stump1eb44332009-09-09 15:08:12 +0000286 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroffb619d952008-12-09 12:56:34 +0000287 SourceRange SrcRange);
Steve Naroffb42f8412007-11-05 14:50:49 +0000288 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000289 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000290 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000291 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffb85e77a2009-12-05 21:43:12 +0000292 void WarnAboutReturnGotoStmts(Stmt *S);
293 void HasReturnStmts(Stmt *S, bool &hasReturns);
294 void RewriteTryReturnStmts(Stmt *S);
295 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000296 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000297 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000298 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
299 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
300 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000301 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
302 SourceLocation OrigEnd);
Mike Stump1eb44332009-09-09 15:08:12 +0000303 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +0000304 Expr **args, unsigned nargs,
305 SourceLocation StartLoc=SourceLocation(),
306 SourceLocation EndLoc=SourceLocation());
307 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
308 SourceLocation StartLoc=SourceLocation(),
309 SourceLocation EndLoc=SourceLocation());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000310 Stmt *RewriteBreakStmt(BreakStmt *S);
311 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000312 void SynthCountByEnumWithState(std::string &buf);
Mike Stump1eb44332009-09-09 15:08:12 +0000313
Steve Naroff09b266e2007-10-30 23:14:51 +0000314 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000315 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000316 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000317 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000318 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000319 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000320 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000321 void SynthSelGetUidFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000322 void SynthSuperContructorFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000323
Chris Lattnerf04da132007-10-24 17:06:59 +0000324 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000325 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000326 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000327
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000328 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000329 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000330
Douglas Gregor653f1b12009-04-23 01:02:12 +0000331 template<typename MethodIterator>
332 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
333 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000334 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000335 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000336 const char *ClassName,
337 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000338
Steve Naroff621edce2009-04-29 16:37:50 +0000339 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
340 const char *prefix,
341 const char *ClassName,
342 std::string &Result);
343 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Mike Stump1eb44332009-09-09 15:08:12 +0000344 const char *prefix,
Steve Naroff621edce2009-04-29 16:37:50 +0000345 const char *ClassName,
346 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000347 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000348 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000349 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
350 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000351 std::string &Result);
Steve Narofface66252008-11-13 20:07:04 +0000352 void RewriteImplementations();
353 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000354
Steve Naroff54055232008-10-27 17:20:55 +0000355 // Block rewriting.
Mike Stump1eb44332009-09-09 15:08:12 +0000356 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff54055232008-10-27 17:20:55 +0000357 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump1eb44332009-09-09 15:08:12 +0000358
Steve Naroff54055232008-10-27 17:20:55 +0000359 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
360 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump1eb44332009-09-09 15:08:12 +0000361
362 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000363 void RewriteBlockCall(CallExpr *Exp);
364 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000365 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +0000366 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +0000367 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Steve Naroff54055232008-10-27 17:20:55 +0000368 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000369
370 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Steve Naroff54055232008-10-27 17:20:55 +0000371 const char *funcName, std::string Tag);
Mike Stump1eb44332009-09-09 15:08:12 +0000372 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Steve Naroff54055232008-10-27 17:20:55 +0000373 const char *funcName, std::string Tag);
Steve Naroff01aec112009-12-06 21:14:13 +0000374 std::string SynthesizeBlockImpl(BlockExpr *CE,
375 std::string Tag, std::string Desc);
376 std::string SynthesizeBlockDescriptor(std::string DescTag,
377 std::string ImplTag,
378 int i, const char *funcName,
379 unsigned hasCopy);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +0000380 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff54055232008-10-27 17:20:55 +0000381 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000382 const char *FunName);
Steve Naroff3d7e7862009-12-05 15:55:59 +0000383 void RewriteRecordBody(RecordDecl *RD);
Mike Stump1eb44332009-09-09 15:08:12 +0000384
Steve Naroff54055232008-10-27 17:20:55 +0000385 void CollectBlockDeclRefInfo(BlockExpr *Exp);
386 void GetBlockCallExprs(Stmt *S);
387 void GetBlockDeclRefExprs(Stmt *S);
Mike Stump1eb44332009-09-09 15:08:12 +0000388
Steve Naroff54055232008-10-27 17:20:55 +0000389 // We avoid calling Type::isBlockPointerType(), since it operates on the
390 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000391 bool isTopLevelBlockPointerType(QualType T) {
392 return isa<BlockPointerType>(T);
393 }
Mike Stump1eb44332009-09-09 15:08:12 +0000394
Steve Naroff54055232008-10-27 17:20:55 +0000395 // FIXME: This predicate seems like it would be useful to add to ASTContext.
396 bool isObjCType(QualType T) {
397 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
398 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000399
Steve Naroff54055232008-10-27 17:20:55 +0000400 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000401
Steve Naroff54055232008-10-27 17:20:55 +0000402 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
403 OCT == Context->getCanonicalType(Context->getObjCClassType()))
404 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000405
Ted Kremenek6217b802009-07-29 21:53:49 +0000406 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000407 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000408 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff54055232008-10-27 17:20:55 +0000409 return true;
410 }
411 return false;
412 }
413 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000414 void GetExtentOfArgList(const char *Name, const char *&LParen,
415 const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000416 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump1eb44332009-09-09 15:08:12 +0000417
Steve Narofffa15fd92008-10-28 20:29:00 +0000418 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000419 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Mike Stump1eb44332009-09-09 15:08:12 +0000420
Steve Naroff621edce2009-04-29 16:37:50 +0000421 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump1eb44332009-09-09 15:08:12 +0000422 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroff621edce2009-04-29 16:37:50 +0000423 if (From[i] == '"')
424 To += "\\\"";
425 else
426 To += From[i];
427 }
428 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000429 };
John McCall9d125032010-01-15 18:39:57 +0000430
431 // Helper function: create a CStyleCastExpr with trivial type source info.
432 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
433 CastExpr::CastKind Kind, Expr *E) {
434 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
435 return new (Ctx) CStyleCastExpr(Ty, Kind, E, TInfo,
436 SourceLocation(), SourceLocation());
437 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000438}
439
Mike Stump1eb44332009-09-09 15:08:12 +0000440void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
441 NamedDecl *D) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000442 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000443 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000444 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000445 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000446 // All the args are checked/rewritten. Don't call twice!
447 RewriteBlockPointerDecl(D);
448 break;
449 }
450 }
451}
452
453void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000454 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +0000455 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000456 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000457}
458
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000459static bool IsHeaderFile(const std::string &Filename) {
460 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump1eb44332009-09-09 15:08:12 +0000461
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000462 if (DotPos == std::string::npos) {
463 // no file extension
Mike Stump1eb44332009-09-09 15:08:12 +0000464 return false;
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000465 }
Mike Stump1eb44332009-09-09 15:08:12 +0000466
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000467 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
468 // C header: .h
469 // C++ header: .hh or .H;
470 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump1eb44332009-09-09 15:08:12 +0000471}
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000472
Eli Friedman66d6f042009-05-18 22:20:00 +0000473RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000474 Diagnostic &D, const LangOptions &LOpts,
475 bool silenceMacroWarn)
476 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
477 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000478 IsHeader = IsHeaderFile(inFile);
Mike Stump1eb44332009-09-09 15:08:12 +0000479 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000480 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump1eb44332009-09-09 15:08:12 +0000481 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000482 "rewriter doesn't support user-specified control flow semantics "
483 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000484}
485
Eli Friedmanbce831b2009-05-18 22:29:17 +0000486ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
487 llvm::raw_ostream* OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000488 Diagnostic &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000489 const LangOptions &LOpts,
490 bool SilenceRewriteMacroWarning) {
491 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere365c502007-11-30 22:25:36 +0000492}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000493
Steve Naroffb29b4272008-04-14 22:03:09 +0000494void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000495 Context = &context;
496 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000497 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000498 MsgSendFunctionDecl = 0;
499 MsgSendSuperFunctionDecl = 0;
500 MsgSendStretFunctionDecl = 0;
501 MsgSendSuperStretFunctionDecl = 0;
502 MsgSendFpretFunctionDecl = 0;
503 GetClassFunctionDecl = 0;
504 GetMetaClassFunctionDecl = 0;
505 SelGetUidFunctionDecl = 0;
506 CFStringFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000507 ConstantStringClassReference = 0;
508 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000509 CurMethodDef = 0;
510 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000511 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000512 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000513 SuperStructDecl = 0;
Steve Naroff621edce2009-04-29 16:37:50 +0000514 ProtocolTypeDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000515 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000516 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000517 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000518 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000519 PropParentMap = 0;
520 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000521 DisableReplaceStmt = false;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000522 objc_impl_method = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000523
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000524 // Get the ID and start/end of the main file.
525 MainFileID = SM->getMainFileID();
526 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
527 MainFileStart = MainBuf->getBufferStart();
528 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000529
Chris Lattner2c78b872009-04-14 23:22:57 +0000530 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump1eb44332009-09-09 15:08:12 +0000531
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000532 // declaring objc_selector outside the parameter list removes a silly
533 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000534 if (IsHeader)
Steve Naroff62c26322009-02-03 20:39:18 +0000535 Preamble = "#pragma once\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000536 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff46a98a72008-12-23 20:11:22 +0000537 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000538 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000539 if (LangOpts.Microsoft) {
540 // Add a constructor for creating temporary objects.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000541 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
542 ": ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000543 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000544 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000545 Preamble += "};\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000546 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
547 Preamble += "typedef struct objc_object Protocol;\n";
548 Preamble += "#define _REWRITER_typedef_Protocol\n";
549 Preamble += "#endif\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000550 if (LangOpts.Microsoft) {
551 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
552 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
553 } else
554 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
555 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000556 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000557 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000558 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000559 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000560 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000561 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000562 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000563 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000564 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000565 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000566 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000567 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000568 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000569 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
570 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
571 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
572 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
573 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000574 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000575 // @synchronized hooks.
Steve Naroff4ebd7162008-12-08 17:30:33 +0000576 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
577 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
578 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000579 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
580 Preamble += "struct __objcFastEnumerationState {\n\t";
581 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000582 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000583 Preamble += "unsigned long *mutationsPtr;\n\t";
584 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000585 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000586 Preamble += "#define __FASTENUMERATIONSTATE\n";
587 Preamble += "#endif\n";
588 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
589 Preamble += "struct __NSConstantStringImpl {\n";
590 Preamble += " int *isa;\n";
591 Preamble += " int flags;\n";
592 Preamble += " char *str;\n";
593 Preamble += " long length;\n";
594 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000595 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
596 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
597 Preamble += "#else\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000598 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000599 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000600 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
601 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000602 // Blocks preamble.
603 Preamble += "#ifndef BLOCK_IMPL\n";
604 Preamble += "#define BLOCK_IMPL\n";
605 Preamble += "struct __block_impl {\n";
606 Preamble += " void *isa;\n";
607 Preamble += " int Flags;\n";
Steve Naroff01aec112009-12-06 21:14:13 +0000608 Preamble += " int Reserved;\n";
Steve Naroff54055232008-10-27 17:20:55 +0000609 Preamble += " void *FuncPtr;\n";
610 Preamble += "};\n";
Steve Naroff5bc60d02008-12-16 15:50:30 +0000611 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroffc9c1e9c2009-12-06 01:52:22 +0000612 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000613 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_assign(void *, const void *, const int);\n";
614 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
615 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
616 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
617 Preamble += "#else\n";
Steve Naroffcd826372010-01-05 18:09:31 +0000618 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
619 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000620 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
621 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
622 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000623 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000624 if (LangOpts.Microsoft) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000625 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
626 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000627 Preamble += "#define __attribute__(X)\n";
Fariborz Jahanian34204192010-01-15 22:29:39 +0000628 Preamble += "#define __weak\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000629 }
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000630 else {
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000631 Preamble += "#define __block\n";
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000632 Preamble += "#define __weak\n";
633 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000634}
635
636
Chris Lattnerf04da132007-10-24 17:06:59 +0000637//===----------------------------------------------------------------------===//
638// Top Level Driver Code
639//===----------------------------------------------------------------------===//
640
Chris Lattner682bf922009-03-29 16:50:03 +0000641void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremeneke50187a2010-02-05 21:28:51 +0000642 if (Diags.hasErrorOccurred())
643 return;
644
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000645 // Two cases: either the decl could be in the main file, or it could be in a
646 // #included file. If the former, rewrite it now. If the later, check to see
647 // if we rewrote the #include/#import.
648 SourceLocation Loc = D->getLocation();
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000649 Loc = SM->getInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000650
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000651 // If this is for a builtin, ignore it.
652 if (Loc.isInvalid()) return;
653
Steve Naroffebf2b562007-10-23 23:50:29 +0000654 // Look for built-in declarations that we need to refer during the rewrite.
655 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000656 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000657 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000658 // declared in <Foundation/NSString.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +0000659 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000660 ConstantStringClassReference = FVD;
661 return;
662 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000663 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000664 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000665 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000666 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000667 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000668 RewriteProtocolDecl(PD);
Mike Stump1eb44332009-09-09 15:08:12 +0000669 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000670 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000671 RewriteForwardProtocolDecl(FP);
Douglas Gregord0434102009-01-09 00:49:46 +0000672 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
673 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000674 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
675 DIEnd = LSD->decls_end();
Douglas Gregord0434102009-01-09 00:49:46 +0000676 DI != DIEnd; ++DI)
Chris Lattner682bf922009-03-29 16:50:03 +0000677 HandleTopLevelSingleDecl(*DI);
Steve Naroffebf2b562007-10-23 23:50:29 +0000678 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000679 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000680 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000681 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000682}
683
Chris Lattnerf04da132007-10-24 17:06:59 +0000684//===----------------------------------------------------------------------===//
685// Syntactic (non-AST) Rewriting Code
686//===----------------------------------------------------------------------===//
687
Steve Naroffb29b4272008-04-14 22:03:09 +0000688void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000689 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000690 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
691 const char *MainBufStart = MainBuf.first;
692 const char *MainBufEnd = MainBuf.second;
693 size_t ImportLen = strlen("import");
Mike Stump1eb44332009-09-09 15:08:12 +0000694
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000695 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000696 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
697 if (*BufPtr == '#') {
698 if (++BufPtr == MainBufEnd)
699 return;
700 while (*BufPtr == ' ' || *BufPtr == '\t')
701 if (++BufPtr == MainBufEnd)
702 return;
703 if (!strncmp(BufPtr, "import", ImportLen)) {
704 // replace import with include
Mike Stump1eb44332009-09-09 15:08:12 +0000705 SourceLocation ImportLoc =
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000706 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000707 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000708 BufPtr += ImportLen;
709 }
710 }
711 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000712}
713
Steve Naroffb29b4272008-04-14 22:03:09 +0000714void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000715 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
716 const char *MainBufStart = MainBuf.first;
717 const char *MainBufEnd = MainBuf.second;
Mike Stump1eb44332009-09-09 15:08:12 +0000718
Chris Lattnerf04da132007-10-24 17:06:59 +0000719 // Loop over the whole file, looking for tabs.
720 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
721 if (*BufPtr != '\t')
722 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000723
Chris Lattnerf04da132007-10-24 17:06:59 +0000724 // Okay, we found a tab. This tab will turn into at least one character,
725 // but it depends on which 'virtual column' it is in. Compute that now.
726 unsigned VCol = 0;
727 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
728 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
729 ++VCol;
Mike Stump1eb44332009-09-09 15:08:12 +0000730
Chris Lattnerf04da132007-10-24 17:06:59 +0000731 // Okay, now that we know the virtual column, we know how many spaces to
732 // insert. We assume 8-character tab-stops.
733 unsigned Spaces = 8-(VCol & 7);
Mike Stump1eb44332009-09-09 15:08:12 +0000734
Chris Lattnerf04da132007-10-24 17:06:59 +0000735 // Get the location of the tab.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000736 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
737 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Mike Stump1eb44332009-09-09 15:08:12 +0000738
Chris Lattnerf04da132007-10-24 17:06:59 +0000739 // Rewrite the single tab character into a sequence of spaces.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000740 ReplaceText(TabLoc, 1, llvm::StringRef(" ", Spaces));
Chris Lattnerf04da132007-10-24 17:06:59 +0000741 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000742}
743
Steve Naroffeb0646c2008-12-02 15:48:25 +0000744static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
745 ObjCIvarDecl *OID) {
746 std::string S;
747 S = "((struct ";
748 S += ClassDecl->getIdentifier()->getName();
749 S += "_IMPL *)self)->";
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +0000750 S += OID->getName();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000751 return S;
752}
753
Steve Naroffa0876e82008-12-02 17:36:43 +0000754void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
755 ObjCImplementationDecl *IMD,
756 ObjCCategoryImplDecl *CID) {
Steve Naroffd40910b2008-12-01 20:33:01 +0000757 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramerd999b372010-02-14 14:14:16 +0000758 InsertText(startLoc, "// ");
Steve Naroffeb0646c2008-12-02 15:48:25 +0000759 const char *startBuf = SM->getCharacterData(startLoc);
760 assert((*startBuf == '@') && "bogus @synthesize location");
761 const char *semiBuf = strchr(startBuf, ';');
762 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000763 SourceLocation onePastSemiLoc =
764 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000765
766 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
767 return; // FIXME: is this correct?
Mike Stump1eb44332009-09-09 15:08:12 +0000768
Steve Naroffeb0646c2008-12-02 15:48:25 +0000769 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000770 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000771 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000772 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000773
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000774 if (!OID)
775 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000776
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000777 std::string Getr;
778 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
779 Getr += "{ ";
780 // Synthesize an explicit cast to gain access to the ivar.
Mike Stump1eb44332009-09-09 15:08:12 +0000781 // FIXME: deal with code generation implications for various property
782 // attributes (copy, retain, nonatomic).
Steve Naroff3539cdb2008-12-02 17:54:50 +0000783 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000784 Getr += "return " + getIvarAccessString(ClassDecl, OID);
785 Getr += "; }";
Benjamin Kramerd999b372010-02-14 14:14:16 +0000786 InsertText(onePastSemiLoc, Getr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000787 if (PD->isReadOnly())
788 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000789
Steve Naroffeb0646c2008-12-02 15:48:25 +0000790 // Generate the 'setter' function.
791 std::string Setr;
792 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000793 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000794 // Synthesize an explicit cast to initialize the ivar.
Mike Stump1eb44332009-09-09 15:08:12 +0000795 // FIXME: deal with code generation implications for various property
796 // attributes (copy, retain, nonatomic).
Steve Naroff15f081d2008-12-03 00:56:33 +0000797 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000798 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
Steve Narofff4312dc2008-12-11 19:29:16 +0000799 Setr += PD->getNameAsCString();
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000800 Setr += "; }";
Benjamin Kramerd999b372010-02-14 14:14:16 +0000801 InsertText(onePastSemiLoc, Setr);
Steve Naroffd40910b2008-12-01 20:33:01 +0000802}
Chris Lattner8a12c272007-10-11 18:38:32 +0000803
Steve Naroffb29b4272008-04-14 22:03:09 +0000804void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000805 // Get the start location and compute the semi location.
806 SourceLocation startLoc = ClassDecl->getLocation();
807 const char *startBuf = SM->getCharacterData(startLoc);
808 const char *semiPtr = strchr(startBuf, ';');
Mike Stump1eb44332009-09-09 15:08:12 +0000809
Chris Lattnerf04da132007-10-24 17:06:59 +0000810 // Translate to typedef's that forward reference structs with the same name
811 // as the class. As a convenience, we include the original declaration
812 // as a comment.
813 std::string typedefString;
Fariborz Jahanian91fbd122010-01-11 22:48:40 +0000814 typedefString += "// @class ";
815 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
816 I != E; ++I) {
817 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
818 typedefString += ForwardDecl->getNameAsString();
819 if (I+1 != E)
820 typedefString += ", ";
821 else
822 typedefString += ";\n";
823 }
824
Chris Lattner67956052009-02-20 18:04:31 +0000825 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
826 I != E; ++I) {
Ted Kremenek321c22f2009-11-18 00:28:11 +0000827 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff32174822007-11-09 12:50:28 +0000828 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000829 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000830 typedefString += "\n";
831 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000832 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000833 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000834 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000835 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000836 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000837 }
Mike Stump1eb44332009-09-09 15:08:12 +0000838
Steve Naroff934f2762007-10-24 22:48:43 +0000839 // Replace the @class with typedefs corresponding to the classes.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000840 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
Chris Lattnerf04da132007-10-24 17:06:59 +0000841}
842
Steve Naroffb29b4272008-04-14 22:03:09 +0000843void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000844 // When method is a synthesized one, such as a getter/setter there is
845 // nothing to rewrite.
846 if (Method->isSynthesized())
847 return;
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000848 SourceLocation LocStart = Method->getLocStart();
849 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000850
Chris Lattner30fc9332009-02-04 01:06:56 +0000851 if (SM->getInstantiationLineNumber(LocEnd) >
852 SM->getInstantiationLineNumber(LocStart)) {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000853 InsertText(LocStart, "#if 0\n");
854 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000855 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000856 InsertText(LocStart, "// ");
Steve Naroff423cb562007-10-30 13:30:57 +0000857 }
858}
859
Mike Stump1eb44332009-09-09 15:08:12 +0000860void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000861 SourceLocation Loc = prop->getAtLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000862
Benjamin Kramerd999b372010-02-14 14:14:16 +0000863 ReplaceText(Loc, 0, "// ");
Steve Naroff6327e0d2009-01-11 01:06:09 +0000864 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000865}
866
Steve Naroffb29b4272008-04-14 22:03:09 +0000867void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000868 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000869
Steve Naroff423cb562007-10-30 13:30:57 +0000870 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000871 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000872
Fariborz Jahanian13751e32010-02-10 01:15:09 +0000873 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
874 E = CatDecl->prop_end(); I != E; ++I)
875 RewriteProperty(*I);
876
Mike Stump1eb44332009-09-09 15:08:12 +0000877 for (ObjCCategoryDecl::instmeth_iterator
878 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000879 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000880 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +0000881 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000882 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000883 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000884 RewriteMethodDeclaration(*I);
885
Steve Naroff423cb562007-10-30 13:30:57 +0000886 // Lastly, comment out the @end.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000887 ReplaceText(CatDecl->getAtEndRange().getBegin(), 0, "// ");
Steve Naroff423cb562007-10-30 13:30:57 +0000888}
889
Steve Naroffb29b4272008-04-14 22:03:09 +0000890void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000891 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Mike Stump1eb44332009-09-09 15:08:12 +0000892
Steve Naroff752d6ef2007-10-30 16:42:30 +0000893 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000894
Steve Naroff752d6ef2007-10-30 16:42:30 +0000895 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000896 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000897
898 for (ObjCProtocolDecl::instmeth_iterator
899 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000900 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000901 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000902 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000903 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000904 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000905 RewriteMethodDeclaration(*I);
906
Steve Naroff752d6ef2007-10-30 16:42:30 +0000907 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +0000908 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Benjamin Kramerd999b372010-02-14 14:14:16 +0000909 ReplaceText(LocEnd, 0, "// ");
Steve Naroff8cc764c2007-11-14 15:03:57 +0000910
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000911 // Must comment out @optional/@required
912 const char *startBuf = SM->getCharacterData(LocStart);
913 const char *endBuf = SM->getCharacterData(LocEnd);
914 for (const char *p = startBuf; p < endBuf; p++) {
915 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Steve Naroff8cc764c2007-11-14 15:03:57 +0000916 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000917 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump1eb44332009-09-09 15:08:12 +0000918
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000919 }
920 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Steve Naroff8cc764c2007-11-14 15:03:57 +0000921 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000922 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump1eb44332009-09-09 15:08:12 +0000923
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000924 }
925 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000926}
927
Steve Naroffb29b4272008-04-14 22:03:09 +0000928void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000929 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000930 if (LocStart.isInvalid())
931 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000932 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000933 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000934}
935
Mike Stump1eb44332009-09-09 15:08:12 +0000936void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000937 std::string &ResultStr) {
Steve Naroffced80a82008-10-30 12:09:33 +0000938 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroff76e429d2008-07-16 14:40:40 +0000939 const FunctionType *FPRetType = 0;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000940 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000941 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000942 ResultStr += "id";
Steve Narofff4312dc2008-12-11 19:29:16 +0000943 else if (OMD->getResultType()->isFunctionPointerType() ||
944 OMD->getResultType()->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +0000945 // needs special handling, since pointer-to-functions have special
946 // syntax (where a decaration models use).
947 QualType retType = OMD->getResultType();
Steve Narofff4312dc2008-12-11 19:29:16 +0000948 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +0000949 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +0000950 PointeeTy = PT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000951 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +0000952 PointeeTy = BPT->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +0000953 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Steve Narofff4312dc2008-12-11 19:29:16 +0000954 ResultStr += FPRetType->getResultType().getAsString();
955 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +0000956 }
957 } else
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000958 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000959 ResultStr += " ";
Mike Stump1eb44332009-09-09 15:08:12 +0000960
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000961 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000962 std::string NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +0000963
Douglas Gregorf8d49f62009-01-09 17:18:27 +0000964 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000965 NameStr += "_I_";
966 else
967 NameStr += "_C_";
Mike Stump1eb44332009-09-09 15:08:12 +0000968
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000969 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000970 NameStr += "_";
Mike Stump1eb44332009-09-09 15:08:12 +0000971
972 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +0000973 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000974 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000975 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000976 }
Mike Stump1eb44332009-09-09 15:08:12 +0000977 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +0000978 {
979 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000980 int len = selString.size();
981 for (int i = 0; i < len; i++)
982 if (selString[i] == ':')
983 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000984 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000985 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000986 // Remember this name for metadata emission
987 MethodInternalNames[OMD] = NameStr;
988 ResultStr += NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +0000989
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000990 // Rewrite arguments
991 ResultStr += "(";
Mike Stump1eb44332009-09-09 15:08:12 +0000992
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000993 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +0000994 if (OMD->isInstanceMethod()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000995 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000996 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000997 if (!LangOpts.Microsoft) {
998 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
999 ResultStr += "struct ";
1000 }
1001 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001002 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001003 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001004 }
1005 else
Steve Naroff621edce2009-04-29 16:37:50 +00001006 ResultStr += Context->getObjCClassType().getAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00001007
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001008 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001009 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001010 ResultStr += " _cmd";
Mike Stump1eb44332009-09-09 15:08:12 +00001011
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001012 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +00001013 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1014 E = OMD->param_end(); PI != E; ++PI) {
1015 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001016 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +00001017 if (PDecl->getType()->isObjCQualifiedIdType()) {
1018 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001019 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +00001020 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001021 std::string Name = PDecl->getNameAsString();
Steve Naroff01f2ffa2008-12-11 21:05:33 +00001022 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroffc8ad87b2008-10-30 14:45:29 +00001023 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Ted Kremenek6217b802009-07-29 21:53:49 +00001024 const BlockPointerType *BPT = PDecl->getType()->getAs<BlockPointerType>();
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001025 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name,
1026 Context->PrintingPolicy);
Steve Naroffc8ad87b2008-10-30 14:45:29 +00001027 } else
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001028 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroff543409e2008-04-18 21:13:19 +00001029 ResultStr += Name;
1030 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001031 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +00001032 if (OMD->isVariadic())
1033 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001034 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +00001035
Steve Naroff76e429d2008-07-16 14:40:40 +00001036 if (FPRetType) {
1037 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +00001038
Steve Naroff76e429d2008-07-16 14:40:40 +00001039 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +00001040 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001041 ResultStr += "(";
1042 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1043 if (i) ResultStr += ", ";
1044 std::string ParamStr = FT->getArgType(i).getAsString();
1045 ResultStr += ParamStr;
1046 }
1047 if (FT->isVariadic()) {
1048 if (FT->getNumArgs()) ResultStr += ", ";
1049 ResultStr += "...";
1050 }
1051 ResultStr += ")";
1052 } else {
1053 ResultStr += "()";
1054 }
1055 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001056}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001057void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001058 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1059 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001060
Fariborz Jahaniana1352162010-02-15 21:11:41 +00001061 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001062
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001063 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001064 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1065 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001066 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001067 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001068 ObjCMethodDecl *OMD = *I;
1069 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001070 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001071 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001072
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001073 const char *startBuf = SM->getCharacterData(LocStart);
1074 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001075 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001076 }
Mike Stump1eb44332009-09-09 15:08:12 +00001077
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001078 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001079 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1080 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001081 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001082 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001083 ObjCMethodDecl *OMD = *I;
1084 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001085 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001086 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001087
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001088 const char *startBuf = SM->getCharacterData(LocStart);
1089 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001090 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001091 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001092 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001093 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001094 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001095 I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001096 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001097 }
1098
Benjamin Kramerd999b372010-02-14 14:14:16 +00001099 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001100}
1101
Steve Naroffb29b4272008-04-14 22:03:09 +00001102void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001103 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001104 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001105 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001106 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001107 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001108 ResultStr += "\n";
1109 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001110 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001111 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001112 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001113 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001114 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001115 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001116 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001117 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001118 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001119
1120 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001121 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff6327e0d2009-01-11 01:06:09 +00001122 RewriteProperty(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001123 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001124 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001125 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001126 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001127 for (ObjCInterfaceDecl::classmeth_iterator
1128 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001129 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001130 RewriteMethodDeclaration(*I);
1131
Steve Naroff2feac5e2007-10-30 03:43:13 +00001132 // Lastly, comment out the @end.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001133 ReplaceText(ClassDecl->getAtEndRange().getBegin(), 0, "// ");
Steve Naroffbef11852007-10-26 20:53:56 +00001134}
1135
Steve Naroffb619d952008-12-09 12:56:34 +00001136Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1137 SourceRange SrcRange) {
Steve Naroffc77a6362008-12-04 16:24:46 +00001138 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1139 // This allows us to reuse all the fun and games in SynthMessageExpr().
1140 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1141 ObjCMessageExpr *MsgExpr;
1142 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1143 llvm::SmallVector<Expr *, 1> ExprVec;
1144 ExprVec.push_back(newStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001145
Steve Naroff8599e7a2008-12-08 16:43:47 +00001146 Stmt *Receiver = PropRefExpr->getBase();
1147 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1148 if (PRE && PropGetters[PRE]) {
1149 // This allows us to handle chain/nested property getters.
1150 Receiver = PropGetters[PRE];
1151 }
Ted Kremenekeb3b3242010-02-11 22:41:21 +00001152 MsgExpr = new (Context) ObjCMessageExpr(*Context, dyn_cast<Expr>(Receiver),
Mike Stump1eb44332009-09-09 15:08:12 +00001153 PDecl->getSetterName(), PDecl->getType(),
1154 PDecl->getSetterMethodDecl(),
1155 SourceLocation(), SourceLocation(),
Steve Naroffc77a6362008-12-04 16:24:46 +00001156 &ExprVec[0], 1);
1157 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001158
Steve Naroffc77a6362008-12-04 16:24:46 +00001159 // Now do the actual rewrite.
Steve Naroffb619d952008-12-09 12:56:34 +00001160 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffe58ee0c2008-12-10 14:53:27 +00001161 //delete BinOp;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001162 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1163 // to things that stay around.
1164 Context->Deallocate(MsgExpr);
Steve Naroffc77a6362008-12-04 16:24:46 +00001165 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001166}
1167
Steve Naroffc77a6362008-12-04 16:24:46 +00001168Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Naroff15f081d2008-12-03 00:56:33 +00001169 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1170 // This allows us to reuse all the fun and games in SynthMessageExpr().
1171 ObjCMessageExpr *MsgExpr;
1172 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
Mike Stump1eb44332009-09-09 15:08:12 +00001173
Steve Naroff8599e7a2008-12-08 16:43:47 +00001174 Stmt *Receiver = PropRefExpr->getBase();
Mike Stump1eb44332009-09-09 15:08:12 +00001175
Steve Naroff8599e7a2008-12-08 16:43:47 +00001176 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1177 if (PRE && PropGetters[PRE]) {
1178 // This allows us to handle chain/nested property getters.
1179 Receiver = PropGetters[PRE];
1180 }
Ted Kremenekeb3b3242010-02-11 22:41:21 +00001181 MsgExpr = new (Context) ObjCMessageExpr(*Context, dyn_cast<Expr>(Receiver),
Mike Stump1eb44332009-09-09 15:08:12 +00001182 PDecl->getGetterName(), PDecl->getType(),
1183 PDecl->getGetterMethodDecl(),
1184 SourceLocation(), SourceLocation(),
Steve Naroff15f081d2008-12-03 00:56:33 +00001185 0, 0);
1186
Steve Naroff4c3580e2008-12-04 23:50:32 +00001187 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001188
1189 if (!PropParentMap)
1190 PropParentMap = new ParentMap(CurrentBody);
1191
1192 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1193 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1194 // We stash away the ReplacingStmt since actually doing the
1195 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1196 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001197 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1198 // to things that stay around.
1199 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001200 return PropRefExpr; // return the original...
1201 } else {
1202 ReplaceStmt(PropRefExpr, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001203 // delete PropRefExpr; elsewhere...
Ted Kremenek8189cde2009-02-07 01:47:29 +00001204 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1205 // to things that stay around.
1206 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001207 return ReplacingStmt;
1208 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001209}
1210
Mike Stump1eb44332009-09-09 15:08:12 +00001211Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001212 SourceLocation OrigStart,
1213 bool &replaced) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001214 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001215 const Expr *BaseExpr = IV->getBase();
Steve Naroff54055232008-10-27 17:20:55 +00001216 if (CurMethodDef) {
Fariborz Jahanian8f095432010-01-26 18:28:51 +00001217 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001218 ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001219 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianffbdead2010-01-26 20:37:44 +00001220 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Narofff0757612008-05-08 17:52:16 +00001221 // lookup which class implements the instance variable.
1222 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001223 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001224 clsDeclared);
Steve Narofff0757612008-05-08 17:52:16 +00001225 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001226
Steve Narofff0757612008-05-08 17:52:16 +00001227 // Synthesize an explicit cast to gain access to the ivar.
1228 std::string RecName = clsDeclared->getIdentifier()->getName();
1229 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001230 IdentifierInfo *II = &Context->Idents.get(RecName);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001231 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001232 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +00001233 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1234 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001235 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1236 CastExpr::CK_Unknown,
1237 IV->getBase());
Steve Narofff0757612008-05-08 17:52:16 +00001238 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001239 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1240 IV->getBase()->getLocEnd(),
1241 castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001242 replaced = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001243 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001244 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001245 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1246 IV->getLocation(),
1247 D->getType());
Steve Naroff4c3580e2008-12-04 23:50:32 +00001248 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001249 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001250 }
Fariborz Jahanian7e20ffe2010-01-28 01:41:20 +00001251 // Get the new text
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001252 // Cannot delete IV->getBase(), since PE points to it.
1253 // Replace the old base with the cast. This is important when doing
1254 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001255 IV->setBase(PE);
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001256 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001257 }
Steve Naroff84472a82008-04-18 21:55:08 +00001258 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001259 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump1eb44332009-09-09 15:08:12 +00001260
Steve Naroff9f525972008-05-06 23:20:07 +00001261 // Explicit ivar refs need to have a cast inserted.
1262 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian26337b22010-01-12 17:31:23 +00001263 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Fariborz Jahanianc374cd92010-01-11 17:50:35 +00001264 ObjCInterfaceType *iFaceDecl =
1265 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001266 // lookup which class implements the instance variable.
1267 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001268 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001269 clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001270 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001271
Steve Naroff9f525972008-05-06 23:20:07 +00001272 // Synthesize an explicit cast to gain access to the ivar.
1273 std::string RecName = clsDeclared->getIdentifier()->getName();
1274 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001275 IdentifierInfo *II = &Context->Idents.get(RecName);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001276 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001277 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001278 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1279 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001280 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1281 CastExpr::CK_Unknown,
1282 IV->getBase());
Steve Naroff9f525972008-05-06 23:20:07 +00001283 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001284 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner8d366162008-05-28 16:38:23 +00001285 IV->getBase()->getLocEnd(), castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001286 replaced = true;
Steve Naroff9f525972008-05-06 23:20:07 +00001287 // Cannot delete IV->getBase(), since PE points to it.
1288 // Replace the old base with the cast. This is important when doing
1289 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001290 IV->setBase(PE);
Steve Naroff9f525972008-05-06 23:20:07 +00001291 return IV;
1292 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001293 }
Steve Naroff84472a82008-04-18 21:55:08 +00001294 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001295}
1296
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001297Stmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) {
1298 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1299 CI != E; ++CI) {
1300 if (*CI) {
1301 Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced);
1302 if (newStmt)
1303 *CI = newStmt;
1304 }
1305 }
1306 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
1307 SourceRange OrigStmtRange = S->getSourceRange();
1308 Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(),
1309 replaced);
1310 return newStmt;
Fariborz Jahanian376338a2010-02-05 17:48:10 +00001311 }
1312 if (ObjCMessageExpr *MsgRefExpr = dyn_cast<ObjCMessageExpr>(S)) {
1313 Stmt *newStmt = SynthMessageExpr(MsgRefExpr);
1314 return newStmt;
1315 }
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001316 return S;
1317}
1318
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001319/// SynthCountByEnumWithState - To print:
1320/// ((unsigned int (*)
1321/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001322/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001323/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001324/// "countByEnumeratingWithState:objects:count:"),
1325/// &enumState,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001326/// (id *)items, (unsigned int)16)
1327///
Steve Naroffb29b4272008-04-14 22:03:09 +00001328void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001329 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1330 "id *, unsigned int))(void *)objc_msgSend)";
1331 buf += "\n\t\t";
1332 buf += "((id)l_collection,\n\t\t";
1333 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1334 buf += "\n\t\t";
1335 buf += "&enumState, "
1336 "(id *)items, (unsigned int)16)";
1337}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001338
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001339/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1340/// statement to exit to its outer synthesized loop.
1341///
Steve Naroffb29b4272008-04-14 22:03:09 +00001342Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001343 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1344 return S;
1345 // replace break with goto __break_label
1346 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001347
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001348 SourceLocation startLoc = S->getLocStart();
1349 buf = "goto __break_label_";
1350 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001351 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001352
1353 return 0;
1354}
1355
1356/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1357/// statement to continue with its inner synthesized loop.
1358///
Steve Naroffb29b4272008-04-14 22:03:09 +00001359Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001360 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1361 return S;
1362 // replace continue with goto __continue_label
1363 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001364
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001365 SourceLocation startLoc = S->getLocStart();
1366 buf = "goto __continue_label_";
1367 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001368 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001369
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001370 return 0;
1371}
1372
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001373/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001374/// It rewrites:
1375/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001376
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001377/// Into:
1378/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001379/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001380/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001381/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001382/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001383/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001384/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001385/// if (limit) {
1386/// unsigned long startMutations = *enumState.mutationsPtr;
1387/// do {
1388/// unsigned long counter = 0;
1389/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001390/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001391/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001392/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001393/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001394/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001395/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001396/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001397/// objects:items count:16]);
1398/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001399/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001400/// }
1401/// else
1402/// elem = nil;
1403/// }
1404///
Steve Naroffb29b4272008-04-14 22:03:09 +00001405Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001406 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001407 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001408 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001409 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001410 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001411 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001412
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001413 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001414 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001415 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001416 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001417 std::string buf;
1418 buf = "\n{\n\t";
1419 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1420 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001421 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001422 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001423 if (ElementType->isObjCQualifiedIdType() ||
1424 ElementType->isObjCQualifiedInterfaceType())
1425 // Simply use 'id' for all qualified types.
1426 elementTypeAsString = "id";
1427 else
1428 elementTypeAsString = ElementType.getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001429 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001430 buf += " ";
Chris Lattner8ec03f52008-11-24 03:54:41 +00001431 elementName = D->getNameAsCString();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001432 buf += elementName;
1433 buf += ";\n\t";
1434 }
Chris Lattner06767512008-04-08 05:52:18 +00001435 else {
1436 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001437 elementName = DR->getDecl()->getNameAsCString();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001438 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1439 if (VD->getType()->isObjCQualifiedIdType() ||
1440 VD->getType()->isObjCQualifiedInterfaceType())
1441 // Simply use 'id' for all qualified types.
1442 elementTypeAsString = "id";
1443 else
1444 elementTypeAsString = VD->getType().getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001445 }
Mike Stump1eb44332009-09-09 15:08:12 +00001446
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001447 // struct __objcFastEnumerationState enumState = { 0 };
1448 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1449 // id items[16];
1450 buf += "id items[16];\n\t";
1451 // id l_collection = (id)
1452 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001453 // Find start location of 'collection' the hard way!
1454 const char *startCollectionBuf = startBuf;
1455 startCollectionBuf += 3; // skip 'for'
1456 startCollectionBuf = strchr(startCollectionBuf, '(');
1457 startCollectionBuf++; // skip '('
1458 // find 'in' and skip it.
1459 while (*startCollectionBuf != ' ' ||
1460 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1461 (*(startCollectionBuf+3) != ' ' &&
1462 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1463 startCollectionBuf++;
1464 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001465
1466 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001467 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001468 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001469 SourceLocation rightParenLoc = S->getRParenLoc();
1470 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1471 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001472 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001473
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001474 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1475 // objects:items count:16];
1476 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001477 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001478 // ((unsigned int (*)
1479 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001480 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001481 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001482 // "countByEnumeratingWithState:objects:count:"),
1483 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001484 // (id *)items, (unsigned int)16);
1485 buf += "unsigned long limit =\n\t\t";
1486 SynthCountByEnumWithState(buf);
1487 buf += ";\n\t";
1488 /// if (limit) {
1489 /// unsigned long startMutations = *enumState.mutationsPtr;
1490 /// do {
1491 /// unsigned long counter = 0;
1492 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001493 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001494 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001495 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001496 buf += "if (limit) {\n\t";
1497 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1498 buf += "do {\n\t\t";
1499 buf += "unsigned long counter = 0;\n\t\t";
1500 buf += "do {\n\t\t\t";
1501 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1502 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1503 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001504 buf += " = (";
1505 buf += elementTypeAsString;
1506 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001507 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001508 ReplaceText(lparenLoc, 1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001509
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001510 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001511 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001512 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001513 /// objects:items count:16]);
1514 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001515 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001516 /// }
1517 /// else
1518 /// elem = nil;
1519 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001520 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001521 buf = ";\n\t";
1522 buf += "__continue_label_";
1523 buf += utostr(ObjCBcLabelNo.back());
1524 buf += ": ;";
1525 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001526 buf += "} while (counter < limit);\n\t";
1527 buf += "} while (limit = ";
1528 SynthCountByEnumWithState(buf);
1529 buf += ");\n\t";
1530 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001531 buf += " = ((";
1532 buf += elementTypeAsString;
1533 buf += ")0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001534 buf += "__break_label_";
1535 buf += utostr(ObjCBcLabelNo.back());
1536 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001537 buf += "}\n\t";
1538 buf += "else\n\t\t";
1539 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001540 buf += " = ((";
1541 buf += elementTypeAsString;
1542 buf += ")0);\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001543 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001544
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001545 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001546 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001547 if (isa<CompoundStmt>(S->getBody())) {
1548 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001549 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001550 } else {
1551 /* Need to treat single statements specially. For example:
1552 *
1553 * for (A *a in b) if (stuff()) break;
1554 * for (A *a in b) xxxyy;
1555 *
1556 * The following code simply scans ahead to the semi to find the actual end.
1557 */
1558 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1559 const char *semiBuf = strchr(stmtBuf, ';');
1560 assert(semiBuf && "Can't find ';'");
1561 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001562 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001563 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001564 Stmts.pop_back();
1565 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001566 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001567}
1568
Mike Stump1eb44332009-09-09 15:08:12 +00001569/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001570/// This routine rewrites @synchronized(expr) stmt;
1571/// into:
1572/// objc_sync_enter(expr);
1573/// @try stmt @finally { objc_sync_exit(expr); }
1574///
Steve Naroffb29b4272008-04-14 22:03:09 +00001575Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001576 // Get the start location and compute the semi location.
1577 SourceLocation startLoc = S->getLocStart();
1578 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001579
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001580 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001581
1582 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001583 buf = "objc_sync_enter((id)";
1584 const char *lparenBuf = startBuf;
1585 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramerd999b372010-02-14 14:14:16 +00001586 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001587 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1588 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001589 // been rewritten! (which implies the SourceLocation's are invalid).
1590 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001591 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001592 while (*endBuf != ')') endBuf--;
1593 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001594 buf = ");\n";
1595 // declare a new scope with two variables, _stack and _rethrow.
1596 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1597 buf += "int buf[18/*32-bit i386*/];\n";
1598 buf += "char *pointers[4];} _stack;\n";
1599 buf += "id volatile _rethrow = 0;\n";
1600 buf += "objc_exception_try_enter(&_stack);\n";
1601 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001602 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001603 startLoc = S->getSynchBody()->getLocEnd();
1604 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001605
Steve Naroffc7089f12008-08-19 13:04:19 +00001606 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001607 SourceLocation lastCurlyLoc = startLoc;
1608 buf = "}\nelse {\n";
1609 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001610 buf += "}\n";
1611 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001612 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001613
1614 std::string syncBuf;
1615 syncBuf += " objc_sync_exit(";
John McCall9d125032010-01-15 18:39:57 +00001616 Expr *syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1617 CastExpr::CK_Unknown,
1618 S->getSynchExpr());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001619 std::string syncExprBufS;
1620 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00001621 syncExpr->printPretty(syncExprBuf, *Context, 0,
1622 PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001623 syncBuf += syncExprBuf.str();
1624 syncBuf += ");";
1625
1626 buf += syncBuf;
1627 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001628 buf += "}\n";
1629 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001630
Benjamin Kramerd999b372010-02-14 14:14:16 +00001631 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001632
1633 bool hasReturns = false;
1634 HasReturnStmts(S->getSynchBody(), hasReturns);
1635 if (hasReturns)
1636 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1637
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001638 return 0;
1639}
1640
Steve Naroffb85e77a2009-12-05 21:43:12 +00001641void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1642{
Steve Naroff8c565152008-12-05 17:03:39 +00001643 // Perform a bottom up traversal of all children.
1644 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1645 CI != E; ++CI)
1646 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001647 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001648
Steve Naroffb85e77a2009-12-05 21:43:12 +00001649 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001650 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001651 TryFinallyContainsReturnDiag);
1652 }
1653 return;
1654}
1655
Steve Naroffb85e77a2009-12-05 21:43:12 +00001656void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1657{
1658 // Perform a bottom up traversal of all children.
1659 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1660 CI != E; ++CI)
1661 if (*CI)
1662 HasReturnStmts(*CI, hasReturns);
1663
1664 if (isa<ReturnStmt>(S))
1665 hasReturns = true;
1666 return;
1667}
1668
1669void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1670 // Perform a bottom up traversal of all children.
1671 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1672 CI != E; ++CI)
1673 if (*CI) {
1674 RewriteTryReturnStmts(*CI);
1675 }
1676 if (isa<ReturnStmt>(S)) {
1677 SourceLocation startLoc = S->getLocStart();
1678 const char *startBuf = SM->getCharacterData(startLoc);
1679
1680 const char *semiBuf = strchr(startBuf, ';');
1681 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1682 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1683
1684 std::string buf;
1685 buf = "{ objc_exception_try_exit(&_stack); return";
1686
Benjamin Kramerd999b372010-02-14 14:14:16 +00001687 ReplaceText(startLoc, 6, buf);
1688 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001689 }
1690 return;
1691}
1692
1693void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1694 // Perform a bottom up traversal of all children.
1695 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1696 CI != E; ++CI)
1697 if (*CI) {
1698 RewriteSyncReturnStmts(*CI, syncExitBuf);
1699 }
1700 if (isa<ReturnStmt>(S)) {
1701 SourceLocation startLoc = S->getLocStart();
1702 const char *startBuf = SM->getCharacterData(startLoc);
1703
1704 const char *semiBuf = strchr(startBuf, ';');
1705 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1706 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1707
1708 std::string buf;
1709 buf = "{ objc_exception_try_exit(&_stack);";
1710 buf += syncExitBuf;
1711 buf += " return";
1712
Benjamin Kramerd999b372010-02-14 14:14:16 +00001713 ReplaceText(startLoc, 6, buf);
1714 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001715 }
1716 return;
1717}
1718
Steve Naroffb29b4272008-04-14 22:03:09 +00001719Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001720 // Get the start location and compute the semi location.
1721 SourceLocation startLoc = S->getLocStart();
1722 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001723
Steve Naroff75730982007-11-07 04:08:17 +00001724 assert((*startBuf == '@') && "bogus @try location");
1725
1726 std::string buf;
1727 // declare a new scope with two variables, _stack and _rethrow.
1728 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1729 buf += "int buf[18/*32-bit i386*/];\n";
1730 buf += "char *pointers[4];} _stack;\n";
1731 buf += "id volatile _rethrow = 0;\n";
1732 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001733 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001734
Benjamin Kramerd999b372010-02-14 14:14:16 +00001735 ReplaceText(startLoc, 4, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001736
Steve Naroff75730982007-11-07 04:08:17 +00001737 startLoc = S->getTryBody()->getLocEnd();
1738 startBuf = SM->getCharacterData(startLoc);
1739
1740 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001741
Steve Naroff75730982007-11-07 04:08:17 +00001742 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-07-16 15:31:30 +00001743 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1744 if (catchList) {
1745 startLoc = startLoc.getFileLocWithOffset(1);
1746 buf = " /* @catch begin */ else {\n";
1747 buf += " id _caught = objc_exception_extract(&_stack);\n";
1748 buf += " objc_exception_try_enter (&_stack);\n";
1749 buf += " if (_setjmp(_stack.buf))\n";
1750 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1751 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00001752
Benjamin Kramerd999b372010-02-14 14:14:16 +00001753 InsertText(startLoc, buf);
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001754 } else { /* no catch list */
1755 buf = "}\nelse {\n";
1756 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1757 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001758 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001759 }
Steve Naroff75730982007-11-07 04:08:17 +00001760 bool sawIdTypedCatch = false;
1761 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001762 while (catchList) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00001763 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00001764
Mike Stump1eb44332009-09-09 15:08:12 +00001765 if (catchList == S->getCatchStmts())
Steve Naroff75730982007-11-07 04:08:17 +00001766 buf = "if ("; // we are generating code for the first catch clause
1767 else
1768 buf = "else if (";
1769 startLoc = catchList->getLocStart();
1770 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001771
Steve Naroff75730982007-11-07 04:08:17 +00001772 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00001773
Steve Naroff75730982007-11-07 04:08:17 +00001774 const char *lParenLoc = strchr(startBuf, '(');
1775
Steve Naroffbe4b3332008-02-01 22:08:12 +00001776 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001777 // Now rewrite the body...
1778 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001779 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1780 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001781 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1782 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001783 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001784
Steve Naroffe12e6922008-02-01 20:02:07 +00001785 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00001786 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00001787 } else if (catchDecl) {
1788 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001789 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001790 buf += "1) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001791 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00001792 sawIdTypedCatch = true;
Fariborz Jahanian66867c52010-01-12 01:22:23 +00001793 } else if (t->isObjCObjectPointerType()) {
1794 QualType InterfaceTy = t->getPointeeType();
1795 const ObjCInterfaceType *cls = // Should be a pointer to a class.
1796 InterfaceTy->getAs<ObjCInterfaceType>();
Steve Naroff75730982007-11-07 04:08:17 +00001797 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001798 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001799 buf += cls->getDecl()->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001800 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001801 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00001802 }
1803 }
1804 // Now rewrite the body...
1805 lastCatchBody = catchList->getCatchBody();
1806 SourceLocation rParenLoc = catchList->getRParenLoc();
1807 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1808 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1809 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1810 assert((*rParenBuf == ')') && "bogus @catch paren location");
1811 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001812
Mike Stump1eb44332009-09-09 15:08:12 +00001813 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00001814 // declares the @catch parameter).
Benjamin Kramerd999b372010-02-14 14:14:16 +00001815 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff7ba138a2009-03-03 19:52:17 +00001816 } else {
Steve Naroff75730982007-11-07 04:08:17 +00001817 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001818 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001819 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001820 catchList = catchList->getNextCatchStmt();
1821 }
1822 // Complete the catch list...
1823 if (lastCatchBody) {
1824 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001825 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1826 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001827
Steve Naroff378f47a2008-09-11 15:29:03 +00001828 // Insert the last (implicit) else clause *before* the right curly brace.
1829 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1830 buf = "} /* last catch end */\n";
1831 buf += "else {\n";
1832 buf += " _rethrow = _caught;\n";
1833 buf += " objc_exception_try_exit(&_stack);\n";
1834 buf += "} } /* @catch end */\n";
1835 if (!S->getFinallyStmt())
1836 buf += "}\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001837 InsertText(bodyLoc, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001838
Steve Naroff75730982007-11-07 04:08:17 +00001839 // Set lastCurlyLoc
1840 lastCurlyLoc = lastCatchBody->getLocEnd();
1841 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001842 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001843 startLoc = finalStmt->getLocStart();
1844 startBuf = SM->getCharacterData(startLoc);
1845 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00001846
Benjamin Kramerd999b372010-02-14 14:14:16 +00001847 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump1eb44332009-09-09 15:08:12 +00001848
Steve Naroff75730982007-11-07 04:08:17 +00001849 Stmt *body = finalStmt->getFinallyBody();
1850 SourceLocation startLoc = body->getLocStart();
1851 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001852 assert(*SM->getCharacterData(startLoc) == '{' &&
1853 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001854 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00001855 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001856
Steve Naroff75730982007-11-07 04:08:17 +00001857 startLoc = startLoc.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001858 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Steve Naroff75730982007-11-07 04:08:17 +00001859 endLoc = endLoc.getFileLocWithOffset(-1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001860 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump1eb44332009-09-09 15:08:12 +00001861
Steve Naroff75730982007-11-07 04:08:17 +00001862 // Set lastCurlyLoc
1863 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00001864
Steve Naroff8c565152008-12-05 17:03:39 +00001865 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00001866 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00001867 } else { /* no finally clause - make sure we synthesize an implicit one */
1868 buf = "{ /* implicit finally clause */\n";
1869 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1870 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1871 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001872 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001873
1874 // Now check for any return/continue/go statements within the @try.
1875 // The implicit finally clause won't called if the @try contains any
1876 // jump statements.
1877 bool hasReturns = false;
1878 HasReturnStmts(S->getTryBody(), hasReturns);
1879 if (hasReturns)
1880 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00001881 }
1882 // Now emit the final closing curly brace...
1883 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001884 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001885 return 0;
1886}
1887
Steve Naroffb29b4272008-04-14 22:03:09 +00001888Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001889 return 0;
1890}
1891
Steve Naroffb29b4272008-04-14 22:03:09 +00001892Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001893 return 0;
1894}
1895
Mike Stump1eb44332009-09-09 15:08:12 +00001896// This can't be done with ReplaceStmt(S, ThrowExpr), since
1897// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00001898// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001899Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001900 // Get the start location and compute the semi location.
1901 SourceLocation startLoc = S->getLocStart();
1902 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001903
Steve Naroff2bd03922007-11-07 15:32:26 +00001904 assert((*startBuf == '@') && "bogus @throw location");
1905
1906 std::string buf;
1907 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001908 if (S->getThrowExpr())
1909 buf = "objc_exception_throw(";
1910 else // add an implicit argument
1911 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00001912
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001913 // handle "@ throw" correctly.
1914 const char *wBuf = strchr(startBuf, 'w');
1915 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramerd999b372010-02-14 14:14:16 +00001916 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001917
Steve Naroff2bd03922007-11-07 15:32:26 +00001918 const char *semiBuf = strchr(startBuf, ';');
1919 assert((*semiBuf == ';') && "@throw: can't find ';'");
1920 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001921 ReplaceText(semiLoc, 1, ");");
Steve Naroff2bd03922007-11-07 15:32:26 +00001922 return 0;
1923}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001924
Steve Naroffb29b4272008-04-14 22:03:09 +00001925Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001926 // Create a new string expression.
1927 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001928 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001929 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattner2085fd62009-02-18 06:40:38 +00001930 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
1931 StrEncoding.length(), false,StrType,
1932 SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001933 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00001934
Chris Lattner07506182007-11-30 22:53:43 +00001935 // Replace this subexpr in the parent.
Steve Naroff4c3580e2008-12-04 23:50:32 +00001936 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00001937 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001938}
1939
Steve Naroffb29b4272008-04-14 22:03:09 +00001940Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00001941 if (!SelGetUidFunctionDecl)
1942 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00001943 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1944 // Create a call to sel_registerName("selName").
1945 llvm::SmallVector<Expr*, 8> SelExprs;
1946 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001947 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00001948 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00001949 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00001950 false, argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00001951 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1952 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001953 ReplaceStmt(Exp, SelExp);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001954 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00001955 return SelExp;
1956}
1957
Steve Naroffb29b4272008-04-14 22:03:09 +00001958CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00001959 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
1960 SourceLocation EndLoc) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001961 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001962 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001963
Steve Naroffebf2b562007-10-23 23:50:29 +00001964 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001965 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001966
Steve Naroffebf2b562007-10-23 23:50:29 +00001967 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001968 QualType pToFunc = Context->getPointerType(msgSendType);
Mike Stump1eb44332009-09-09 15:08:12 +00001969 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc,
Anders Carlssoncdef2b72009-07-31 00:48:10 +00001970 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00001971 DRE,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001972 /*isLvalue=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00001973
John McCall183700f2009-09-21 23:43:11 +00001974 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001975
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00001976 CallExpr *Exp =
1977 new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
1978 EndLoc);
1979 return Exp;
Steve Naroff934f2762007-10-24 22:48:43 +00001980}
1981
Steve Naroffd5255f52007-11-01 13:24:47 +00001982static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1983 const char *&startRef, const char *&endRef) {
1984 while (startBuf < endBuf) {
1985 if (*startBuf == '<')
1986 startRef = startBuf; // mark the start.
1987 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001988 if (startRef && *startRef == '<') {
1989 endRef = startBuf; // mark the end.
1990 return true;
1991 }
1992 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001993 }
1994 startBuf++;
1995 }
1996 return false;
1997}
1998
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001999static void scanToNextArgument(const char *&argRef) {
2000 int angle = 0;
2001 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2002 if (*argRef == '<')
2003 angle++;
2004 else if (*argRef == '>')
2005 angle--;
2006 argRef++;
2007 }
2008 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2009}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002010
Steve Naroffb29b4272008-04-14 22:03:09 +00002011bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian32132a02010-02-03 21:29:28 +00002012 if (T->isObjCQualifiedIdType())
2013 return true;
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002014 if (const PointerType *PT = T->getAs<PointerType>()) {
2015 if (PT->getPointeeType()->isObjCQualifiedIdType())
2016 return true;
2017 }
2018 if (T->isObjCObjectPointerType()) {
2019 T = T->getPointeeType();
2020 return T->isObjCQualifiedInterfaceType();
2021 }
2022 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002023}
2024
Steve Naroff4f95b752008-07-29 18:15:38 +00002025void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2026 QualType Type = E->getType();
2027 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00002028 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00002029
Steve Naroffcda658e2008-11-19 21:15:47 +00002030 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2031 Loc = ECE->getLParenLoc();
2032 EndLoc = ECE->getRParenLoc();
2033 } else {
2034 Loc = E->getLocStart();
2035 EndLoc = E->getLocEnd();
2036 }
2037 // This will defend against trying to rewrite synthesized expressions.
2038 if (Loc.isInvalid() || EndLoc.isInvalid())
2039 return;
2040
Steve Naroff4f95b752008-07-29 18:15:38 +00002041 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00002042 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00002043 const char *startRef = 0, *endRef = 0;
2044 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2045 // Get the locations of the startRef, endRef.
2046 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2047 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2048 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002049 InsertText(LessLoc, "/*");
2050 InsertText(GreaterLoc, "*/");
Steve Naroff4f95b752008-07-29 18:15:38 +00002051 }
2052 }
2053}
2054
Steve Naroffb29b4272008-04-14 22:03:09 +00002055void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002056 SourceLocation Loc;
2057 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00002058 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002059 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2060 Loc = VD->getLocation();
2061 Type = VD->getType();
2062 }
2063 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2064 Loc = FD->getLocation();
2065 // Check for ObjC 'id' and class types that have been adorned with protocol
2066 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002067 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002068 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002069 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002070 if (!proto)
2071 return;
2072 Type = proto->getResultType();
2073 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002074 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2075 Loc = FD->getLocation();
2076 Type = FD->getType();
2077 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002078 else
2079 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002080
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002081 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002082 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002083
Steve Naroffd5255f52007-11-01 13:24:47 +00002084 const char *endBuf = SM->getCharacterData(Loc);
2085 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002086 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002087 startBuf--; // scan backward (from the decl location) for return type.
2088 const char *startRef = 0, *endRef = 0;
2089 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2090 // Get the locations of the startRef, endRef.
2091 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2092 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2093 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002094 InsertText(LessLoc, "/*");
2095 InsertText(GreaterLoc, "*/");
Steve Naroff9165ad32007-10-31 04:38:33 +00002096 }
2097 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002098 if (!proto)
2099 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002100 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002101 const char *startBuf = SM->getCharacterData(Loc);
2102 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00002103 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2104 if (needToScanForQualifiers(proto->getArgType(i))) {
2105 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002106
Steve Naroffd5255f52007-11-01 13:24:47 +00002107 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002108 // scan forward (from the decl location) for argument types.
2109 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00002110 const char *startRef = 0, *endRef = 0;
2111 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2112 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002113 SourceLocation LessLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002114 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002115 SourceLocation GreaterLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002116 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002117 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002118 InsertText(LessLoc, "/*");
2119 InsertText(GreaterLoc, "*/");
Steve Naroffd5255f52007-11-01 13:24:47 +00002120 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002121 startBuf = ++endBuf;
2122 }
2123 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002124 // If the function name is derived from a macro expansion, then the
2125 // argument buffer will not follow the name. Need to speak with Chris.
2126 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002127 startBuf++; // scan forward (from the decl location) for argument types.
2128 startBuf++;
2129 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002130 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002131}
2132
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002133void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2134 QualType QT = ND->getType();
2135 const Type* TypePtr = QT->getAs<Type>();
2136 if (!isa<TypeOfExprType>(TypePtr))
2137 return;
2138 while (isa<TypeOfExprType>(TypePtr)) {
2139 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2140 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2141 TypePtr = QT->getAs<Type>();
2142 }
2143 // FIXME. This will not work for multiple declarators; as in:
2144 // __typeof__(a) b,c,d;
2145 std::string TypeAsString(QT.getAsString());
2146 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2147 const char *startBuf = SM->getCharacterData(DeclLoc);
2148 if (ND->getInit()) {
2149 std::string Name(ND->getNameAsString());
2150 TypeAsString += " " + Name + " = ";
2151 Expr *E = ND->getInit();
2152 SourceLocation startLoc;
2153 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2154 startLoc = ECE->getLParenLoc();
2155 else
2156 startLoc = E->getLocStart();
2157 startLoc = SM->getInstantiationLoc(startLoc);
2158 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002159 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002160 }
2161 else {
2162 SourceLocation X = ND->getLocEnd();
2163 X = SM->getInstantiationLoc(X);
2164 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002165 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002166 }
2167}
2168
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002169// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002170void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002171 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2172 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002173 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002174 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002175 &ArgTys[0], ArgTys.size(),
2176 false /*isVariadic*/, 0,
2177 false, false, 0, 0, false,
2178 CC_Default);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002179 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002180 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002181 SelGetUidIdent, getFuncType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002182 FunctionDecl::Extern, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002183}
2184
Steve Naroffb29b4272008-04-14 22:03:09 +00002185void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002186 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002187 if (FD->getIdentifier() &&
2188 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002189 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002190 return;
2191 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002192 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002193}
2194
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002195static void RewriteBlockPointerType(std::string& Str, QualType Type) {
2196 std::string TypeString(Type.getAsString());
2197 const char *argPtr = TypeString.c_str();
2198 if (!strchr(argPtr, '^')) {
2199 Str += TypeString;
2200 return;
2201 }
2202 while (*argPtr) {
2203 Str += (*argPtr == '^' ? '*' : *argPtr);
2204 argPtr++;
2205 }
2206}
2207
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002208// FIXME. Consolidate this routine with RewriteBlockPointerType.
2209static void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD) {
2210 QualType Type = VD->getType();
2211 std::string TypeString(Type.getAsString());
2212 const char *argPtr = TypeString.c_str();
2213 int paren = 0;
2214 while (*argPtr) {
2215 switch (*argPtr) {
2216 case '(':
2217 Str += *argPtr;
2218 paren++;
2219 break;
2220 case ')':
2221 Str += *argPtr;
2222 paren--;
2223 break;
2224 case '^':
2225 Str += '*';
2226 if (paren == 1)
2227 Str += VD->getNameAsString();
2228 break;
2229 default:
2230 Str += *argPtr;
2231 break;
2232 }
2233 argPtr++;
2234 }
2235}
2236
2237
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002238void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2239 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2240 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2241 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2242 if (!proto)
2243 return;
2244 QualType Type = proto->getResultType();
2245 std::string FdStr = Type.getAsString();
2246 FdStr += " ";
2247 FdStr += FD->getNameAsCString();
2248 FdStr += "(";
2249 unsigned numArgs = proto->getNumArgs();
2250 for (unsigned i = 0; i < numArgs; i++) {
2251 QualType ArgType = proto->getArgType(i);
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002252 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002253 if (i+1 < numArgs)
2254 FdStr += ", ";
2255 }
2256 FdStr += ");\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002257 InsertText(FunLocStart, FdStr);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002258 CurFunctionDeclToDeclareForBlock = 0;
2259}
2260
Steve Naroffc0a123c2008-03-11 17:37:02 +00002261// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002262void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002263 if (SuperContructorFunctionDecl)
2264 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002265 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroffc0a123c2008-03-11 17:37:02 +00002266 llvm::SmallVector<QualType, 16> ArgTys;
2267 QualType argT = Context->getObjCIdType();
2268 assert(!argT.isNull() && "Can't find 'id' type");
2269 ArgTys.push_back(argT);
2270 ArgTys.push_back(argT);
2271 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2272 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002273 false, 0,
2274 false, false, 0, 0, false,
2275 CC_Default);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002276 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002277 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002278 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002279 FunctionDecl::Extern, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002280}
2281
Steve Naroff09b266e2007-10-30 23:14:51 +00002282// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002283void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002284 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2285 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002286 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002287 assert(!argT.isNull() && "Can't find 'id' type");
2288 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002289 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002290 assert(!argT.isNull() && "Can't find 'SEL' type");
2291 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002292 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002293 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002294 true /*isVariadic*/, 0,
2295 false, false, 0, 0, false,
2296 CC_Default);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002297 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002298 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002299 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002300 FunctionDecl::Extern, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002301}
2302
Steve Naroff874e2322007-11-15 10:28:18 +00002303// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002304void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002305 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2306 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002307 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002308 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002309 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002310 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2311 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2312 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002313 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002314 assert(!argT.isNull() && "Can't find 'SEL' type");
2315 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002316 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00002317 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002318 true /*isVariadic*/, 0,
2319 false, false, 0, 0, false,
2320 CC_Default);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002321 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002322 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002323 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002324 FunctionDecl::Extern, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002325}
2326
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002327// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002328void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002329 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2330 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002331 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002332 assert(!argT.isNull() && "Can't find 'id' type");
2333 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002334 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002335 assert(!argT.isNull() && "Can't find 'SEL' type");
2336 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002337 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002338 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002339 true /*isVariadic*/, 0,
2340 false, false, 0, 0, false,
2341 CC_Default);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002342 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002343 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002344 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002345 FunctionDecl::Extern, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002346}
2347
Mike Stump1eb44332009-09-09 15:08:12 +00002348// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002349// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002350void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002351 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002352 &Context->Idents.get("objc_msgSendSuper_stret");
2353 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002354 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002355 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002356 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002357 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2358 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2359 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002360 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002361 assert(!argT.isNull() && "Can't find 'SEL' type");
2362 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002363 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002364 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002365 true /*isVariadic*/, 0,
2366 false, false, 0, 0, false,
2367 CC_Default);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002368 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002369 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002370 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002371 FunctionDecl::Extern, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002372}
2373
Steve Naroff1284db82008-05-08 22:02:18 +00002374// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002375void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002376 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2377 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002378 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002379 assert(!argT.isNull() && "Can't find 'id' type");
2380 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002381 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002382 assert(!argT.isNull() && "Can't find 'SEL' type");
2383 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00002384 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002385 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002386 true /*isVariadic*/, 0,
2387 false, false, 0, 0, false,
2388 CC_Default);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002389 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002390 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002391 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002392 FunctionDecl::Extern, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002393}
2394
Steve Naroff09b266e2007-10-30 23:14:51 +00002395// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002396void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002397 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2398 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002399 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002400 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002401 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002402 false /*isVariadic*/, 0,
2403 false, false, 0, 0, false,
2404 CC_Default);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002405 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002406 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002407 getClassIdent, getClassType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002408 FunctionDecl::Extern, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002409}
2410
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002411// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002412void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002413 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2414 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002415 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002416 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002417 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002418 false /*isVariadic*/, 0,
2419 false, false, 0, 0, false,
2420 CC_Default);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002421 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002422 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002423 getClassIdent, getClassType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002424 FunctionDecl::Extern, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002425}
2426
Steve Naroffb29b4272008-04-14 22:03:09 +00002427Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002428 QualType strType = getConstantStringStructType();
2429
2430 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002431
2432 std::string tmpName = InFileName;
2433 unsigned i;
2434 for (i=0; i < tmpName.length(); i++) {
2435 char c = tmpName.at(i);
2436 // replace any non alphanumeric characters with '_'.
2437 if (!isalpha(c) && (c < '0' || c > '9'))
2438 tmpName[i] = '_';
2439 }
2440 S += tmpName;
2441 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002442 S += utostr(NumObjCStringLiterals++);
2443
Steve Naroffba92b2e2008-03-27 22:29:16 +00002444 Preamble += "static __NSConstantStringImpl " + S;
2445 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2446 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002447 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002448 std::string prettyBufS;
2449 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00002450 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2451 PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002452 Preamble += prettyBuf.str();
2453 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002454 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002455
2456 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Benjamin Kramerd999b372010-02-14 14:14:16 +00002457 &Context->Idents.get(S), strType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002458 VarDecl::Static);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002459 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2460 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002461 Context->getPointerType(DRE->getType()),
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002462 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002463 // cast to NSConstantString *
John McCall9d125032010-01-15 18:39:57 +00002464 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2465 CastExpr::CK_Unknown, Unop);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002466 ReplaceStmt(Exp, cast);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002467 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002468 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002469}
2470
Steve Naroffb29b4272008-04-14 22:03:09 +00002471ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002472 // check if we are sending a message to 'super'
Douglas Gregorf8d49f62009-01-09 17:18:27 +00002473 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002474
Douglas Gregorcd9b46e2008-11-04 14:56:14 +00002475 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002476 const ObjCObjectPointerType *OPT =
John McCall183700f2009-09-21 23:43:11 +00002477 Super->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00002478 assert(OPT);
2479 const ObjCInterfaceType *IT = OPT->getInterfaceType();
Chris Lattner0d17f6f2008-06-21 18:04:54 +00002480 return IT->getDecl();
2481 }
2482 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00002483}
2484
2485// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002486QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002487 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002488 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002489 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002490 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002491 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002492
Steve Naroff874e2322007-11-15 10:28:18 +00002493 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002494 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002495 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002496 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002497
Steve Naroff874e2322007-11-15 10:28:18 +00002498 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002499 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002500 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2501 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002502 FieldTypes[i], 0,
2503 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002504 /*Mutable=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002505 }
Mike Stump1eb44332009-09-09 15:08:12 +00002506
Douglas Gregor838db382010-02-11 01:19:42 +00002507 SuperStructDecl->completeDefinition();
Steve Naroff874e2322007-11-15 10:28:18 +00002508 }
2509 return Context->getTagDeclType(SuperStructDecl);
2510}
2511
Steve Naroffb29b4272008-04-14 22:03:09 +00002512QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002513 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002514 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002515 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002516 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002517 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002518
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002519 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002520 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002521 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002522 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002523 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002524 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002525 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002526 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002527
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002528 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002529 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002530 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2531 ConstantStringDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002532 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002533 FieldTypes[i], 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00002534 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002535 /*Mutable=*/true));
Douglas Gregor44b43212008-12-11 16:49:14 +00002536 }
2537
Douglas Gregor838db382010-02-11 01:19:42 +00002538 ConstantStringDecl->completeDefinition();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002539 }
2540 return Context->getTagDeclType(ConstantStringDecl);
2541}
2542
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002543Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2544 SourceLocation StartLoc,
2545 SourceLocation EndLoc) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002546 if (!SelGetUidFunctionDecl)
2547 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002548 if (!MsgSendFunctionDecl)
2549 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002550 if (!MsgSendSuperFunctionDecl)
2551 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002552 if (!MsgSendStretFunctionDecl)
2553 SynthMsgSendStretFunctionDecl();
2554 if (!MsgSendSuperStretFunctionDecl)
2555 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002556 if (!MsgSendFpretFunctionDecl)
2557 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002558 if (!GetClassFunctionDecl)
2559 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002560 if (!GetMetaClassFunctionDecl)
2561 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002562
Steve Naroff874e2322007-11-15 10:28:18 +00002563 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002564 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2565 // May need to use objc_msgSend_stret() as well.
2566 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002567 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2568 QualType resultType = mDecl->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00002569 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002570 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002571 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002572 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002573 }
Mike Stump1eb44332009-09-09 15:08:12 +00002574
Steve Naroff934f2762007-10-24 22:48:43 +00002575 // Synthesize a call to objc_msgSend().
2576 llvm::SmallVector<Expr*, 8> MsgExprs;
2577 IdentifierInfo *clsName = Exp->getClassName();
Mike Stump1eb44332009-09-09 15:08:12 +00002578
Steve Naroff934f2762007-10-24 22:48:43 +00002579 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2580 if (clsName) { // class message.
Steve Narofffc93d522008-07-24 19:44:33 +00002581 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2582 // the 'super' idiom within a class method.
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00002583 if (clsName->getName() == "super") {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002584 MsgSendFlavor = MsgSendSuperFunctionDecl;
2585 if (MsgSendStretFlavor)
2586 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2587 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002588
2589 ObjCInterfaceDecl *SuperDecl =
Steve Naroff54055232008-10-27 17:20:55 +00002590 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002591
2592 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00002593
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002594 // set the receiver to self, the first argument to all methods.
Steve Naroff621edce2009-04-29 16:37:50 +00002595 InitExprs.push_back(
John McCall9d125032010-01-15 18:39:57 +00002596 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2597 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002598 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroff621edce2009-04-29 16:37:50 +00002599 Context->getObjCIdType(),
John McCall9d125032010-01-15 18:39:57 +00002600 SourceLocation()))
2601 ); // set the 'receiver'.
Steve Naroff621edce2009-04-29 16:37:50 +00002602
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002603 llvm::SmallVector<Expr*, 8> ClsExprs;
2604 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002605 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbare013d682009-10-18 20:26:12 +00002606 SuperDecl->getIdentifier()->getNameStart(),
2607 SuperDecl->getIdentifier()->getLength(),
2608 false, argType, SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002609 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002610 &ClsExprs[0],
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002611 ClsExprs.size(),
2612 StartLoc,
2613 EndLoc);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002614 // To turn off a warning, type-cast to 'id'
Douglas Gregor49badde2008-10-27 19:41:14 +00002615 InitExprs.push_back( // set 'super class', using objc_getClass().
John McCall9d125032010-01-15 18:39:57 +00002616 NoTypeInfoCStyleCastExpr(Context,
2617 Context->getObjCIdType(),
2618 CastExpr::CK_Unknown, Cls));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002619 // struct objc_super
2620 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00002621 Expr *SuperRep;
Mike Stump1eb44332009-09-09 15:08:12 +00002622
Steve Naroff23f41272008-03-11 18:14:26 +00002623 if (LangOpts.Microsoft) {
2624 SynthSuperContructorFunctionDecl();
2625 // Simulate a contructor call...
Mike Stump1eb44332009-09-09 15:08:12 +00002626 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff23f41272008-03-11 18:14:26 +00002627 superType, SourceLocation());
Ted Kremenek668bf912009-02-09 20:51:47 +00002628 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002629 InitExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00002630 superType, SourceLocation());
Steve Naroff46a98a72008-12-23 20:11:22 +00002631 // The code for super is a little tricky to prevent collision with
2632 // the structure definition in the header. The rewriter has it's own
2633 // internal definition (__rw_objc_super) that is uses. This is why
2634 // we need the cast below. For example:
2635 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2636 //
Ted Kremenek8189cde2009-02-07 01:47:29 +00002637 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002638 Context->getPointerType(SuperRep->getType()),
Steve Naroff46a98a72008-12-23 20:11:22 +00002639 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00002640 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2641 Context->getPointerType(superType),
2642 CastExpr::CK_Unknown, SuperRep);
Mike Stump1eb44332009-09-09 15:08:12 +00002643 } else {
Steve Naroff23f41272008-03-11 18:14:26 +00002644 // (struct objc_super) { <exprs from above> }
Ted Kremenekba7bc552010-02-19 01:50:18 +00002645 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2646 &InitExprs[0], InitExprs.size(),
2647 SourceLocation());
John McCall42f56b52010-01-18 19:35:47 +00002648 TypeSourceInfo *superTInfo
2649 = Context->getTrivialTypeSourceInfo(superType);
John McCall1d7d8d62010-01-19 22:33:45 +00002650 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2651 superType, ILE, false);
Steve Naroff46a98a72008-12-23 20:11:22 +00002652 // struct objc_super *
Ted Kremenek8189cde2009-02-07 01:47:29 +00002653 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002654 Context->getPointerType(SuperRep->getType()),
Steve Naroff46a98a72008-12-23 20:11:22 +00002655 SourceLocation());
Steve Naroff23f41272008-03-11 18:14:26 +00002656 }
Steve Naroff46a98a72008-12-23 20:11:22 +00002657 MsgExprs.push_back(SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002658 } else {
2659 llvm::SmallVector<Expr*, 8> ClsExprs;
2660 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002661 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbare013d682009-10-18 20:26:12 +00002662 clsName->getNameStart(),
Chris Lattner2085fd62009-02-18 06:40:38 +00002663 clsName->getLength(),
2664 false, argType,
2665 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002666 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002667 &ClsExprs[0],
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002668 ClsExprs.size(),
2669 StartLoc, EndLoc);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002670 MsgExprs.push_back(Cls);
2671 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002672 } else { // instance message.
2673 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002674
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002675 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002676 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002677 if (MsgSendStretFlavor)
2678 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002679 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002680
Steve Naroff874e2322007-11-15 10:28:18 +00002681 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00002682
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002683 InitExprs.push_back(
John McCall9d125032010-01-15 18:39:57 +00002684 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2685 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002686 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002687 Context->getObjCIdType(),
John McCall9d125032010-01-15 18:39:57 +00002688 SourceLocation()))
2689 ); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002690
Steve Naroff874e2322007-11-15 10:28:18 +00002691 llvm::SmallVector<Expr*, 8> ClsExprs;
2692 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002693 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbare013d682009-10-18 20:26:12 +00002694 SuperDecl->getIdentifier()->getNameStart(),
2695 SuperDecl->getIdentifier()->getLength(),
2696 false, argType, SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002697 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002698 &ClsExprs[0],
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002699 ClsExprs.size(),
2700 StartLoc, EndLoc);
Fariborz Jahanian71274312007-12-05 17:29:46 +00002701 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002702 InitExprs.push_back(
Douglas Gregor49badde2008-10-27 19:41:14 +00002703 // set 'super class', using objc_getClass().
John McCall9d125032010-01-15 18:39:57 +00002704 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2705 CastExpr::CK_Unknown, Cls));
Steve Naroff874e2322007-11-15 10:28:18 +00002706 // struct objc_super
2707 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002708 Expr *SuperRep;
Mike Stump1eb44332009-09-09 15:08:12 +00002709
Steve Naroffc0a123c2008-03-11 17:37:02 +00002710 if (LangOpts.Microsoft) {
2711 SynthSuperContructorFunctionDecl();
2712 // Simulate a contructor call...
Mike Stump1eb44332009-09-09 15:08:12 +00002713 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroffc0a123c2008-03-11 17:37:02 +00002714 superType, SourceLocation());
Ted Kremenek668bf912009-02-09 20:51:47 +00002715 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002716 InitExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00002717 superType, SourceLocation());
Steve Naroff46a98a72008-12-23 20:11:22 +00002718 // The code for super is a little tricky to prevent collision with
2719 // the structure definition in the header. The rewriter has it's own
2720 // internal definition (__rw_objc_super) that is uses. This is why
2721 // we need the cast below. For example:
2722 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2723 //
Ted Kremenek8189cde2009-02-07 01:47:29 +00002724 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002725 Context->getPointerType(SuperRep->getType()),
Steve Naroff46a98a72008-12-23 20:11:22 +00002726 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00002727 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2728 Context->getPointerType(superType),
2729 CastExpr::CK_Unknown, SuperRep);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002730 } else {
2731 // (struct objc_super) { <exprs from above> }
Ted Kremenekba7bc552010-02-19 01:50:18 +00002732 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2733 &InitExprs[0], InitExprs.size(),
2734 SourceLocation());
John McCall42f56b52010-01-18 19:35:47 +00002735 TypeSourceInfo *superTInfo
2736 = Context->getTrivialTypeSourceInfo(superType);
John McCall1d7d8d62010-01-19 22:33:45 +00002737 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2738 superType, ILE, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002739 }
Steve Naroff46a98a72008-12-23 20:11:22 +00002740 MsgExprs.push_back(SuperRep);
Steve Naroff874e2322007-11-15 10:28:18 +00002741 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002742 // Remove all type-casts because it may contain objc-style types; e.g.
2743 // Foo<Proto> *.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002744 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002745 recExpr = CE->getSubExpr();
John McCall9d125032010-01-15 18:39:57 +00002746 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2747 CastExpr::CK_Unknown, recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +00002748 MsgExprs.push_back(recExpr);
2749 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002750 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002751 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002752 llvm::SmallVector<Expr*, 8> SelExprs;
2753 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002754 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002755 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00002756 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00002757 false, argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00002758 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002759 &SelExprs[0], SelExprs.size(),
2760 StartLoc,
2761 EndLoc);
Steve Naroff934f2762007-10-24 22:48:43 +00002762 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002763
Steve Naroff934f2762007-10-24 22:48:43 +00002764 // Now push any user supplied arguments.
2765 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002766 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002767 // Make all implicit casts explicit...ICE comes in handy:-)
2768 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2769 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002770 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002771 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002772 : ICE->getType();
John McCall9d125032010-01-15 18:39:57 +00002773 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CastExpr::CK_Unknown,
2774 userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002775 }
2776 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002777 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002778 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002779 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002780 userExpr = CE->getSubExpr();
John McCall9d125032010-01-15 18:39:57 +00002781 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2782 CastExpr::CK_Unknown, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002783 }
Mike Stump1eb44332009-09-09 15:08:12 +00002784 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002785 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00002786 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2787 // out the argument in the original expression (since we aren't deleting
2788 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2789 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00002790 }
Steve Naroffab972d32007-11-04 22:37:50 +00002791 // Generate the funky cast.
2792 CastExpr *cast;
2793 llvm::SmallVector<QualType, 8> ArgTypes;
2794 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00002795
Steve Naroffab972d32007-11-04 22:37:50 +00002796 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002797 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2798 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2799 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002800 ArgTypes.push_back(Context->getObjCIdType());
2801 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00002802 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002803 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00002804 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2805 E = OMD->param_end(); PI != E; ++PI) {
2806 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00002807 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00002808 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002809 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00002810 if (isTopLevelBlockPointerType(t)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002811 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroffa206b062008-10-29 14:49:46 +00002812 t = Context->getPointerType(BPT->getPointeeType());
2813 }
Steve Naroff352336b2007-11-05 14:36:37 +00002814 ArgTypes.push_back(t);
2815 }
Chris Lattner89951a82009-02-20 18:43:26 +00002816 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2817 ? Context->getObjCIdType() : OMD->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002818 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002819 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002820 }
2821 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002822 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002823
Steve Naroffab972d32007-11-04 22:37:50 +00002824 // Create a reference to the objc_msgSend() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002825 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002826 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002827
Mike Stump1eb44332009-09-09 15:08:12 +00002828 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00002829 // If we don't do this cast, we get the following bizarre warning/note:
2830 // xx.m:13: warning: function called through a non-compatible type
2831 // xx.m:13: note: if this code is reached, the program will abort
John McCall9d125032010-01-15 18:39:57 +00002832 cast = NoTypeInfoCStyleCastExpr(Context,
2833 Context->getPointerType(Context->VoidTy),
2834 CastExpr::CK_Unknown, DRE);
Mike Stump1eb44332009-09-09 15:08:12 +00002835
Steve Naroffab972d32007-11-04 22:37:50 +00002836 // Now do the "normal" pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00002837 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002838 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002839 // If we don't have a method decl, force a variadic cast.
Douglas Gregorce056bc2010-02-21 22:15:06 +00002840 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0,
2841 false, false, 0, 0, false,
2842 CC_Default);
Steve Naroffab972d32007-11-04 22:37:50 +00002843 castType = Context->getPointerType(castType);
John McCall9d125032010-01-15 18:39:57 +00002844 cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown,
2845 cast);
Steve Naroffab972d32007-11-04 22:37:50 +00002846
2847 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002848 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump1eb44332009-09-09 15:08:12 +00002849
John McCall183700f2009-09-21 23:43:11 +00002850 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00002851 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002852 MsgExprs.size(),
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002853 FT->getResultType(), EndLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002854 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002855 if (MsgSendStretFlavor) {
2856 // We have the method which returns a struct/union. Must also generate
2857 // call to objc_msgSend_stret and hang both varieties on a conditional
2858 // expression which dictate which one to envoke depending on size of
2859 // method's return type.
Mike Stump1eb44332009-09-09 15:08:12 +00002860
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002861 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002862 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002863 SourceLocation());
2864 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall9d125032010-01-15 18:39:57 +00002865 cast = NoTypeInfoCStyleCastExpr(Context,
2866 Context->getPointerType(Context->VoidTy),
2867 CastExpr::CK_Unknown, STDRE);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002868 // Now do the "normal" pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00002869 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002870 &ArgTypes[0], ArgTypes.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002871 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0,
2872 false, false, 0, 0, false,
2873 CC_Default);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002874 castType = Context->getPointerType(castType);
John McCall9d125032010-01-15 18:39:57 +00002875 cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown,
2876 cast);
Mike Stump1eb44332009-09-09 15:08:12 +00002877
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002878 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002879 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00002880
John McCall183700f2009-09-21 23:43:11 +00002881 FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00002882 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002883 MsgExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00002884 FT->getResultType(), SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002885
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002886 // Build sizeof(returnType)
Mike Stump1eb44332009-09-09 15:08:12 +00002887 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCalla93c9342009-12-07 02:54:59 +00002888 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl05189992008-11-11 17:56:53 +00002889 Context->getSizeType(),
2890 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002891 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2892 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2893 // For X86 it is more complicated and some kind of target specific routine
2894 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00002895 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00002896 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Mike Stump1eb44332009-09-09 15:08:12 +00002897 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002898 Context->IntTy,
2899 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002900 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
2901 BinaryOperator::LE,
2902 Context->IntTy,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002903 SourceLocation());
2904 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00002905 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00002906 new (Context) ConditionalOperator(lessThanExpr,
2907 SourceLocation(), CE,
2908 SourceLocation(), STCE, returnType);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002909 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002910 }
Mike Stump1eb44332009-09-09 15:08:12 +00002911 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002912 return ReplacingStmt;
2913}
2914
Steve Naroffb29b4272008-04-14 22:03:09 +00002915Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002916 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
2917 Exp->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00002918
Steve Naroff934f2762007-10-24 22:48:43 +00002919 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002920 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00002921
2922 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002923 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002924}
2925
Steve Naroff621edce2009-04-29 16:37:50 +00002926// typedef struct objc_object Protocol;
2927QualType RewriteObjC::getProtocolType() {
2928 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00002929 TypeSourceInfo *TInfo
2930 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00002931 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002932 SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00002933 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00002934 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00002935 }
2936 return Context->getTypeDeclType(ProtocolTypeDecl);
2937}
2938
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002939/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00002940/// a synthesized/forward data reference (to the protocol's metadata).
2941/// The forward references (and metadata) are generated in
2942/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00002943Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00002944 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
2945 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00002946 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregor0da76df2009-11-23 11:41:28 +00002947 ID, getProtocolType(), 0, VarDecl::Extern);
Steve Naroff621edce2009-04-29 16:37:50 +00002948 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
2949 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
2950 Context->getPointerType(DRE->getType()),
2951 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00002952 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
2953 CastExpr::CK_Unknown,
2954 DerefExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00002955 ReplaceStmt(Exp, castExpr);
2956 ProtocolExprDecls.insert(Exp->getProtocol());
Mike Stump1eb44332009-09-09 15:08:12 +00002957 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00002958 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002959
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002960}
2961
Mike Stump1eb44332009-09-09 15:08:12 +00002962bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00002963 const char *endBuf) {
2964 while (startBuf < endBuf) {
2965 if (*startBuf == '#') {
2966 // Skip whitespace.
2967 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2968 ;
2969 if (!strncmp(startBuf, "if", strlen("if")) ||
2970 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2971 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2972 !strncmp(startBuf, "define", strlen("define")) ||
2973 !strncmp(startBuf, "undef", strlen("undef")) ||
2974 !strncmp(startBuf, "else", strlen("else")) ||
2975 !strncmp(startBuf, "elif", strlen("elif")) ||
2976 !strncmp(startBuf, "endif", strlen("endif")) ||
2977 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2978 !strncmp(startBuf, "include", strlen("include")) ||
2979 !strncmp(startBuf, "import", strlen("import")) ||
2980 !strncmp(startBuf, "include_next", strlen("include_next")))
2981 return true;
2982 }
2983 startBuf++;
2984 }
2985 return false;
2986}
2987
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002988/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002989/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002990void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002991 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002992 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Mike Stump1eb44332009-09-09 15:08:12 +00002993 assert(CDecl->getNameAsCString() &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002994 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002995 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002996 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002997 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002998 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002999 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00003000 SourceLocation LocStart = CDecl->getLocStart();
3001 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00003002
Steve Narofffea763e82007-11-14 19:25:57 +00003003 const char *startBuf = SM->getCharacterData(LocStart);
3004 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00003005
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003006 // If no ivars and no root or if its root, directly or indirectly,
3007 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003008 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
3009 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00003010 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003011 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003012 return;
3013 }
Mike Stump1eb44332009-09-09 15:08:12 +00003014
3015 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003016 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003017 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003018 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00003019 if (LangOpts.Microsoft)
3020 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00003021
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003022 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00003023 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00003024 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003025 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00003026 // If the buffer contains preprocessor directives, we do more fine-grained
3027 // rewrites. This is intended to fix code that looks like (which occurs in
3028 // NSURL.h, for example):
3029 //
3030 // #ifdef XYZ
3031 // @interface Foo : NSObject
3032 // #else
3033 // @interface FooBar : NSObject
3034 // #endif
3035 // {
3036 // int i;
3037 // }
3038 // @end
3039 //
3040 // This clause is segregated to avoid breaking the common case.
3041 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003042 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffbaf58c32008-05-31 14:15:04 +00003043 CDecl->getClassLoc();
3044 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00003045 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003046
Chris Lattnercafeb352009-02-20 18:18:36 +00003047 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00003048 // advance to the end of the referenced protocols.
3049 while (endHeader < cursor && *endHeader != '>') endHeader++;
3050 endHeader++;
3051 }
3052 // rewrite the original header
Benjamin Kramerd999b372010-02-14 14:14:16 +00003053 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003054 } else {
3055 // rewrite the original header *without* disturbing the '{'
Benjamin Kramerd999b372010-02-14 14:14:16 +00003056 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003057 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003058 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00003059 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003060 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003061 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003062 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003063 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003064
Steve Narofffea763e82007-11-14 19:25:57 +00003065 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00003066 SourceLocation OnePastCurly =
3067 LocStart.getFileLocWithOffset(cursor-startBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003068 InsertText(OnePastCurly, Result);
Steve Narofffea763e82007-11-14 19:25:57 +00003069 }
3070 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00003071
Steve Narofffea763e82007-11-14 19:25:57 +00003072 // Now comment out any visibility specifiers.
3073 while (cursor < endBuf) {
3074 if (*cursor == '@') {
3075 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00003076 // Skip whitespace.
3077 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3078 /*scan*/;
3079
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003080 // FIXME: presence of @public, etc. inside comment results in
3081 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00003082 if (!strncmp(cursor, "public", strlen("public")) ||
3083 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00003084 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00003085 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramerd999b372010-02-14 14:14:16 +00003086 InsertText(atLoc, "// ");
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003087 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00003088 // FIXME: If there are cases where '<' is used in ivar declaration part
3089 // of user code, then scan the ivar list and use needToScanForQualifiers
3090 // for type checking.
3091 else if (*cursor == '<') {
3092 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003093 InsertText(atLoc, "/* ");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003094 cursor = strchr(cursor, '>');
3095 cursor++;
3096 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003097 InsertText(atLoc, " */");
Steve Naroffced80a82008-10-30 12:09:33 +00003098 } else if (*cursor == '^') { // rewrite block specifier.
3099 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003100 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003101 }
Steve Narofffea763e82007-11-14 19:25:57 +00003102 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003103 }
Steve Narofffea763e82007-11-14 19:25:57 +00003104 // Don't forget to add a ';'!!
Benjamin Kramerd999b372010-02-14 14:14:16 +00003105 InsertText(LocEnd.getFileLocWithOffset(1), ";");
Steve Narofffea763e82007-11-14 19:25:57 +00003106 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00003107 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00003108 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003109 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003110 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003111 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003112 Result += "_IVARS;\n};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00003113 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003114 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003115 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003116 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00003117 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003118}
3119
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003120// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003121/// class methods.
Douglas Gregor653f1b12009-04-23 01:02:12 +00003122template<typename MethodIterator>
3123void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3124 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00003125 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003126 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00003127 const char *ClassName,
3128 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003129 if (MethodBegin == MethodEnd) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003130
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003131 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003132 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003133 SEL _cmd;
3134 char *method_types;
3135 void *_imp;
3136 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003137 */
Chris Lattner158ecb92007-10-25 17:07:24 +00003138 Result += "\nstruct _objc_method {\n";
3139 Result += "\tSEL _cmd;\n";
3140 Result += "\tchar *method_types;\n";
3141 Result += "\tvoid *_imp;\n";
3142 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003143
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003144 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00003145 }
Mike Stump1eb44332009-09-09 15:08:12 +00003146
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003147 // Build _objc_method_list for class's methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003148
Steve Naroff946a6932008-03-11 00:12:29 +00003149 /* struct {
3150 struct _objc_method_list *next_method;
3151 int method_count;
3152 struct _objc_method method_list[];
3153 }
3154 */
Douglas Gregor653f1b12009-04-23 01:02:12 +00003155 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroff946a6932008-03-11 00:12:29 +00003156 Result += "\nstatic struct {\n";
3157 Result += "\tstruct _objc_method_list *next_method;\n";
3158 Result += "\tint method_count;\n";
3159 Result += "\tstruct _objc_method method_list[";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003160 Result += utostr(NumMethods);
Steve Naroff946a6932008-03-11 00:12:29 +00003161 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003162 Result += prefix;
3163 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3164 Result += "_METHODS_";
3165 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003166 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003167 Result += IsInstanceMethod ? "inst" : "cls";
3168 Result += "_meth\")))= ";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003169 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003170
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003171 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003172 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003173 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003174 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003175 Result += "\", \"";
3176 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003177 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003178 Result += MethodInternalNames[*MethodBegin];
3179 Result += "}\n";
3180 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3181 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003182 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003183 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003184 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003185 Result += "\", \"";
3186 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003187 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003188 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00003189 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003190 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003191 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003192}
3193
Steve Naroff621edce2009-04-29 16:37:50 +00003194/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00003195void RewriteObjC::
Steve Naroff621edce2009-04-29 16:37:50 +00003196RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix,
3197 const char *ClassName, std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003198 static bool objc_protocol_methods = false;
Steve Naroff621edce2009-04-29 16:37:50 +00003199
3200 // Output struct protocol_methods holder of method selector and type.
3201 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3202 /* struct protocol_methods {
3203 SEL _cmd;
3204 char *method_types;
3205 }
3206 */
3207 Result += "\nstruct _protocol_methods {\n";
3208 Result += "\tstruct objc_selector *_cmd;\n";
3209 Result += "\tchar *method_types;\n";
3210 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003211
Steve Naroff621edce2009-04-29 16:37:50 +00003212 objc_protocol_methods = true;
3213 }
3214 // Do not synthesize the protocol more than once.
3215 if (ObjCSynthesizedProtocols.count(PDecl))
3216 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003217
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003218 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3219 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3220 PDecl->instmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003221 /* struct _objc_protocol_method_list {
3222 int protocol_method_count;
3223 struct protocol_methods protocols[];
3224 }
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003225 */
Steve Naroff621edce2009-04-29 16:37:50 +00003226 Result += "\nstatic struct {\n";
3227 Result += "\tint protocol_method_count;\n";
3228 Result += "\tstruct _protocol_methods protocol_methods[";
3229 Result += utostr(NumMethods);
3230 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3231 Result += PDecl->getNameAsString();
3232 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3233 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003234
Steve Naroff621edce2009-04-29 16:37:50 +00003235 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003236 for (ObjCProtocolDecl::instmeth_iterator
3237 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003238 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003239 if (I == PDecl->instmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003240 Result += "\t ,{{(struct objc_selector *)\"";
3241 else
3242 Result += "\t ,{(struct objc_selector *)\"";
3243 Result += (*I)->getSelector().getAsString().c_str();
3244 std::string MethodTypeString;
3245 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3246 Result += "\", \"";
3247 Result += MethodTypeString;
3248 Result += "\"}\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003249 }
Steve Naroff621edce2009-04-29 16:37:50 +00003250 Result += "\t }\n};\n";
3251 }
Mike Stump1eb44332009-09-09 15:08:12 +00003252
Steve Naroff621edce2009-04-29 16:37:50 +00003253 // Output class methods declared in this protocol.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003254 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3255 PDecl->classmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003256 if (NumMethods > 0) {
3257 /* struct _objc_protocol_method_list {
3258 int protocol_method_count;
3259 struct protocol_methods protocols[];
3260 }
3261 */
3262 Result += "\nstatic struct {\n";
3263 Result += "\tint protocol_method_count;\n";
3264 Result += "\tstruct _protocol_methods protocol_methods[";
3265 Result += utostr(NumMethods);
3266 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3267 Result += PDecl->getNameAsString();
3268 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3269 "{\n\t";
3270 Result += utostr(NumMethods);
3271 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003272
Steve Naroff621edce2009-04-29 16:37:50 +00003273 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003274 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003275 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003276 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003277 if (I == PDecl->classmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003278 Result += "\t ,{{(struct objc_selector *)\"";
3279 else
3280 Result += "\t ,{(struct objc_selector *)\"";
3281 Result += (*I)->getSelector().getAsString().c_str();
3282 std::string MethodTypeString;
3283 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3284 Result += "\", \"";
3285 Result += MethodTypeString;
3286 Result += "\"}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003287 }
Steve Naroff621edce2009-04-29 16:37:50 +00003288 Result += "\t }\n};\n";
3289 }
3290
3291 // Output:
3292 /* struct _objc_protocol {
3293 // Objective-C 1.0 extensions
3294 struct _objc_protocol_extension *isa;
3295 char *protocol_name;
3296 struct _objc_protocol **protocol_list;
3297 struct _objc_protocol_method_list *instance_methods;
3298 struct _objc_protocol_method_list *class_methods;
Mike Stump1eb44332009-09-09 15:08:12 +00003299 };
Steve Naroff621edce2009-04-29 16:37:50 +00003300 */
3301 static bool objc_protocol = false;
3302 if (!objc_protocol) {
3303 Result += "\nstruct _objc_protocol {\n";
3304 Result += "\tstruct _objc_protocol_extension *isa;\n";
3305 Result += "\tchar *protocol_name;\n";
3306 Result += "\tstruct _objc_protocol **protocol_list;\n";
3307 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3308 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003309 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003310
Steve Naroff621edce2009-04-29 16:37:50 +00003311 objc_protocol = true;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003312 }
Mike Stump1eb44332009-09-09 15:08:12 +00003313
Steve Naroff621edce2009-04-29 16:37:50 +00003314 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3315 Result += PDecl->getNameAsString();
3316 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3317 "{\n\t0, \"";
3318 Result += PDecl->getNameAsString();
3319 Result += "\", 0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003320 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003321 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3322 Result += PDecl->getNameAsString();
3323 Result += ", ";
3324 }
3325 else
3326 Result += "0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003327 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003328 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3329 Result += PDecl->getNameAsString();
3330 Result += "\n";
3331 }
3332 else
3333 Result += "0\n";
3334 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003335
Steve Naroff621edce2009-04-29 16:37:50 +00003336 // Mark this protocol as having been generated.
3337 if (!ObjCSynthesizedProtocols.insert(PDecl))
3338 assert(false && "protocol already synthesized");
3339
3340}
3341
3342void RewriteObjC::
3343RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3344 const char *prefix, const char *ClassName,
3345 std::string &Result) {
3346 if (Protocols.empty()) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003347
Steve Naroff621edce2009-04-29 16:37:50 +00003348 for (unsigned i = 0; i != Protocols.size(); i++)
3349 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3350
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003351 // Output the top lovel protocol meta-data for the class.
3352 /* struct _objc_protocol_list {
3353 struct _objc_protocol_list *next;
3354 int protocol_count;
3355 struct _objc_protocol *class_protocols[];
3356 }
3357 */
3358 Result += "\nstatic struct {\n";
3359 Result += "\tstruct _objc_protocol_list *next;\n";
3360 Result += "\tint protocol_count;\n";
3361 Result += "\tstruct _objc_protocol *class_protocols[";
3362 Result += utostr(Protocols.size());
3363 Result += "];\n} _OBJC_";
3364 Result += prefix;
3365 Result += "_PROTOCOLS_";
3366 Result += ClassName;
3367 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3368 "{\n\t0, ";
3369 Result += utostr(Protocols.size());
3370 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003371
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003372 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003373 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003374 Result += " \n";
Mike Stump1eb44332009-09-09 15:08:12 +00003375
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003376 for (unsigned i = 1; i != Protocols.size(); i++) {
3377 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003378 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003379 Result += "\n";
3380 }
3381 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003382}
3383
Steve Naroff621edce2009-04-29 16:37:50 +00003384
Mike Stump1eb44332009-09-09 15:08:12 +00003385/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003386/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003387void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003388 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003389 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003390 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003391 ObjCCategoryDecl *CDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00003392 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003393 CDecl = CDecl->getNextClassCategory())
3394 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3395 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003396
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003397 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003398 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003399 FullCategoryName += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003400
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003401 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003402 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003403 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003404
3405 // If any of our property implementations have associated getters or
3406 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003407 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3408 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003409 Prop != PropEnd; ++Prop) {
3410 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3411 continue;
3412 if (!(*Prop)->getPropertyIvarDecl())
3413 continue;
3414 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3415 if (!PD)
3416 continue;
3417 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3418 InstanceMethods.push_back(Getter);
3419 if (PD->isReadOnly())
3420 continue;
3421 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3422 InstanceMethods.push_back(Setter);
3423 }
3424 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003425 true, "CATEGORY_", FullCategoryName.c_str(),
3426 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003427
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003428 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003429 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003430 false, "CATEGORY_", FullCategoryName.c_str(),
3431 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003432
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003433 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003434 // Null CDecl is case of a category implementation with no category interface
3435 if (CDecl)
Steve Naroff621edce2009-04-29 16:37:50 +00003436 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3437 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003438 /* struct _objc_category {
3439 char *category_name;
3440 char *class_name;
3441 struct _objc_method_list *instance_methods;
3442 struct _objc_method_list *class_methods;
3443 struct _objc_protocol_list *protocols;
3444 // Objective-C 1.0 extensions
3445 uint32_t size; // sizeof (struct _objc_category)
Mike Stump1eb44332009-09-09 15:08:12 +00003446 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003447 // @property decl.
Mike Stump1eb44332009-09-09 15:08:12 +00003448 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003449 */
Mike Stump1eb44332009-09-09 15:08:12 +00003450
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003451 static bool objc_category = false;
3452 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003453 Result += "\nstruct _objc_category {\n";
3454 Result += "\tchar *category_name;\n";
3455 Result += "\tchar *class_name;\n";
3456 Result += "\tstruct _objc_method_list *instance_methods;\n";
3457 Result += "\tstruct _objc_method_list *class_methods;\n";
3458 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003459 Result += "\tunsigned int size;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003460 Result += "\tstruct _objc_property_list *instance_properties;\n";
3461 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003462 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003463 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003464 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3465 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003466 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003467 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003468 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003469 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003470 Result += "\"\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003471
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003472 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003473 Result += "\t, (struct _objc_method_list *)"
3474 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3475 Result += FullCategoryName;
3476 Result += "\n";
3477 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003478 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003479 Result += "\t, 0\n";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003480 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003481 Result += "\t, (struct _objc_method_list *)"
3482 "&_OBJC_CATEGORY_CLASS_METHODS_";
3483 Result += FullCategoryName;
3484 Result += "\n";
3485 }
3486 else
3487 Result += "\t, 0\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003488
Chris Lattnercafeb352009-02-20 18:18:36 +00003489 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003490 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003491 Result += FullCategoryName;
3492 Result += "\n";
3493 }
3494 else
3495 Result += "\t, 0\n";
3496 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003497}
3498
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003499/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3500/// ivar offset.
Mike Stump1eb44332009-09-09 15:08:12 +00003501void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
3502 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003503 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003504 if (ivar->isBitField()) {
3505 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3506 // place all bitfields at offset 0.
3507 Result += "0";
3508 } else {
3509 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003510 Result += IDecl->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003511 if (LangOpts.Microsoft)
3512 Result += "_IMPL";
3513 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003514 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003515 Result += ")";
3516 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003517}
3518
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003519//===----------------------------------------------------------------------===//
3520// Meta Data Emission
3521//===----------------------------------------------------------------------===//
3522
Steve Naroffb29b4272008-04-14 22:03:09 +00003523void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003524 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003525 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00003526
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003527 // Explictly declared @interface's are already synthesized.
Steve Naroff33feeb02009-04-20 20:09:33 +00003528 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003529 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003530 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003531 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003532 }
Mike Stump1eb44332009-09-09 15:08:12 +00003533
Chris Lattnerbe6df082007-12-12 07:56:42 +00003534 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003535 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump1eb44332009-09-09 15:08:12 +00003536 ? IDecl->ivar_size()
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003537 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003538 if (NumIvars > 0) {
3539 static bool objc_ivar = false;
3540 if (!objc_ivar) {
3541 /* struct _objc_ivar {
3542 char *ivar_name;
3543 char *ivar_type;
3544 int ivar_offset;
Mike Stump1eb44332009-09-09 15:08:12 +00003545 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003546 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003547 Result += "\nstruct _objc_ivar {\n";
3548 Result += "\tchar *ivar_name;\n";
3549 Result += "\tchar *ivar_type;\n";
3550 Result += "\tint ivar_offset;\n";
3551 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003552
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003553 objc_ivar = true;
3554 }
3555
Steve Naroff946a6932008-03-11 00:12:29 +00003556 /* struct {
3557 int ivar_count;
3558 struct _objc_ivar ivar_list[nIvars];
Mike Stump1eb44332009-09-09 15:08:12 +00003559 };
Steve Naroff946a6932008-03-11 00:12:29 +00003560 */
Mike Stump1eb44332009-09-09 15:08:12 +00003561 Result += "\nstatic struct {\n";
Steve Naroff946a6932008-03-11 00:12:29 +00003562 Result += "\tint ivar_count;\n";
3563 Result += "\tstruct _objc_ivar ivar_list[";
3564 Result += utostr(NumIvars);
3565 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003566 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003567 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003568 "{\n\t";
3569 Result += utostr(NumIvars);
3570 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003571
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003572 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003573 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003574 if (!IDecl->ivar_empty()) {
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003575 for (ObjCInterfaceDecl::ivar_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003576 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003577 IV != IVEnd; ++IV)
3578 IVars.push_back(*IV);
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003579 IVI = IDecl->ivar_begin();
3580 IVE = IDecl->ivar_end();
Chris Lattnerbe6df082007-12-12 07:56:42 +00003581 } else {
3582 IVI = CDecl->ivar_begin();
3583 IVE = CDecl->ivar_end();
3584 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003585 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003586 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003587 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003588 std::string TmpString, StrEncoding;
3589 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3590 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003591 Result += StrEncoding;
3592 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003593 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003594 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003595 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003596 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003597 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003598 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003599 std::string TmpString, StrEncoding;
3600 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3601 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003602 Result += StrEncoding;
3603 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003604 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003605 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003606 }
Mike Stump1eb44332009-09-09 15:08:12 +00003607
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003608 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003609 }
Mike Stump1eb44332009-09-09 15:08:12 +00003610
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003611 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003612 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003613 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003614
3615 // If any of our property implementations have associated getters or
3616 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003617 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3618 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003619 Prop != PropEnd; ++Prop) {
3620 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3621 continue;
3622 if (!(*Prop)->getPropertyIvarDecl())
3623 continue;
3624 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3625 if (!PD)
3626 continue;
3627 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3628 InstanceMethods.push_back(Getter);
3629 if (PD->isReadOnly())
3630 continue;
3631 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3632 InstanceMethods.push_back(Setter);
3633 }
3634 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003635 true, "", IDecl->getNameAsCString(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003636
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003637 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003638 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003639 false, "", IDecl->getNameAsCString(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003640
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003641 // Protocols referenced in class declaration?
Steve Naroff621edce2009-04-29 16:37:50 +00003642 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3643 "CLASS", CDecl->getNameAsCString(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003644
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003645 // Declaration of class/meta-class metadata
3646 /* struct _objc_class {
3647 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003648 const char *super_class_name;
3649 char *name;
3650 long version;
3651 long info;
3652 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003653 struct _objc_ivar_list *ivars;
3654 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003655 struct objc_cache *cache;
3656 struct objc_protocol_list *protocols;
3657 const char *ivar_layout;
3658 struct _objc_class_ext *ext;
Mike Stump1eb44332009-09-09 15:08:12 +00003659 };
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003660 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003661 static bool objc_class = false;
3662 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003663 Result += "\nstruct _objc_class {\n";
3664 Result += "\tstruct _objc_class *isa;\n";
3665 Result += "\tconst char *super_class_name;\n";
3666 Result += "\tchar *name;\n";
3667 Result += "\tlong version;\n";
3668 Result += "\tlong info;\n";
3669 Result += "\tlong instance_size;\n";
3670 Result += "\tstruct _objc_ivar_list *ivars;\n";
3671 Result += "\tstruct _objc_method_list *methods;\n";
3672 Result += "\tstruct objc_cache *cache;\n";
3673 Result += "\tstruct _objc_protocol_list *protocols;\n";
3674 Result += "\tconst char *ivar_layout;\n";
3675 Result += "\tstruct _objc_class_ext *ext;\n";
3676 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003677 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003678 }
Mike Stump1eb44332009-09-09 15:08:12 +00003679
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003680 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003681 ObjCInterfaceDecl *RootClass = 0;
3682 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003683 while (SuperClass) {
3684 RootClass = SuperClass;
3685 SuperClass = SuperClass->getSuperClass();
3686 }
3687 SuperClass = CDecl->getSuperClass();
Mike Stump1eb44332009-09-09 15:08:12 +00003688
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003689 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003690 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003691 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003692 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003693 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003694 Result += "\"";
3695
3696 if (SuperClass) {
3697 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003698 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003699 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003700 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003701 Result += "\"";
3702 }
3703 else {
3704 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003705 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003706 Result += "\"";
3707 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003708 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003709 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003710 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003711 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff23f41272008-03-11 18:14:26 +00003712 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003713 Result += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003714 Result += "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003715 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003716 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003717 Result += ", 0\n";
Chris Lattnercafeb352009-02-20 18:18:36 +00003718 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003719 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003720 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003721 Result += ",0,0\n";
3722 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003723 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003724 Result += "\t,0,0,0,0\n";
3725 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003726
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003727 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003728 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003729 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003730 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003731 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003732 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003733 if (SuperClass) {
3734 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003735 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003736 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003737 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003738 Result += "\"";
3739 }
3740 else {
3741 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003742 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003743 Result += "\"";
3744 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003745 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003746 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003747 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003748 Result += ",0";
3749 else {
3750 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003751 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003752 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003753 if (LangOpts.Microsoft)
3754 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003755 Result += ")";
3756 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003757 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003758 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003759 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003760 Result += "\n\t";
3761 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003762 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003763 Result += ",0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003764 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroff946a6932008-03-11 00:12:29 +00003765 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003766 Result += CDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003767 Result += ", 0\n\t";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003768 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003769 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003770 Result += ",0,0";
Chris Lattnercafeb352009-02-20 18:18:36 +00003771 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003772 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003773 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003774 Result += ", 0,0\n";
3775 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003776 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003777 Result += ",0,0,0\n";
3778 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003779}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003780
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003781/// RewriteImplementations - This routine rewrites all method implementations
3782/// and emits meta-data.
3783
Steve Narofface66252008-11-13 20:07:04 +00003784void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003785 int ClsDefCount = ClassImplementation.size();
3786 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00003787
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003788 // Rewrite implemented methods
3789 for (int i = 0; i < ClsDefCount; i++)
3790 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00003791
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003792 for (int i = 0; i < CatDefCount; i++)
3793 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003794}
Mike Stump1eb44332009-09-09 15:08:12 +00003795
Steve Narofface66252008-11-13 20:07:04 +00003796void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3797 int ClsDefCount = ClassImplementation.size();
3798 int CatDefCount = CategoryImplementation.size();
3799
Steve Naroff5df5b762008-05-07 21:23:49 +00003800 // This is needed for determining instance variable offsets.
Fariborz Jahanianc98cbb42010-01-07 18:31:42 +00003801 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003802 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003803 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003804 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003805
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003806 // For each implemented category, write out all its meta data.
3807 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003808 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroff621edce2009-04-29 16:37:50 +00003809
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003810 // Write objc_symtab metadata
3811 /*
3812 struct _objc_symtab
3813 {
3814 long sel_ref_cnt;
3815 SEL *refs;
3816 short cls_def_cnt;
3817 short cat_def_cnt;
3818 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump1eb44332009-09-09 15:08:12 +00003819 };
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003820 */
Mike Stump1eb44332009-09-09 15:08:12 +00003821
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003822 Result += "\nstruct _objc_symtab {\n";
3823 Result += "\tlong sel_ref_cnt;\n";
3824 Result += "\tSEL *refs;\n";
3825 Result += "\tshort cls_def_cnt;\n";
3826 Result += "\tshort cat_def_cnt;\n";
3827 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3828 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003829
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003830 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003831 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003832 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003833 + ", " + utostr(CatDefCount) + "\n";
3834 for (int i = 0; i < ClsDefCount; i++) {
3835 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003836 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003837 Result += "\n";
3838 }
Mike Stump1eb44332009-09-09 15:08:12 +00003839
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003840 for (int i = 0; i < CatDefCount; i++) {
3841 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003842 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003843 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003844 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003845 Result += "\n";
3846 }
Mike Stump1eb44332009-09-09 15:08:12 +00003847
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003848 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003849
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003850 // Write objc_module metadata
Mike Stump1eb44332009-09-09 15:08:12 +00003851
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003852 /*
3853 struct _objc_module {
3854 long version;
3855 long size;
3856 const char *name;
3857 struct _objc_symtab *symtab;
3858 }
3859 */
Mike Stump1eb44332009-09-09 15:08:12 +00003860
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003861 Result += "\nstruct _objc_module {\n";
3862 Result += "\tlong version;\n";
3863 Result += "\tlong size;\n";
3864 Result += "\tconst char *name;\n";
3865 Result += "\tstruct _objc_symtab *symtab;\n";
3866 Result += "};\n\n";
3867 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003868 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003869 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003870 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003871 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003872
3873 if (LangOpts.Microsoft) {
Steve Naroff621edce2009-04-29 16:37:50 +00003874 if (ProtocolExprDecls.size()) {
3875 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
3876 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003877 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00003878 E = ProtocolExprDecls.end(); I != E; ++I) {
3879 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
3880 Result += (*I)->getNameAsString();
3881 Result += " = &_OBJC_PROTOCOL_";
3882 Result += (*I)->getNameAsString();
3883 Result += ";\n";
3884 }
3885 Result += "#pragma data_seg(pop)\n\n";
3886 }
Steve Naroff4f943c22008-03-10 20:43:59 +00003887 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003888 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003889 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3890 Result += "&_OBJC_MODULES;\n";
3891 Result += "#pragma data_seg(pop)\n\n";
3892 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003893}
Chris Lattner311ff022007-10-16 22:36:42 +00003894
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003895void RewriteObjC::RewriteByRefString(std::string &ResultStr,
3896 const std::string &Name,
3897 ValueDecl *VD) {
3898 assert(BlockByRefDeclNo.count(VD) &&
3899 "RewriteByRefString: ByRef decl missing");
3900 ResultStr += "struct __Block_byref_" + Name +
3901 "_" + utostr(BlockByRefDeclNo[VD]) ;
3902}
3903
Steve Naroff54055232008-10-27 17:20:55 +00003904std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3905 const char *funcName,
3906 std::string Tag) {
3907 const FunctionType *AFT = CE->getFunctionType();
3908 QualType RT = AFT->getResultType();
3909 std::string StructRef = "struct " + Tag;
3910 std::string S = "static " + RT.getAsString() + " __" +
3911 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003912
Steve Naroff54055232008-10-27 17:20:55 +00003913 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00003914
Douglas Gregor72564e72009-02-26 23:50:07 +00003915 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003916 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00003917 // block (to reference imported block decl refs).
3918 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00003919 } else if (BD->param_empty()) {
3920 S += "(" + StructRef + " *__cself)";
3921 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003922 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00003923 assert(FT && "SynthesizeBlockFunc: No function proto");
3924 S += '(';
3925 // first add the implicit argument.
3926 S += StructRef + " *__cself, ";
3927 std::string ParamStr;
3928 for (BlockDecl::param_iterator AI = BD->param_begin(),
3929 E = BD->param_end(); AI != E; ++AI) {
3930 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003931 ParamStr = (*AI)->getNameAsString();
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00003932 (*AI)->getType().getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00003933 S += ParamStr;
3934 }
3935 if (FT->isVariadic()) {
3936 if (!BD->param_empty()) S += ", ";
3937 S += "...";
3938 }
3939 S += ')';
3940 }
3941 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003942
Steve Naroff54055232008-10-27 17:20:55 +00003943 // Create local declarations to avoid rewriting all closure decl ref exprs.
3944 // First, emit a declaration for all "by ref" decls.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003945 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003946 E = BlockByRefDecls.end(); I != E; ++I) {
3947 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003948 std::string Name = (*I)->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003949 std::string TypeString;
3950 RewriteByRefString(TypeString, Name, (*I));
3951 TypeString += " *";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003952 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003953 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003954 }
Steve Naroff54055232008-10-27 17:20:55 +00003955 // Next, emit a declaration for all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003956 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003957 E = BlockByCopyDecls.end(); I != E; ++I) {
3958 S += " ";
Steve Naroff54055232008-10-27 17:20:55 +00003959 // Handle nested closure invocation. For example:
3960 //
3961 // void (^myImportedClosure)(void);
3962 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003963 //
Steve Naroff54055232008-10-27 17:20:55 +00003964 // void (^anotherClosure)(void);
3965 // anotherClosure = ^(void) {
3966 // myImportedClosure(); // import and invoke the closure
3967 // };
3968 //
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00003969 if (isTopLevelBlockPointerType((*I)->getType())) {
3970 RewriteBlockPointerTypeVariable(S, (*I));
3971 S += " = (";
3972 RewriteBlockPointerType(S, (*I)->getType());
3973 S += ")";
3974 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3975 }
3976 else {
Fariborz Jahanian210c2482010-02-16 17:26:03 +00003977 std::string Name = (*I)->getNameAsString();
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00003978 (*I)->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00003979 S += Name + " = __cself->" +
3980 (*I)->getNameAsString() + "; // bound by copy\n";
3981 }
Steve Naroff54055232008-10-27 17:20:55 +00003982 }
3983 std::string RewrittenStr = RewrittenBlockExprs[CE];
3984 const char *cstr = RewrittenStr.c_str();
3985 while (*cstr++ != '{') ;
3986 S += cstr;
3987 S += "\n";
3988 return S;
3989}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003990
Steve Naroff54055232008-10-27 17:20:55 +00003991std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3992 const char *funcName,
3993 std::string Tag) {
3994 std::string StructRef = "struct " + Tag;
3995 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00003996
Steve Naroff54055232008-10-27 17:20:55 +00003997 S += funcName;
3998 S += "_block_copy_" + utostr(i);
3999 S += "(" + StructRef;
4000 S += "*dst, " + StructRef;
4001 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004002 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004003 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00004004 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004005 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00004006 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004007 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004008 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004009 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004010 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004011 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004012 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004013 S += "}\n";
4014
Steve Naroff54055232008-10-27 17:20:55 +00004015 S += "\nstatic void __";
4016 S += funcName;
4017 S += "_block_dispose_" + utostr(i);
4018 S += "(" + StructRef;
4019 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004020 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004021 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00004022 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004023 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004024 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004025 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004026 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004027 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004028 }
Mike Stump1eb44332009-09-09 15:08:12 +00004029 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00004030 return S;
4031}
4032
Steve Naroff01aec112009-12-06 21:14:13 +00004033std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4034 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00004035 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00004036 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00004037
Steve Naroff54055232008-10-27 17:20:55 +00004038 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004039 S += " struct " + Desc;
4040 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004041
Steve Naroff01aec112009-12-06 21:14:13 +00004042 Constructor += "(void *fp, "; // Invoke function pointer.
4043 Constructor += "struct " + Desc; // Descriptor pointer.
4044 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00004045
Steve Naroff54055232008-10-27 17:20:55 +00004046 if (BlockDeclRefs.size()) {
4047 // Output all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004048 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004049 E = BlockByCopyDecls.end(); I != E; ++I) {
4050 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004051 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004052 std::string ArgName = "_" + FieldName;
4053 // Handle nested closure invocation. For example:
4054 //
4055 // void (^myImportedBlock)(void);
4056 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004057 //
Steve Naroff54055232008-10-27 17:20:55 +00004058 // void (^anotherBlock)(void);
4059 // anotherBlock = ^(void) {
4060 // myImportedBlock(); // import and invoke the closure
4061 // };
4062 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004063 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00004064 S += "struct __block_impl *";
4065 Constructor += ", void *" + ArgName;
4066 } else {
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00004067 (*I)->getType().getAsStringInternal(FieldName, Context->PrintingPolicy);
4068 (*I)->getType().getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00004069 Constructor += ", " + ArgName;
4070 }
4071 S += FieldName + ";\n";
4072 }
4073 // Output all "by ref" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004074 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004075 E = BlockByRefDecls.end(); I != E; ++I) {
4076 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004077 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004078 std::string ArgName = "_" + FieldName;
4079 // Handle nested closure invocation. For example:
4080 //
4081 // void (^myImportedBlock)(void);
4082 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004083 //
Steve Naroff54055232008-10-27 17:20:55 +00004084 // void (^anotherBlock)(void);
4085 // anotherBlock = ^(void) {
4086 // myImportedBlock(); // import and invoke the closure
4087 // };
4088 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004089 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00004090 S += "struct __block_impl *";
4091 Constructor += ", void *" + ArgName;
4092 } else {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004093 std::string TypeString;
4094 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004095 TypeString += " *";
4096 FieldName = TypeString + FieldName;
4097 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00004098 Constructor += ", " + ArgName;
4099 }
4100 S += FieldName + "; // by ref\n";
4101 }
4102 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00004103 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004104 if (GlobalVarDecl)
4105 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4106 else
4107 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004108 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004109
Steve Naroff01aec112009-12-06 21:14:13 +00004110 Constructor += " Desc = desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004111
Steve Naroff54055232008-10-27 17:20:55 +00004112 // Initialize all "by copy" arguments.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004113 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004114 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004115 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004116 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004117 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00004118 Constructor += Name + " = (struct __block_impl *)_";
4119 else
4120 Constructor += Name + " = _";
4121 Constructor += Name + ";\n";
4122 }
4123 // Initialize all "by ref" arguments.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004124 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004125 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004126 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004127 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004128 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00004129 Constructor += Name + " = (struct __block_impl *)_";
4130 else
4131 Constructor += Name + " = _";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004132 Constructor += Name + "->__forwarding;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004133 }
4134 } else {
4135 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00004136 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004137 if (GlobalVarDecl)
4138 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4139 else
4140 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004141 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4142 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004143 }
4144 Constructor += " ";
4145 Constructor += "}\n";
4146 S += Constructor;
4147 S += "};\n";
4148 return S;
4149}
4150
Steve Naroff01aec112009-12-06 21:14:13 +00004151std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4152 std::string ImplTag, int i,
4153 const char *FunName,
4154 unsigned hasCopy) {
4155 std::string S = "\nstatic struct " + DescTag;
4156
4157 S += " {\n unsigned long reserved;\n";
4158 S += " unsigned long Block_size;\n";
4159 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004160 S += " void (*copy)(struct ";
4161 S += ImplTag; S += "*, struct ";
4162 S += ImplTag; S += "*);\n";
4163
4164 S += " void (*dispose)(struct ";
4165 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004166 }
4167 S += "} ";
4168
4169 S += DescTag + "_DATA = { 0, sizeof(struct ";
4170 S += ImplTag + ")";
4171 if (hasCopy) {
4172 S += ", __" + std::string(FunName) + "_block_copy_" + utostr(i);
4173 S += ", __" + std::string(FunName) + "_block_dispose_" + utostr(i);
4174 }
4175 S += "};\n";
4176 return S;
4177}
4178
Steve Naroff54055232008-10-27 17:20:55 +00004179void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004180 const char *FunName) {
4181 // Insert declaration for the function in which block literal is used.
Fariborz Jahanianbf070122010-01-15 18:14:52 +00004182 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004183 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Steve Naroff54055232008-10-27 17:20:55 +00004184 // Insert closures that were part of the function.
4185 for (unsigned i = 0; i < Blocks.size(); i++) {
4186
4187 CollectBlockDeclRefInfo(Blocks[i]);
4188
Steve Naroff01aec112009-12-06 21:14:13 +00004189 std::string ImplTag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
4190 std::string DescTag = "__" + std::string(FunName) + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00004191
Steve Naroff01aec112009-12-06 21:14:13 +00004192 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00004193
Benjamin Kramerd999b372010-02-14 14:14:16 +00004194 InsertText(FunLocStart, CI);
Steve Naroff54055232008-10-27 17:20:55 +00004195
Steve Naroff01aec112009-12-06 21:14:13 +00004196 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00004197
Benjamin Kramerd999b372010-02-14 14:14:16 +00004198 InsertText(FunLocStart, CF);
Steve Naroff54055232008-10-27 17:20:55 +00004199
4200 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00004201 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004202 InsertText(FunLocStart, HF);
Steve Naroff54055232008-10-27 17:20:55 +00004203 }
Steve Naroff01aec112009-12-06 21:14:13 +00004204 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4205 ImportedBlockDecls.size() > 0);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004206 InsertText(FunLocStart, BD);
Mike Stump1eb44332009-09-09 15:08:12 +00004207
Steve Naroff54055232008-10-27 17:20:55 +00004208 BlockDeclRefs.clear();
4209 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004210 BlockByRefDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004211 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004212 BlockByCopyDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004213 BlockCallExprs.clear();
4214 ImportedBlockDecls.clear();
4215 }
4216 Blocks.clear();
4217 RewrittenBlockExprs.clear();
4218}
4219
4220void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4221 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner8ec03f52008-11-24 03:54:41 +00004222 const char *FuncName = FD->getNameAsCString();
Mike Stump1eb44332009-09-09 15:08:12 +00004223
Steve Naroff54055232008-10-27 17:20:55 +00004224 SynthesizeBlockLiterals(FunLocStart, FuncName);
4225}
4226
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004227static void BuildUniqueMethodName(std::string &Name,
4228 ObjCMethodDecl *MD) {
4229 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4230 Name = IFace->getNameAsCString();
4231 Name += "__" + MD->getSelector().getAsString();
4232 // Convert colons to underscores.
4233 std::string::size_type loc = 0;
4234 while ((loc = Name.find(":", loc)) != std::string::npos)
4235 Name.replace(loc, 1, "_");
4236}
4237
Steve Naroff54055232008-10-27 17:20:55 +00004238void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00004239 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4240 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanian0e1c99a2010-01-29 01:55:49 +00004241 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004242 std::string FuncName;
4243 BuildUniqueMethodName(FuncName, MD);
Steve Naroff54055232008-10-27 17:20:55 +00004244 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
4245}
4246
4247void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4248 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4249 CI != E; ++CI)
4250 if (*CI) {
4251 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4252 GetBlockDeclRefExprs(CBE->getBody());
4253 else
4254 GetBlockDeclRefExprs(*CI);
4255 }
4256 // Handle specific things.
4257 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
4258 // FIXME: Handle enums.
4259 if (!isa<FunctionDecl>(CDRE->getDecl()))
4260 BlockDeclRefs.push_back(CDRE);
4261 return;
4262}
4263
4264void RewriteObjC::GetBlockCallExprs(Stmt *S) {
4265 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4266 CI != E; ++CI)
4267 if (*CI) {
4268 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4269 GetBlockCallExprs(CBE->getBody());
4270 else
4271 GetBlockCallExprs(*CI);
4272 }
Mike Stump1eb44332009-09-09 15:08:12 +00004273
Steve Naroff54055232008-10-27 17:20:55 +00004274 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4275 if (CE->getCallee()->getType()->isBlockPointerType()) {
4276 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
4277 }
4278 }
4279 return;
4280}
4281
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004282Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00004283 // Navigate to relevant type information.
Steve Naroff54055232008-10-27 17:20:55 +00004284 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004285
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004286 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004287 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004288 } else if (const BlockDeclRefExpr *CDRE =
4289 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004290 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004291 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004292 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004293 }
4294 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4295 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4296 }
4297 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4298 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4299 else if (const ConditionalOperator *CEXPR =
4300 dyn_cast<ConditionalOperator>(BlockExp)) {
4301 Expr *LHSExp = CEXPR->getLHS();
4302 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4303 Expr *RHSExp = CEXPR->getRHS();
4304 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4305 Expr *CONDExp = CEXPR->getCond();
4306 ConditionalOperator *CondExpr =
4307 new (Context) ConditionalOperator(CONDExp,
4308 SourceLocation(), cast<Expr>(LHSStmt),
4309 SourceLocation(), cast<Expr>(RHSStmt),
4310 Exp->getType());
4311 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00004312 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4313 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004314 } else {
4315 assert(1 && "RewriteBlockClass: Bad type");
4316 }
4317 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00004318 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00004319 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00004320 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00004321 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004322
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004323 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
4324 SourceLocation(),
4325 &Context->Idents.get("__block_impl"));
4326 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00004327
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004328 // Generate a funky cast.
4329 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004330
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004331 // Push the block argument type.
4332 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00004333 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004334 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004335 E = FTP->arg_type_end(); I && (I != E); ++I) {
4336 QualType t = *I;
4337 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004338 if (isTopLevelBlockPointerType(t)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004339 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004340 t = Context->getPointerType(BPT->getPointeeType());
4341 }
4342 ArgTypes.push_back(t);
4343 }
Steve Naroff54055232008-10-27 17:20:55 +00004344 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004345 // Now do the pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00004346 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00004347 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0,
4348 false, false, 0, 0,
4349 false, CC_Default);
Mike Stump1eb44332009-09-09 15:08:12 +00004350
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004351 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00004352
John McCall9d125032010-01-15 18:39:57 +00004353 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4354 CastExpr::CK_Unknown,
4355 const_cast<Expr*>(BlockExp));
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004356 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004357 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4358 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004359 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00004360
Douglas Gregor44b43212008-12-11 16:49:14 +00004361 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00004362 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004363 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004364 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4365 FD->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00004366
John McCall9d125032010-01-15 18:39:57 +00004367 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4368 CastExpr::CK_Unknown, ME);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004369 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00004370
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004371 llvm::SmallVector<Expr*, 8> BlkExprs;
4372 // Add the implicit argument.
4373 BlkExprs.push_back(BlkCast);
4374 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004375 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004376 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004377 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00004378 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004379 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4380 BlkExprs.size(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00004381 Exp->getType(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004382 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00004383}
4384
4385void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004386 Stmt *BlockCall = SynthesizeBlockCall(Exp, Exp->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004387 ReplaceStmt(Exp, BlockCall);
Steve Naroff54055232008-10-27 17:20:55 +00004388}
4389
Steve Naroff621edce2009-04-29 16:37:50 +00004390// We need to return the rewritten expression to handle cases where the
4391// BlockDeclRefExpr is embedded in another expression being rewritten.
4392// For example:
4393//
4394// int main() {
4395// __block Foo *f;
4396// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00004397//
Steve Naroff621edce2009-04-29 16:37:50 +00004398// void (^myblock)() = ^() {
4399// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4400// i = 77;
4401// };
4402//}
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004403Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00004404 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004405 // for each DeclRefExp where BYREFVAR is name of the variable.
4406 ValueDecl *VD;
4407 bool isArrow = true;
4408 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4409 VD = BDRE->getDecl();
4410 else {
4411 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4412 isArrow = false;
4413 }
4414
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004415 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4416 &Context->Idents.get("__forwarding"),
4417 Context->VoidPtrTy, 0,
4418 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004419 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4420 FD, SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004421 FD->getType());
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004422
4423 const char *Name = VD->getNameAsCString();
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004424 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4425 &Context->Idents.get(Name),
4426 Context->VoidPtrTy, 0,
4427 /*BitWidth=*/0, /*Mutable=*/true);
4428 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004429 DeclRefExp->getType());
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004430
4431
4432
Steve Naroffdf8570d2009-02-02 17:19:26 +00004433 // Need parens to enforce precedence.
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004434 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4435 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004436 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00004437 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00004438}
4439
Steve Naroffb2f9e512008-11-03 23:29:32 +00004440void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4441 SourceLocation LocStart = CE->getLParenLoc();
4442 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00004443
4444 // Need to avoid trying to rewrite synthesized casts.
4445 if (LocStart.isInvalid())
4446 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00004447 // Need to avoid trying to rewrite casts contained in macros.
4448 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4449 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004450
Steve Naroff54055232008-10-27 17:20:55 +00004451 const char *startBuf = SM->getCharacterData(LocStart);
4452 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004453 QualType QT = CE->getType();
4454 const Type* TypePtr = QT->getAs<Type>();
4455 if (isa<TypeOfExprType>(TypePtr)) {
4456 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4457 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4458 std::string TypeAsString = "(";
Fariborz Jahanianafad76f2010-02-18 01:20:22 +00004459 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004460 TypeAsString += ")";
Benjamin Kramerd999b372010-02-14 14:14:16 +00004461 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004462 return;
4463 }
Steve Naroff54055232008-10-27 17:20:55 +00004464 // advance the location to startArgList.
4465 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00004466
Steve Naroff54055232008-10-27 17:20:55 +00004467 while (*argPtr++ && (argPtr < endBuf)) {
4468 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004469 case '^':
4470 // Replace the '^' with '*'.
4471 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004472 ReplaceText(LocStart, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004473 break;
Steve Naroff54055232008-10-27 17:20:55 +00004474 }
4475 }
4476 return;
4477}
4478
4479void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4480 SourceLocation DeclLoc = FD->getLocation();
4481 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004482
Steve Naroff54055232008-10-27 17:20:55 +00004483 // We have 1 or more arguments that have closure pointers.
4484 const char *startBuf = SM->getCharacterData(DeclLoc);
4485 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00004486
Steve Naroff54055232008-10-27 17:20:55 +00004487 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004488
Steve Naroff54055232008-10-27 17:20:55 +00004489 parenCount++;
4490 // advance the location to startArgList.
4491 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4492 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00004493
Steve Naroff54055232008-10-27 17:20:55 +00004494 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00004495
Steve Naroff54055232008-10-27 17:20:55 +00004496 while (*argPtr++ && parenCount) {
4497 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004498 case '^':
4499 // Replace the '^' with '*'.
4500 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004501 ReplaceText(DeclLoc, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004502 break;
4503 case '(':
4504 parenCount++;
4505 break;
4506 case ')':
4507 parenCount--;
4508 break;
Steve Naroff54055232008-10-27 17:20:55 +00004509 }
4510 }
4511 return;
4512}
4513
4514bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004515 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004516 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004517 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004518 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004519 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004520 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004521 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004522 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004523 }
4524 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004525 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004526 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004527 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004528 return true;
4529 }
4530 return false;
4531}
4532
Ted Kremenek8189cde2009-02-07 01:47:29 +00004533void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4534 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00004535 const char *argPtr = strchr(Name, '(');
4536 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004537
Steve Naroff54055232008-10-27 17:20:55 +00004538 LParen = argPtr; // output the start.
4539 argPtr++; // skip past the left paren.
4540 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004541
Steve Naroff54055232008-10-27 17:20:55 +00004542 while (*argPtr && parenCount) {
4543 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004544 case '(': parenCount++; break;
4545 case ')': parenCount--; break;
4546 default: break;
Steve Naroff54055232008-10-27 17:20:55 +00004547 }
4548 if (parenCount) argPtr++;
4549 }
4550 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4551 RParen = argPtr; // output the end
4552}
4553
4554void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4555 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4556 RewriteBlockPointerFunctionArgs(FD);
4557 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004558 }
Steve Naroff54055232008-10-27 17:20:55 +00004559 // Handle Variables and Typedefs.
4560 SourceLocation DeclLoc = ND->getLocation();
4561 QualType DeclT;
4562 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4563 DeclT = VD->getType();
4564 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4565 DeclT = TDD->getUnderlyingType();
4566 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4567 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004568 else
Steve Naroff54055232008-10-27 17:20:55 +00004569 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00004570
Steve Naroff54055232008-10-27 17:20:55 +00004571 const char *startBuf = SM->getCharacterData(DeclLoc);
4572 const char *endBuf = startBuf;
4573 // scan backward (from the decl location) for the end of the previous decl.
4574 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4575 startBuf--;
Mike Stump1eb44332009-09-09 15:08:12 +00004576
Steve Naroff54055232008-10-27 17:20:55 +00004577 // *startBuf != '^' if we are dealing with a pointer to function that
4578 // may take block argument types (which will be handled below).
4579 if (*startBuf == '^') {
4580 // Replace the '^' with '*', computing a negative offset.
4581 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004582 ReplaceText(DeclLoc, 1, "*");
Steve Naroff54055232008-10-27 17:20:55 +00004583 }
4584 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4585 // Replace the '^' with '*' for arguments.
4586 DeclLoc = ND->getLocation();
4587 startBuf = SM->getCharacterData(DeclLoc);
4588 const char *argListBegin, *argListEnd;
4589 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4590 while (argListBegin < argListEnd) {
4591 if (*argListBegin == '^') {
4592 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004593 ReplaceText(CaretLoc, 1, "*");
Steve Naroff54055232008-10-27 17:20:55 +00004594 }
4595 argListBegin++;
4596 }
4597 }
4598 return;
4599}
4600
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004601
4602/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4603/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4604/// struct Block_byref_id_object *src) {
4605/// _Block_object_assign (&_dest->object, _src->object,
4606/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4607/// [|BLOCK_FIELD_IS_WEAK]) // object
4608/// _Block_object_assign(&_dest->object, _src->object,
4609/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4610/// [|BLOCK_FIELD_IS_WEAK]) // block
4611/// }
4612/// And:
4613/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4614/// _Block_object_dispose(_src->object,
4615/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4616/// [|BLOCK_FIELD_IS_WEAK]) // object
4617/// _Block_object_dispose(_src->object,
4618/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4619/// [|BLOCK_FIELD_IS_WEAK]) // block
4620/// }
4621
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004622std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4623 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004624 std::string S;
Benjamin Kramer1211a712010-01-10 19:57:50 +00004625 if (CopyDestroyCache.count(flag))
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004626 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004627 CopyDestroyCache.insert(flag);
4628 S = "static void __Block_byref_id_object_copy_";
4629 S += utostr(flag);
4630 S += "(void *dst, void *src) {\n";
4631
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004632 // offset into the object pointer is computed as:
4633 // void * + void* + int + int + void* + void *
4634 unsigned IntSize =
4635 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4636 unsigned VoidPtrSize =
4637 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4638
4639 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
4640 S += " _Block_object_assign((char*)dst + ";
4641 S += utostr(offset);
4642 S += ", *(void * *) ((char*)src + ";
4643 S += utostr(offset);
4644 S += "), ";
4645 S += utostr(flag);
4646 S += ");\n}\n";
4647
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004648 S += "static void __Block_byref_id_object_dispose_";
4649 S += utostr(flag);
4650 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004651 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4652 S += utostr(offset);
4653 S += "), ";
4654 S += utostr(flag);
4655 S += ");\n}\n";
4656 return S;
4657}
4658
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004659/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4660/// the declaration into:
4661/// struct __Block_byref_ND {
4662/// void *__isa; // NULL for everything except __weak pointers
4663/// struct __Block_byref_ND *__forwarding;
4664/// int32_t __flags;
4665/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004666/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4667/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004668/// typex ND;
4669/// };
4670///
4671/// It then replaces declaration of ND variable with:
4672/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4673/// __size=sizeof(struct __Block_byref_ND),
4674/// ND=initializer-if-any};
4675///
4676///
4677void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004678 // Insert declaration for the function in which block literal is
4679 // used.
4680 if (CurFunctionDeclToDeclareForBlock)
4681 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004682 int flag = 0;
4683 int isa = 0;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004684 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4685 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00004686 SourceLocation X = ND->getLocEnd();
4687 X = SM->getInstantiationLoc(X);
4688 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004689 std::string Name(ND->getNameAsString());
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004690 std::string ByrefType;
4691 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004692 ByrefType += " {\n";
4693 ByrefType += " void *__isa;\n";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004694 RewriteByRefString(ByrefType, Name, ND);
4695 ByrefType += " *__forwarding;\n";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004696 ByrefType += " int __flags;\n";
4697 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004698 // Add void *__Block_byref_id_object_copy;
4699 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004700 QualType Ty = ND->getType();
4701 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4702 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004703 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4704 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004705 }
4706
4707 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004708 ByrefType += " " + Name + ";\n";
4709 ByrefType += "};\n";
4710 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004711 SourceLocation FunLocStart;
4712 if (CurFunctionDef)
4713 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4714 else {
4715 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4716 FunLocStart = CurMethodDef->getLocStart();
4717 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00004718 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004719 if (Ty.isObjCGCWeak()) {
4720 flag |= BLOCK_FIELD_IS_WEAK;
4721 isa = 1;
4722 }
4723
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004724 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004725 flag = BLOCK_BYREF_CALLER;
4726 QualType Ty = ND->getType();
4727 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4728 if (Ty->isBlockPointerType())
4729 flag |= BLOCK_FIELD_IS_BLOCK;
4730 else
4731 flag |= BLOCK_FIELD_IS_OBJECT;
4732 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004733 if (!HF.empty())
Benjamin Kramerd999b372010-02-14 14:14:16 +00004734 InsertText(FunLocStart, HF);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004735 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004736
4737 // struct __Block_byref_ND ND =
4738 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4739 // initializer-if-any};
4740 bool hasInit = (ND->getInit() != 0);
Fariborz Jahaniane1f84f82010-01-05 18:15:57 +00004741 unsigned flags = 0;
4742 if (HasCopyAndDispose)
4743 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004744 Name = ND->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004745 ByrefType.clear();
4746 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004747 std::string ForwardingCastType("(");
4748 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004749 if (!hasInit) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004750 ByrefType += " " + Name + " = {(void*)";
4751 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004752 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004753 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004754 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004755 ByrefType += "sizeof(";
4756 RewriteByRefString(ByrefType, Name, ND);
4757 ByrefType += ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004758 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004759 ByrefType += ", __Block_byref_id_object_copy_";
4760 ByrefType += utostr(flag);
4761 ByrefType += ", __Block_byref_id_object_dispose_";
4762 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004763 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004764 ByrefType += "};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00004765 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(), ByrefType);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004766 }
4767 else {
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004768 SourceLocation startLoc;
4769 Expr *E = ND->getInit();
4770 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4771 startLoc = ECE->getLParenLoc();
4772 else
4773 startLoc = E->getLocStart();
Fariborz Jahanian791b10d2010-01-05 23:06:29 +00004774 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004775 endBuf = SM->getCharacterData(startLoc);
4776
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004777 ByrefType += " " + Name;
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004778 ByrefType += " = {(void*)";
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004779 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004780 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004781 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004782 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004783 ByrefType += "sizeof(";
4784 RewriteByRefString(ByrefType, Name, ND);
4785 ByrefType += "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004786 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004787 ByrefType += "__Block_byref_id_object_copy_";
4788 ByrefType += utostr(flag);
4789 ByrefType += ", __Block_byref_id_object_dispose_";
4790 ByrefType += utostr(flag);
4791 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004792 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00004793 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroffc5143c52009-12-23 17:24:33 +00004794
4795 // Complete the newly synthesized compound expression by inserting a right
4796 // curly brace before the end of the declaration.
4797 // FIXME: This approach avoids rewriting the initializer expression. It
4798 // also assumes there is only one declarator. For example, the following
4799 // isn't currently supported by this routine (in general):
4800 //
4801 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4802 //
4803 const char *startBuf = SM->getCharacterData(startLoc);
4804 const char *semiBuf = strchr(startBuf, ';');
4805 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4806 SourceLocation semiLoc =
4807 startLoc.getFileLocWithOffset(semiBuf-startBuf);
4808
Benjamin Kramerd999b372010-02-14 14:14:16 +00004809 InsertText(semiLoc, "}");
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004810 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00004811 return;
4812}
4813
Mike Stump1eb44332009-09-09 15:08:12 +00004814void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00004815 // Add initializers for any closure decl refs.
4816 GetBlockDeclRefExprs(Exp->getBody());
4817 if (BlockDeclRefs.size()) {
4818 // Unique all "by copy" declarations.
4819 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004820 if (!BlockDeclRefs[i]->isByRef()) {
4821 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4822 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4823 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4824 }
4825 }
Steve Naroff54055232008-10-27 17:20:55 +00004826 // Unique all "by ref" declarations.
4827 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4828 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004829 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4830 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4831 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4832 }
Steve Naroff54055232008-10-27 17:20:55 +00004833 }
4834 // Find any imported blocks...they will need special attention.
4835 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004836 if (BlockDeclRefs[i]->isByRef() ||
4837 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4838 BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroff00072682008-11-13 17:40:07 +00004839 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff54055232008-10-27 17:20:55 +00004840 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4841 }
4842 }
4843}
4844
Steve Narofffa15fd92008-10-28 20:29:00 +00004845FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4846 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00004847 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump1eb44332009-09-09 15:08:12 +00004848 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004849 ID, FType, 0, FunctionDecl::Extern, false,
Douglas Gregor2224f842009-02-25 16:33:18 +00004850 false);
Steve Narofffa15fd92008-10-28 20:29:00 +00004851}
4852
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004853Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004854 Blocks.push_back(Exp);
4855
4856 CollectBlockDeclRefInfo(Exp);
4857 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00004858
Steve Narofffa15fd92008-10-28 20:29:00 +00004859 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00004860 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004861 else if (CurMethodDef)
4862 BuildUniqueMethodName(FuncName, CurMethodDef);
4863 else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004864 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00004865
Steve Narofffa15fd92008-10-28 20:29:00 +00004866 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00004867
Steve Narofffa15fd92008-10-28 20:29:00 +00004868 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4869 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00004870
Steve Narofffa15fd92008-10-28 20:29:00 +00004871 // Get a pointer to the function type so we can cast appropriately.
4872 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4873
4874 FunctionDecl *FD;
4875 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00004876
Steve Narofffa15fd92008-10-28 20:29:00 +00004877 // Simulate a contructor call...
4878 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004879 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004880
Steve Narofffa15fd92008-10-28 20:29:00 +00004881 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00004882
Steve Narofffdc03722008-10-29 21:23:59 +00004883 // Initialize the block function.
Steve Narofffa15fd92008-10-28 20:29:00 +00004884 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004885 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
4886 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00004887 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4888 CastExpr::CK_Unknown, Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00004889 InitExprs.push_back(castExpr);
4890
Steve Naroff01aec112009-12-06 21:14:13 +00004891 // Initialize the block descriptor.
4892 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00004893
Steve Naroff01aec112009-12-06 21:14:13 +00004894 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
4895 &Context->Idents.get(DescData.c_str()),
4896 Context->VoidPtrTy, 0,
4897 VarDecl::Static);
4898 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
4899 new (Context) DeclRefExpr(NewVD,
4900 Context->VoidPtrTy, SourceLocation()),
4901 UnaryOperator::AddrOf,
4902 Context->getPointerType(Context->VoidPtrTy),
4903 SourceLocation());
4904 InitExprs.push_back(DescRefExpr);
4905
Steve Narofffa15fd92008-10-28 20:29:00 +00004906 // Add initializers for any closure decl refs.
4907 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00004908 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00004909 // Output all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004910 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004911 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004912 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00004913 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner8ec03f52008-11-24 03:54:41 +00004914 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004915 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004916 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004917 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004918 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00004919 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4920 CastExpr::CK_Unknown, Arg);
Steve Narofffa15fd92008-10-28 20:29:00 +00004921 } else {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004922 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004923 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004924 }
Mike Stump1eb44332009-09-09 15:08:12 +00004925 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004926 }
4927 // Output all "by ref" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004928 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004929 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004930 ValueDecl *ND = (*I);
4931 std::string Name(ND->getNameAsString());
4932 std::string RecName;
4933 RewriteByRefString(RecName, Name, ND);
4934 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4935 + sizeof("struct"));
4936 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
4937 SourceLocation(), II);
4938 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4939 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4940
Chris Lattner8ec03f52008-11-24 03:54:41 +00004941 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004942 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4943 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00004944 Context->getPointerType(Exp->getType()),
Steve Narofffdc03722008-10-29 21:23:59 +00004945 SourceLocation());
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004946 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CastExpr::CK_Unknown, Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00004947 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004948 }
4949 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00004950 if (ImportedBlockDecls.size()) {
4951 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4952 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00004953 unsigned IntSize =
4954 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanianff127882009-12-23 21:52:32 +00004955 Expr *FlagExp = new (Context) IntegerLiteral(llvm::APInt(IntSize, flag),
4956 Context->IntTy, SourceLocation());
4957 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00004958 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004959 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4960 FType, SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004961 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00004962 Context->getPointerType(NewRep->getType()),
Steve Narofffa15fd92008-10-28 20:29:00 +00004963 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00004964 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CastExpr::CK_Unknown,
4965 NewRep);
Steve Narofffa15fd92008-10-28 20:29:00 +00004966 BlockDeclRefs.clear();
4967 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004968 BlockByRefDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00004969 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004970 BlockByCopyDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00004971 ImportedBlockDecls.clear();
4972 return NewRep;
4973}
4974
4975//===----------------------------------------------------------------------===//
4976// Function Body / Expression rewriting
4977//===----------------------------------------------------------------------===//
4978
Steve Naroffc77a6362008-12-04 16:24:46 +00004979// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4980// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4981// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4982// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4983// Since the rewriter isn't capable of rewriting rewritten code, it's important
4984// we get this right.
4985void RewriteObjC::CollectPropertySetters(Stmt *S) {
4986 // Perform a bottom up traversal of all children.
4987 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4988 CI != E; ++CI)
4989 if (*CI)
4990 CollectPropertySetters(*CI);
4991
4992 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4993 if (BinOp->isAssignmentOp()) {
4994 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4995 PropSetters[PRE] = BinOp;
4996 }
4997 }
4998}
4999
Steve Narofffa15fd92008-10-28 20:29:00 +00005000Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00005001 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005002 isa<DoStmt>(S) || isa<ForStmt>(S))
5003 Stmts.push_back(S);
5004 else if (isa<ObjCForCollectionStmt>(S)) {
5005 Stmts.push_back(S);
Chris Lattner4824fcd2010-01-09 21:45:57 +00005006 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00005007 }
Mike Stump1eb44332009-09-09 15:08:12 +00005008
Steve Narofffa15fd92008-10-28 20:29:00 +00005009 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005010
Steve Narofffa15fd92008-10-28 20:29:00 +00005011 // Perform a bottom up rewrite of all children.
5012 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5013 CI != E; ++CI)
5014 if (*CI) {
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005015 Stmt *newStmt;
5016 Stmt *S = (*CI);
5017 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5018 Expr *OldBase = IvarRefExpr->getBase();
5019 bool replaced = false;
5020 newStmt = RewriteObjCNestedIvarRefExpr(S, replaced);
5021 if (replaced) {
5022 if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
5023 ReplaceStmt(OldBase, IRE->getBase());
5024 else
5025 ReplaceStmt(S, newStmt);
5026 }
5027 }
5028 else
5029 newStmt = RewriteFunctionBodyOrGlobalInitializer(S);
Mike Stump1eb44332009-09-09 15:08:12 +00005030 if (newStmt)
Steve Narofffa15fd92008-10-28 20:29:00 +00005031 *CI = newStmt;
5032 }
Mike Stump1eb44332009-09-09 15:08:12 +00005033
Steve Narofffa15fd92008-10-28 20:29:00 +00005034 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
5035 // Rewrite the block body in place.
5036 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Mike Stump1eb44332009-09-09 15:08:12 +00005037
Steve Narofffa15fd92008-10-28 20:29:00 +00005038 // Now we snarf the rewritten text and stash it away for later use.
Ted Kremenek6a12a142010-01-07 18:00:35 +00005039 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005040 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00005041
Steve Narofffa15fd92008-10-28 20:29:00 +00005042 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
5043 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005044 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00005045 return blockTranscribed;
5046 }
5047 // Handle specific things.
5048 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5049 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00005050
Steve Naroffc77a6362008-12-04 16:24:46 +00005051 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
5052 BinaryOperator *BinOp = PropSetters[PropRefExpr];
5053 if (BinOp) {
5054 // Because the rewriter doesn't allow us to rewrite rewritten code,
5055 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffb619d952008-12-09 12:56:34 +00005056 DisableReplaceStmt = true;
5057 // Save the source range. Even if we disable the replacement, the
5058 // rewritten node will have been inserted into the tree. If the synthesized
5059 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump1eb44332009-09-09 15:08:12 +00005060 // self.errorHandler = handler ? handler :
Steve Naroffb619d952008-12-09 12:56:34 +00005061 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
5062 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroffc77a6362008-12-04 16:24:46 +00005063 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroffb619d952008-12-09 12:56:34 +00005064 DisableReplaceStmt = false;
Steve Naroff4c3580e2008-12-04 23:50:32 +00005065 //
5066 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
5067 // we changed the RHS of BinOp, the rewriter would fail (since it needs
5068 // to see the original expression). Consider this example:
5069 //
5070 // Foo *obj1, *obj2;
5071 //
5072 // obj1.i = [obj2 rrrr];
5073 //
5074 // 'BinOp' for the previous expression looks like:
5075 //
5076 // (BinaryOperator 0x231ccf0 'int' '='
5077 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
5078 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
5079 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
5080 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
5081 //
5082 // 'newStmt' represents the rewritten message expression. For example:
5083 //
5084 // (CallExpr 0x231d300 'id':'struct objc_object *'
5085 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
5086 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
5087 // (CStyleCastExpr 0x231d220 'void *'
5088 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
5089 //
5090 // Note that 'newStmt' is passed to RewritePropertySetter so that it
5091 // can be used as the setter argument. ReplaceStmt() will still 'see'
5092 // the original RHS (since we haven't altered BinOp).
5093 //
Mike Stump1eb44332009-09-09 15:08:12 +00005094 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff4c3580e2008-12-04 23:50:32 +00005095 // node. As a result, we now leak the original AST nodes.
5096 //
Steve Naroffb619d952008-12-09 12:56:34 +00005097 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroffc77a6362008-12-04 16:24:46 +00005098 } else {
5099 return RewritePropertyGetter(PropRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00005100 }
5101 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005102 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5103 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00005104
Steve Narofffa15fd92008-10-28 20:29:00 +00005105 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5106 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00005107
Steve Narofffa15fd92008-10-28 20:29:00 +00005108 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00005109#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00005110 // Before we rewrite it, put the original message expression in a comment.
5111 SourceLocation startLoc = MessExpr->getLocStart();
5112 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00005113
Steve Narofffa15fd92008-10-28 20:29:00 +00005114 const char *startBuf = SM->getCharacterData(startLoc);
5115 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00005116
Steve Narofffa15fd92008-10-28 20:29:00 +00005117 std::string messString;
5118 messString += "// ";
5119 messString.append(startBuf, endBuf-startBuf+1);
5120 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00005121
5122 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00005123 // InsertText(clang::SourceLocation, char const*, unsigned int).
5124 // InsertText(startLoc, messString.c_str(), messString.size());
5125 // Tried this, but it didn't work either...
5126 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00005127#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00005128 return RewriteMessageExpr(MessExpr);
5129 }
Mike Stump1eb44332009-09-09 15:08:12 +00005130
Steve Narofffa15fd92008-10-28 20:29:00 +00005131 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5132 return RewriteObjCTryStmt(StmtTry);
5133
5134 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5135 return RewriteObjCSynchronizedStmt(StmtTry);
5136
5137 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5138 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00005139
Steve Narofffa15fd92008-10-28 20:29:00 +00005140 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5141 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00005142
5143 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00005144 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00005145 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00005146 OrigStmtRange.getEnd());
5147 if (BreakStmt *StmtBreakStmt =
5148 dyn_cast<BreakStmt>(S))
5149 return RewriteBreakStmt(StmtBreakStmt);
5150 if (ContinueStmt *StmtContinueStmt =
5151 dyn_cast<ContinueStmt>(S))
5152 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00005153
5154 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00005155 // and cast exprs.
5156 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5157 // FIXME: What we're doing here is modifying the type-specifier that
5158 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00005159 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00005160 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5161 // the context of an ObjCForCollectionStmt. For example:
5162 // NSArray *someArray;
5163 // for (id <FooProtocol> index in someArray) ;
5164 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5165 // and it depends on the original text locations/positions.
Benjamin Kramerb2041de2009-12-05 22:16:51 +00005166 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroff3d7e7862009-12-05 15:55:59 +00005167 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00005168
Steve Narofffa15fd92008-10-28 20:29:00 +00005169 // Blocks rewrite rules.
5170 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5171 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00005172 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00005173 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005174 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005175 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00005176 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005177 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005178 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005179 if (VD->hasAttr<BlocksAttr>()) {
5180 static unsigned uniqueByrefDeclCount = 0;
5181 assert(!BlockByRefDeclNo.count(ND) &&
5182 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5183 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005184 RewriteByRefVar(VD);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005185 }
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005186 else
5187 RewriteTypeOfDecl(VD);
5188 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005189 }
5190 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005191 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005192 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005193 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005194 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5195 }
5196 }
5197 }
Mike Stump1eb44332009-09-09 15:08:12 +00005198
Steve Narofffa15fd92008-10-28 20:29:00 +00005199 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5200 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00005201
5202 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005203 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5204 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00005205 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5206 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005207 && "Statement stack mismatch");
5208 Stmts.pop_back();
5209 }
5210 // Handle blocks rewriting.
5211 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5212 if (BDRE->isByRef())
Steve Naroff621edce2009-04-29 16:37:50 +00005213 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofffa15fd92008-10-28 20:29:00 +00005214 }
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005215 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5216 ValueDecl *VD = DRE->getDecl();
5217 if (VD->hasAttr<BlocksAttr>())
5218 return RewriteBlockDeclRefExpr(DRE);
5219 }
5220
Steve Narofffa15fd92008-10-28 20:29:00 +00005221 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005222 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00005223 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005224 ReplaceStmt(S, BlockCall);
5225 return BlockCall;
5226 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005227 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00005228 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005229 RewriteCastExpr(CE);
5230 }
5231#if 0
5232 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00005233 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00005234 // Get the new text.
5235 std::string SStr;
5236 llvm::raw_string_ostream Buf(SStr);
Eli Friedman3a9eb442009-05-30 05:19:26 +00005237 Replacement->printPretty(Buf, *Context);
Steve Narofffa15fd92008-10-28 20:29:00 +00005238 const std::string &Str = Buf.str();
5239
5240 printf("CAST = %s\n", &Str[0]);
5241 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5242 delete S;
5243 return Replacement;
5244 }
5245#endif
5246 // Return this stmt unmodified.
5247 return S;
5248}
5249
Steve Naroff3d7e7862009-12-05 15:55:59 +00005250void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5251 for (RecordDecl::field_iterator i = RD->field_begin(),
5252 e = RD->field_end(); i != e; ++i) {
5253 FieldDecl *FD = *i;
5254 if (isTopLevelBlockPointerType(FD->getType()))
5255 RewriteBlockPointerDecl(FD);
5256 if (FD->getType()->isObjCQualifiedIdType() ||
5257 FD->getType()->isObjCQualifiedInterfaceType())
5258 RewriteObjCQualifiedInterfaceTypes(FD);
5259 }
5260}
5261
Steve Narofffa15fd92008-10-28 20:29:00 +00005262/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5263/// main file of the input.
5264void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5265 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffcb735302008-12-17 00:20:22 +00005266 if (FD->isOverloadedOperator())
5267 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005268
Steve Narofffa15fd92008-10-28 20:29:00 +00005269 // Since function prototypes don't have ParmDecl's, we check the function
5270 // prototype. This enables us to rewrite function declarations and
5271 // definitions using the same code.
Douglas Gregor72564e72009-02-26 23:50:07 +00005272 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005273
Sebastian Redld3a413d2009-04-26 20:35:05 +00005274 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005275 if (CompoundStmt *Body = FD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005276 CurFunctionDef = FD;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005277 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005278 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005279 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005280 Body =
5281 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5282 FD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005283 CurrentBody = 0;
5284 if (PropParentMap) {
5285 delete PropParentMap;
5286 PropParentMap = 0;
5287 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005288 // This synthesizes and inserts the block "impl" struct, invoke function,
5289 // and any copy/dispose helper functions.
5290 InsertBlockLiteralsWithinFunction(FD);
5291 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005292 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00005293 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005294 return;
5295 }
5296 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005297 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005298 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005299 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005300 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005301 Body =
5302 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5303 MD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005304 CurrentBody = 0;
5305 if (PropParentMap) {
5306 delete PropParentMap;
5307 PropParentMap = 0;
5308 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005309 InsertBlockLiteralsWithinMethod(MD);
5310 CurMethodDef = 0;
5311 }
5312 }
5313 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5314 ClassImplementation.push_back(CI);
5315 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5316 CategoryImplementation.push_back(CI);
5317 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5318 RewriteForwardClassDecl(CD);
5319 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5320 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005321 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005322 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005323 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005324 CheckFunctionPointerDecl(VD->getType(), VD);
5325 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00005326 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005327 RewriteCastExpr(CE);
5328 }
5329 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00005330 } else if (VD->getType()->isRecordType()) {
5331 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5332 if (RD->isDefinition())
5333 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005334 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005335 if (VD->getInit()) {
5336 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005337 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005338 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005339 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005340 CurrentBody = 0;
5341 if (PropParentMap) {
5342 delete PropParentMap;
5343 PropParentMap = 0;
5344 }
Mike Stump1eb44332009-09-09 15:08:12 +00005345 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00005346 VD->getNameAsCString());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005347 GlobalVarDecl = 0;
5348
5349 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00005350 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005351 RewriteCastExpr(CE);
5352 }
5353 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005354 return;
5355 }
5356 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005357 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005358 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005359 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005360 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Steve Naroff3d7e7862009-12-05 15:55:59 +00005361 else if (TD->getUnderlyingType()->isRecordType()) {
5362 RecordDecl *RD = TD->getUnderlyingType()->getAs<RecordType>()->getDecl();
5363 if (RD->isDefinition())
5364 RewriteRecordBody(RD);
5365 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005366 return;
5367 }
5368 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroff3d7e7862009-12-05 15:55:59 +00005369 if (RD->isDefinition())
5370 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005371 return;
5372 }
5373 // Nothing yet.
5374}
5375
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00005376void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005377 if (Diags.hasErrorOccurred())
5378 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005379
Steve Narofffa15fd92008-10-28 20:29:00 +00005380 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00005381
Steve Naroff621edce2009-04-29 16:37:50 +00005382 // Here's a great place to add any extra declarations that may be needed.
5383 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00005384 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00005385 E = ProtocolExprDecls.end(); I != E; ++I)
5386 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5387
Benjamin Kramerd999b372010-02-14 14:14:16 +00005388 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff0aab7962008-11-14 14:10:01 +00005389 if (ClassImplementation.size() || CategoryImplementation.size())
5390 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00005391
Steve Narofffa15fd92008-10-28 20:29:00 +00005392 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5393 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00005394 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00005395 Rewrite.getRewriteBufferFor(MainFileID)) {
5396 //printf("Changed:\n");
5397 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5398 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +00005399 llvm::errs() << "No changes\n";
Steve Narofffa15fd92008-10-28 20:29:00 +00005400 }
Steve Narofface66252008-11-13 20:07:04 +00005401
Steve Naroff621edce2009-04-29 16:37:50 +00005402 if (ClassImplementation.size() || CategoryImplementation.size() ||
5403 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00005404 // Rewrite Objective-c meta data*
5405 std::string ResultStr;
5406 SynthesizeMetaDataIntoBuffer(ResultStr);
5407 // Emit metadata.
5408 *OutFile << ResultStr;
5409 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005410 OutFile->flush();
5411}
5412