blob: 804a5d0b9da16c45053b8d7e55c302b225c5389d [file] [log] [blame]
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattnere99c8322007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-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 Lattnere99c8322007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Eli Friedman9f30fc32009-05-18 22:50:54 +000014#include "clang/Frontend/ASTConsumers.h"
Chris Lattner16a0de42007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattnere99c8322007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Steve Naroff1042ff32008-12-08 16:43:47 +000018#include "clang/AST/ParentMap.h"
Chris Lattner16a0de42007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner4431a1b2007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattnerf3a59a12007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Benjamin Kramer89b422c2009-08-23 12:08:50 +000023#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
Chris Lattner211f8b82007-10-25 17:07:24 +000025#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian99e96b02007-10-26 19:46:17 +000026#include "llvm/ADT/SmallPtrSet.h"
Ted Kremenek2d470fc2008-09-13 05:16:45 +000027#include "llvm/ADT/OwningPtr.h"
Fariborz Jahaniane3891582010-01-05 18:04:40 +000028#include "llvm/ADT/DenseSet.h"
Fariborz Jahanianf4609d42010-03-01 23:36:21 +000029
Chris Lattnere99c8322007-10-11 00:43:27 +000030using namespace clang;
Chris Lattner211f8b82007-10-25 17:07:24 +000031using llvm::utostr;
Chris Lattnere99c8322007-10-11 00:43:27 +000032
Chris Lattnere99c8322007-10-11 00:43:27 +000033namespace {
Steve Naroff1dc53ef2008-04-14 22:03:09 +000034 class RewriteObjC : public ASTConsumer {
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +000035 enum {
36 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
37 block, ... */
38 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
39 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
40 __block variable */
41 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
42 helpers */
43 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
44 support routines */
45 BLOCK_BYREF_CURRENT_MAX = 256
46 };
47
48 enum {
49 BLOCK_NEEDS_FREE = (1 << 24),
50 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
51 BLOCK_HAS_CXX_OBJ = (1 << 26),
52 BLOCK_IS_GC = (1 << 27),
53 BLOCK_IS_GLOBAL = (1 << 28),
54 BLOCK_HAS_DESCRIPTOR = (1 << 29)
55 };
56
Chris Lattner0bd1c972007-10-16 21:07:07 +000057 Rewriter Rewrite;
Chris Lattnere9c810c2007-11-30 22:25:36 +000058 Diagnostic &Diags;
Steve Naroff945a3b12008-03-10 20:43:59 +000059 const LangOptions &LangOpts;
Steve Naroff7b3579b2008-01-30 19:17:43 +000060 unsigned RewriteFailedDiag;
Steve Naroff6d6da252008-12-05 17:03:39 +000061 unsigned TryFinallyContainsReturnDiag;
Mike Stump11289f42009-09-09 15:08:12 +000062
Chris Lattnerc6d91c02007-10-17 22:35:30 +000063 ASTContext *Context;
Chris Lattnere99c8322007-10-11 00:43:27 +000064 SourceManager *SM;
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +000065 TranslationUnitDecl *TUDecl;
Chris Lattnerd32480d2009-01-17 06:22:33 +000066 FileID MainFileID;
Chris Lattnerf3a59a12007-12-02 01:13:47 +000067 const char *MainFileStart, *MainFileEnd;
Chris Lattner0bd1c972007-10-16 21:07:07 +000068 SourceLocation LastIncLoc;
Mike Stump11289f42009-09-09 15:08:12 +000069
Ted Kremenek1b0ea822008-01-07 19:49:32 +000070 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
71 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
72 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Naroff13e74872008-05-06 18:26:51 +000073 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremenek1b0ea822008-01-07 19:49:32 +000074 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
75 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +000076 llvm::SmallVector<Stmt *, 32> Stmts;
77 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffd9803712009-04-29 16:37:50 +000078 // Remember all the @protocol(<expr>) expressions.
79 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahaniane3891582010-01-05 18:04:40 +000080
81 llvm::DenseSet<uint64_t> CopyDestroyCache;
82
Steve Naroffce8e8862008-03-15 00:55:56 +000083 unsigned NumObjCStringLiterals;
Mike Stump11289f42009-09-09 15:08:12 +000084
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000085 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff7fa2f042007-11-15 10:28:18 +000086 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +000087 FunctionDecl *MsgSendStretFunctionDecl;
88 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanian4f76f222007-12-03 21:26:48 +000089 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000090 FunctionDecl *GetClassFunctionDecl;
Steve Naroffb2f8ff12007-12-07 03:50:46 +000091 FunctionDecl *GetMetaClassFunctionDecl;
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +000092 FunctionDecl *GetSuperClassFunctionDecl;
Steve Naroff574440f2007-10-24 22:48:43 +000093 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff265a6b92007-11-08 14:30:50 +000094 FunctionDecl *CFStringFunctionDecl;
Steve Naroff17978c42008-03-11 17:37:02 +000095 FunctionDecl *SuperContructorFunctionDecl;
Mike Stump11289f42009-09-09 15:08:12 +000096
Steve Naroffa397efd2007-11-03 11:27:19 +000097 // ObjC string constant support.
Steve Naroff08899ff2008-04-15 22:42:06 +000098 VarDecl *ConstantStringClassReference;
Steve Naroffa397efd2007-11-03 11:27:19 +000099 RecordDecl *NSStringRecord;
Mike Stump11289f42009-09-09 15:08:12 +0000100
Fariborz Jahanian19d42bf2008-01-16 00:09:11 +0000101 // ObjC foreach break/continue generation support.
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +0000102 int BcLabelCount;
Mike Stump11289f42009-09-09 15:08:12 +0000103
Steve Naroff7fa2f042007-11-15 10:28:18 +0000104 // Needed for super.
Steve Naroff677ab3a2008-10-27 17:20:55 +0000105 ObjCMethodDecl *CurMethodDef;
Steve Naroff7fa2f042007-11-15 10:28:18 +0000106 RecordDecl *SuperStructDecl;
Steve Naroffce8e8862008-03-15 00:55:56 +0000107 RecordDecl *ConstantStringDecl;
Mike Stump11289f42009-09-09 15:08:12 +0000108
Steve Naroffd9803712009-04-29 16:37:50 +0000109 TypeDecl *ProtocolTypeDecl;
110 QualType getProtocolType();
Mike Stump11289f42009-09-09 15:08:12 +0000111
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000112 // Needed for header files being rewritten
113 bool IsHeader;
Mike Stump11289f42009-09-09 15:08:12 +0000114
Steve Narofff9e7c902008-03-28 22:26:09 +0000115 std::string InFileName;
Eli Friedman94cf21e2009-05-18 22:20:00 +0000116 llvm::raw_ostream* OutFile;
Eli Friedmanf22439a2009-05-18 22:39:16 +0000117
118 bool SilenceRewriteMacroWarning;
Fariborz Jahanianbc6811c2010-01-07 22:51:18 +0000119 bool objc_impl_method;
Eli Friedmanf22439a2009-05-18 22:39:16 +0000120
Steve Naroff00a31762008-03-27 22:29:16 +0000121 std::string Preamble;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000122
123 // Block expressions.
124 llvm::SmallVector<BlockExpr *, 32> Blocks;
Fariborz Jahanian8652be02010-02-24 22:48:18 +0000125 llvm::SmallVector<int, 32> InnerDeclRefsCount;
126 llvm::SmallVector<BlockDeclRefExpr *, 32> InnerDeclRefs;
127
Steve Naroff677ab3a2008-10-27 17:20:55 +0000128 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
Mike Stump11289f42009-09-09 15:08:12 +0000129
Steve Naroff677ab3a2008-10-27 17:20:55 +0000130 // Block related declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +0000131 llvm::SmallVector<ValueDecl *, 8> BlockByCopyDecls;
132 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
133 llvm::SmallVector<ValueDecl *, 8> BlockByRefDecls;
134 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +0000135 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000136 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
Fariborz Jahanian3a106e72010-03-11 18:20:03 +0000137 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
138
Steve Naroff677ab3a2008-10-27 17:20:55 +0000139 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
140
Steve Naroff4588d0f2008-12-04 16:24:46 +0000141 // This maps a property to it's assignment statement.
142 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
Steve Naroff1042ff32008-12-08 16:43:47 +0000143 // This maps a property to it's synthesied message expression.
144 // This allows us to rewrite chained getters (e.g. o.a.b.c).
145 llvm::DenseMap<ObjCPropertyRefExpr *, Stmt *> PropGetters;
Mike Stump11289f42009-09-09 15:08:12 +0000146
Steve Naroff22216db2008-12-04 23:50:32 +0000147 // This maps an original source AST to it's rewritten form. This allows
148 // us to avoid rewriting the same node twice (which is very uncommon).
149 // This is needed to support some of the exotic property rewriting.
150 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Narofff326f402008-12-03 00:56:33 +0000151
Steve Naroff677ab3a2008-10-27 17:20:55 +0000152 FunctionDecl *CurFunctionDef;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000153 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Steve Naroffd8907b72008-10-29 18:15:37 +0000154 VarDecl *GlobalVarDecl;
Mike Stump11289f42009-09-09 15:08:12 +0000155
Steve Naroff08628db2008-12-09 12:56:34 +0000156 bool DisableReplaceStmt;
Mike Stump11289f42009-09-09 15:08:12 +0000157
Fariborz Jahanian93191af2007-10-18 19:23:00 +0000158 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnere99c8322007-10-11 00:43:27 +0000159 public:
Ted Kremenek380df932008-05-31 20:11:04 +0000160 virtual void Initialize(ASTContext &context);
161
Chris Lattner3c799d72007-10-24 17:06:59 +0000162 // Top Level Driver code.
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000163 virtual void HandleTopLevelDecl(DeclGroupRef D) {
164 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
165 HandleTopLevelSingleDecl(*I);
166 }
167 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000168 void HandleDeclInMainFile(Decl *D);
Eli Friedman94cf21e2009-05-18 22:20:00 +0000169 RewriteObjC(std::string inFile, llvm::raw_ostream *OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000170 Diagnostic &D, const LangOptions &LOpts,
171 bool silenceMacroWarn);
Ted Kremenek6231e7e2008-08-08 04:15:52 +0000172
173 ~RewriteObjC() {}
Mike Stump11289f42009-09-09 15:08:12 +0000174
Chris Lattnercf169832009-03-28 04:11:33 +0000175 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump11289f42009-09-09 15:08:12 +0000176
Fariborz Jahaniana7e1dcd2010-02-05 16:43:40 +0000177 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff22216db2008-12-04 23:50:32 +0000178 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump11289f42009-09-09 15:08:12 +0000179
Steve Naroff22216db2008-12-04 23:50:32 +0000180 if (ReplacingStmt)
181 return; // We can't rewrite the same node twice.
Chris Lattner2e0d2602008-01-31 19:37:57 +0000182
Steve Naroff08628db2008-12-09 12:56:34 +0000183 if (DisableReplaceStmt)
184 return; // Used when rewriting the assignment of a property setter.
185
Steve Naroff22216db2008-12-04 23:50:32 +0000186 // If replacement succeeded or warning disabled return with no warning.
Fariborz Jahaniana7e1dcd2010-02-05 16:43:40 +0000187 if (!Rewrite.ReplaceStmt(Old, New)) {
Steve Naroff22216db2008-12-04 23:50:32 +0000188 ReplacedNodes[Old] = New;
189 return;
190 }
191 if (SilenceRewriteMacroWarning)
192 return;
Chris Lattner8488c822008-11-18 07:04:44 +0000193 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
194 << Old->getSourceRange();
Chris Lattner2e0d2602008-01-31 19:37:57 +0000195 }
Steve Naroff08628db2008-12-09 12:56:34 +0000196
197 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
198 // Measaure the old text.
199 int Size = Rewrite.getRangeSize(SrcRange);
200 if (Size == -1) {
201 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
202 << Old->getSourceRange();
203 return;
204 }
205 // Get the new text.
206 std::string SStr;
207 llvm::raw_string_ostream S(SStr);
Chris Lattnerc61089a2009-06-30 01:26:17 +0000208 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroff08628db2008-12-09 12:56:34 +0000209 const std::string &Str = S.str();
210
211 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000212 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroff08628db2008-12-09 12:56:34 +0000213 ReplacedNodes[Old] = New;
214 return;
215 }
216 if (SilenceRewriteMacroWarning)
217 return;
218 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
219 << Old->getSourceRange();
220 }
221
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000222 void InsertText(SourceLocation Loc, llvm::StringRef Str,
Steve Naroff00a31762008-03-27 22:29:16 +0000223 bool InsertAfter = true) {
Chris Lattner9cc55f52008-01-31 19:51:04 +0000224 // If insertion succeeded or warning disabled return with no warning.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000225 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
Chris Lattner1780a852008-01-31 19:42:41 +0000226 SilenceRewriteMacroWarning)
227 return;
Mike Stump11289f42009-09-09 15:08:12 +0000228
Chris Lattner1780a852008-01-31 19:42:41 +0000229 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
230 }
Mike Stump11289f42009-09-09 15:08:12 +0000231
Chris Lattner9cc55f52008-01-31 19:51:04 +0000232 void RemoveText(SourceLocation Loc, unsigned StrLen) {
233 // If removal succeeded or warning disabled return with no warning.
234 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
235 return;
Mike Stump11289f42009-09-09 15:08:12 +0000236
Chris Lattner9cc55f52008-01-31 19:51:04 +0000237 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
238 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000239
Chris Lattner9cc55f52008-01-31 19:51:04 +0000240 void ReplaceText(SourceLocation Start, unsigned OrigLength,
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000241 llvm::StringRef Str) {
Chris Lattner9cc55f52008-01-31 19:51:04 +0000242 // If removal succeeded or warning disabled return with no warning.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000243 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
Chris Lattner9cc55f52008-01-31 19:51:04 +0000244 SilenceRewriteMacroWarning)
245 return;
Mike Stump11289f42009-09-09 15:08:12 +0000246
Chris Lattner9cc55f52008-01-31 19:51:04 +0000247 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
248 }
Mike Stump11289f42009-09-09 15:08:12 +0000249
Chris Lattner3c799d72007-10-24 17:06:59 +0000250 // Syntactic Rewriting.
Steve Narofff36987c2007-11-04 22:37:50 +0000251 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000252 void RewriteInclude();
Chris Lattner3c799d72007-10-24 17:06:59 +0000253 void RewriteTabs();
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000254 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffc038b3a2008-12-02 17:36:43 +0000255 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
256 ObjCImplementationDecl *IMD,
257 ObjCCategoryImplDecl *CID);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000258 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000259 void RewriteImplementationDecl(Decl *Dcl);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000260 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000261 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
262 const FunctionType *&FPRetType);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +0000263 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
264 ValueDecl *VD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000265 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
266 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
267 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
268 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000269 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000270 void RewriteFunctionDecl(FunctionDecl *FD);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000271 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000272 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +0000273 void RewriteTypeOfDecl(VarDecl *VD);
Steve Naroff873bd842008-07-29 18:15:38 +0000274 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroff50d42052007-11-01 13:24:47 +0000275 bool needToScanForQualifiers(QualType T);
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +0000276 bool isSuperReceiver(Expr *recExpr);
Steve Naroff7fa2f042007-11-15 10:28:18 +0000277 QualType getSuperStructType();
Steve Naroffce8e8862008-03-15 00:55:56 +0000278 QualType getConstantStringStructType();
Steve Naroffcd92aeb2008-05-31 14:15:04 +0000279 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump11289f42009-09-09 15:08:12 +0000280
Chris Lattner3c799d72007-10-24 17:06:59 +0000281 // Expression Rewriting.
Steve Naroff20113382007-11-09 15:20:18 +0000282 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroff4588d0f2008-12-04 16:24:46 +0000283 void CollectPropertySetters(Stmt *S);
Mike Stump11289f42009-09-09 15:08:12 +0000284
Steve Naroff1042ff32008-12-08 16:43:47 +0000285 Stmt *CurrentBody;
286 ParentMap *PropParentMap; // created lazily.
Mike Stump11289f42009-09-09 15:08:12 +0000287
Chris Lattner69534692007-10-24 16:57:36 +0000288 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +0000289 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart,
290 bool &replaced);
291 Stmt *RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced);
Steve Naroff4588d0f2008-12-04 16:24:46 +0000292 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Mike Stump11289f42009-09-09 15:08:12 +0000293 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroff08628db2008-12-09 12:56:34 +0000294 SourceRange SrcRange);
Steve Naroffe4f9b232007-11-05 14:50:49 +0000295 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner69534692007-10-24 16:57:36 +0000296 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffa397efd2007-11-03 11:27:19 +0000297 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian33c0e812007-12-07 18:47:10 +0000298 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffec60b432009-12-05 21:43:12 +0000299 void WarnAboutReturnGotoStmts(Stmt *S);
300 void HasReturnStmts(Stmt *S, bool &hasReturns);
301 void RewriteTryReturnStmts(Stmt *S);
302 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000303 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian284011b2008-01-29 22:59:37 +0000304 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000305 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
306 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
307 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattnera779d692008-01-31 05:10:40 +0000308 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
309 SourceLocation OrigEnd);
Mike Stump11289f42009-09-09 15:08:12 +0000310 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +0000311 Expr **args, unsigned nargs,
312 SourceLocation StartLoc=SourceLocation(),
313 SourceLocation EndLoc=SourceLocation());
314 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
315 SourceLocation StartLoc=SourceLocation(),
316 SourceLocation EndLoc=SourceLocation());
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +0000317 Stmt *RewriteBreakStmt(BreakStmt *S);
318 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian965a8962008-01-08 22:06:28 +0000319 void SynthCountByEnumWithState(std::string &buf);
Mike Stump11289f42009-09-09 15:08:12 +0000320
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000321 void SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +0000322 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000323 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +0000324 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000325 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000326 void SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +0000327 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +0000328 void SynthGetSuperClassFunctionDecl();
Fariborz Jahanian31e18502007-12-04 21:47:40 +0000329 void SynthSelGetUidFunctionDecl();
Steve Naroff17978c42008-03-11 17:37:02 +0000330 void SynthSuperContructorFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000331
Chris Lattner3c799d72007-10-24 17:06:59 +0000332 // Metadata emission.
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000333 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000334 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000335
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000336 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000337 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000338
Douglas Gregor29bd76f2009-04-23 01:02:12 +0000339 template<typename MethodIterator>
340 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
341 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +0000342 bool IsInstanceMethod,
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +0000343 const char *prefix,
Chris Lattner211f8b82007-10-25 17:07:24 +0000344 const char *ClassName,
345 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000346
Steve Naroffd9803712009-04-29 16:37:50 +0000347 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
348 const char *prefix,
349 const char *ClassName,
350 std::string &Result);
351 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Mike Stump11289f42009-09-09 15:08:12 +0000352 const char *prefix,
Steve Naroffd9803712009-04-29 16:37:50 +0000353 const char *ClassName,
354 std::string &Result);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000355 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000356 std::string &Result);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000357 void SynthesizeIvarOffsetComputation(ObjCContainerDecl *IDecl,
Mike Stump11289f42009-09-09 15:08:12 +0000358 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000359 std::string &Result);
Steve Narofff8cfd162008-11-13 20:07:04 +0000360 void RewriteImplementations();
361 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000362
Steve Naroff677ab3a2008-10-27 17:20:55 +0000363 // Block rewriting.
Mike Stump11289f42009-09-09 15:08:12 +0000364 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000365 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump11289f42009-09-09 15:08:12 +0000366
Steve Naroff677ab3a2008-10-27 17:20:55 +0000367 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
368 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump11289f42009-09-09 15:08:12 +0000369
370 // Block specific rewrite rules.
Steve Naroff677ab3a2008-10-27 17:20:55 +0000371 void RewriteBlockCall(CallExpr *Exp);
372 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000373 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahaniane3891582010-01-05 18:04:40 +0000374 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +0000375 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +0000376 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000377 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump11289f42009-09-09 15:08:12 +0000378
379 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Steve Naroff677ab3a2008-10-27 17:20:55 +0000380 const char *funcName, std::string Tag);
Mike Stump11289f42009-09-09 15:08:12 +0000381 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Steve Naroff677ab3a2008-10-27 17:20:55 +0000382 const char *funcName, std::string Tag);
Steve Naroff30484702009-12-06 21:14:13 +0000383 std::string SynthesizeBlockImpl(BlockExpr *CE,
384 std::string Tag, std::string Desc);
385 std::string SynthesizeBlockDescriptor(std::string DescTag,
386 std::string ImplTag,
387 int i, const char *funcName,
388 unsigned hasCopy);
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +0000389 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000390 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000391 const char *FunName);
Steve Naroffe70a52a2009-12-05 15:55:59 +0000392 void RewriteRecordBody(RecordDecl *RD);
Mike Stump11289f42009-09-09 15:08:12 +0000393
Steve Naroff677ab3a2008-10-27 17:20:55 +0000394 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000395 void GetBlockDeclRefExprs(Stmt *S);
Fariborz Jahanian8652be02010-02-24 22:48:18 +0000396 void GetInnerBlockDeclRefExprs(Stmt *S,
397 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +0000398 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
Mike Stump11289f42009-09-09 15:08:12 +0000399
Steve Naroff677ab3a2008-10-27 17:20:55 +0000400 // We avoid calling Type::isBlockPointerType(), since it operates on the
401 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek5a201952009-02-07 01:47:29 +0000402 bool isTopLevelBlockPointerType(QualType T) {
403 return isa<BlockPointerType>(T);
404 }
Mike Stump11289f42009-09-09 15:08:12 +0000405
Steve Naroff677ab3a2008-10-27 17:20:55 +0000406 // FIXME: This predicate seems like it would be useful to add to ASTContext.
407 bool isObjCType(QualType T) {
408 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
409 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000410
Steve Naroff677ab3a2008-10-27 17:20:55 +0000411 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000412
Steve Naroff677ab3a2008-10-27 17:20:55 +0000413 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
414 OCT == Context->getCanonicalType(Context->getObjCClassType()))
415 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000416
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000417 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +0000418 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Narofffb4330f2009-06-17 22:40:22 +0000419 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff677ab3a2008-10-27 17:20:55 +0000420 return true;
421 }
422 return false;
423 }
424 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek5a201952009-02-07 01:47:29 +0000425 void GetExtentOfArgList(const char *Name, const char *&LParen,
426 const char *&RParen);
Steve Naroffc989a7b2008-11-03 23:29:32 +0000427 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump11289f42009-09-09 15:08:12 +0000428
Steve Narofff4b992a2008-10-28 20:29:00 +0000429 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Fariborz Jahanian8652be02010-02-24 22:48:18 +0000430 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
431 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs);
Mike Stump11289f42009-09-09 15:08:12 +0000432
Steve Naroffd9803712009-04-29 16:37:50 +0000433 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump11289f42009-09-09 15:08:12 +0000434 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroffd9803712009-04-29 16:37:50 +0000435 if (From[i] == '"')
436 To += "\\\"";
437 else
438 To += From[i];
439 }
440 }
Chris Lattnere99c8322007-10-11 00:43:27 +0000441 };
John McCall97513962010-01-15 18:39:57 +0000442
443 // Helper function: create a CStyleCastExpr with trivial type source info.
444 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
445 CastExpr::CastKind Kind, Expr *E) {
446 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
447 return new (Ctx) CStyleCastExpr(Ty, Kind, E, TInfo,
448 SourceLocation(), SourceLocation());
449 }
Chris Lattnere99c8322007-10-11 00:43:27 +0000450}
451
Mike Stump11289f42009-09-09 15:08:12 +0000452void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
453 NamedDecl *D) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000454 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000455 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +0000456 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +0000457 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +0000458 // All the args are checked/rewritten. Don't call twice!
459 RewriteBlockPointerDecl(D);
460 break;
461 }
462 }
463}
464
465void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000466 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +0000467 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000468 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000469}
470
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000471static bool IsHeaderFile(const std::string &Filename) {
472 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump11289f42009-09-09 15:08:12 +0000473
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000474 if (DotPos == std::string::npos) {
475 // no file extension
Mike Stump11289f42009-09-09 15:08:12 +0000476 return false;
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000477 }
Mike Stump11289f42009-09-09 15:08:12 +0000478
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000479 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
480 // C header: .h
481 // C++ header: .hh or .H;
482 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump11289f42009-09-09 15:08:12 +0000483}
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000484
Eli Friedman94cf21e2009-05-18 22:20:00 +0000485RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000486 Diagnostic &D, const LangOptions &LOpts,
487 bool silenceMacroWarn)
488 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
489 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Narofff9e7c902008-03-28 22:26:09 +0000490 IsHeader = IsHeaderFile(inFile);
Mike Stump11289f42009-09-09 15:08:12 +0000491 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Narofff9e7c902008-03-28 22:26:09 +0000492 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump11289f42009-09-09 15:08:12 +0000493 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek5a201952009-02-07 01:47:29 +0000494 "rewriter doesn't support user-specified control flow semantics "
495 "for @try/@finally (code may not execute properly)");
Steve Narofff9e7c902008-03-28 22:26:09 +0000496}
497
Eli Friedmana63ab2d2009-05-18 22:29:17 +0000498ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
499 llvm::raw_ostream* OS,
Mike Stump11289f42009-09-09 15:08:12 +0000500 Diagnostic &Diags,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000501 const LangOptions &LOpts,
502 bool SilenceRewriteMacroWarning) {
503 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere9c810c2007-11-30 22:25:36 +0000504}
Chris Lattnere99c8322007-10-11 00:43:27 +0000505
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000506void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner187f6262008-01-31 19:38:44 +0000507 Context = &context;
508 SM = &Context->getSourceManager();
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +0000509 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner187f6262008-01-31 19:38:44 +0000510 MsgSendFunctionDecl = 0;
511 MsgSendSuperFunctionDecl = 0;
512 MsgSendStretFunctionDecl = 0;
513 MsgSendSuperStretFunctionDecl = 0;
514 MsgSendFpretFunctionDecl = 0;
515 GetClassFunctionDecl = 0;
516 GetMetaClassFunctionDecl = 0;
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +0000517 GetSuperClassFunctionDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000518 SelGetUidFunctionDecl = 0;
519 CFStringFunctionDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000520 ConstantStringClassReference = 0;
521 NSStringRecord = 0;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000522 CurMethodDef = 0;
523 CurFunctionDef = 0;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000524 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000525 GlobalVarDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000526 SuperStructDecl = 0;
Steve Naroffd9803712009-04-29 16:37:50 +0000527 ProtocolTypeDecl = 0;
Steve Naroff60a9ef62008-03-27 22:59:54 +0000528 ConstantStringDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000529 BcLabelCount = 0;
Steve Naroff17978c42008-03-11 17:37:02 +0000530 SuperContructorFunctionDecl = 0;
Steve Naroffce8e8862008-03-15 00:55:56 +0000531 NumObjCStringLiterals = 0;
Steve Narofff1ab6002008-12-08 20:01:41 +0000532 PropParentMap = 0;
533 CurrentBody = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000534 DisableReplaceStmt = false;
Fariborz Jahanianbc6811c2010-01-07 22:51:18 +0000535 objc_impl_method = false;
Mike Stump11289f42009-09-09 15:08:12 +0000536
Chris Lattner187f6262008-01-31 19:38:44 +0000537 // Get the ID and start/end of the main file.
538 MainFileID = SM->getMainFileID();
539 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
540 MainFileStart = MainBuf->getBufferStart();
541 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000542
Chris Lattner184e65d2009-04-14 23:22:57 +0000543 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump11289f42009-09-09 15:08:12 +0000544
Chris Lattner187f6262008-01-31 19:38:44 +0000545 // declaring objc_selector outside the parameter list removes a silly
546 // scope related warning...
Steve Naroff00a31762008-03-27 22:29:16 +0000547 if (IsHeader)
Steve Narofffcc6fd52009-02-03 20:39:18 +0000548 Preamble = "#pragma once\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000549 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff6ab6dc72008-12-23 20:11:22 +0000550 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroff00a31762008-03-27 22:29:16 +0000551 Preamble += "struct objc_object *superClass; ";
Steve Naroff17978c42008-03-11 17:37:02 +0000552 if (LangOpts.Microsoft) {
553 // Add a constructor for creating temporary objects.
Ted Kremenek5a201952009-02-07 01:47:29 +0000554 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
555 ": ";
Steve Naroff00a31762008-03-27 22:29:16 +0000556 Preamble += "object(o), superClass(s) {} ";
Steve Naroff17978c42008-03-11 17:37:02 +0000557 }
Steve Naroff00a31762008-03-27 22:29:16 +0000558 Preamble += "};\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000559 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
560 Preamble += "typedef struct objc_object Protocol;\n";
561 Preamble += "#define _REWRITER_typedef_Protocol\n";
562 Preamble += "#endif\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000563 if (LangOpts.Microsoft) {
564 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
565 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
566 } else
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000567 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000568 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroff00a31762008-03-27 22:29:16 +0000569 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000570 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroff00a31762008-03-27 22:29:16 +0000571 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000572 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000573 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000574 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000575 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000576 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroff00a31762008-03-27 22:29:16 +0000577 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000578 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000579 Preamble += "(const char *);\n";
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +0000580 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
581 Preamble += "(struct objc_class *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000582 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000583 Preamble += "(const char *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000584 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
585 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
586 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
587 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
588 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroffd30f8c52008-05-09 21:17:56 +0000589 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff8dd15252008-07-16 18:58:11 +0000590 // @synchronized hooks.
Steve Narofff122ff02008-12-08 17:30:33 +0000591 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
592 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
593 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000594 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
595 Preamble += "struct __objcFastEnumerationState {\n\t";
596 Preamble += "unsigned long state;\n\t";
Steve Naroff4dbab8a2008-04-04 22:58:22 +0000597 Preamble += "void **itemsPtr;\n\t";
Steve Naroff00a31762008-03-27 22:29:16 +0000598 Preamble += "unsigned long *mutationsPtr;\n\t";
599 Preamble += "unsigned long extra[5];\n};\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000600 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000601 Preamble += "#define __FASTENUMERATIONSTATE\n";
602 Preamble += "#endif\n";
603 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
604 Preamble += "struct __NSConstantStringImpl {\n";
605 Preamble += " int *isa;\n";
606 Preamble += " int flags;\n";
607 Preamble += " char *str;\n";
608 Preamble += " long length;\n";
609 Preamble += "};\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000610 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
611 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
612 Preamble += "#else\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000613 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000614 Preamble += "#endif\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000615 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
616 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000617 // Blocks preamble.
618 Preamble += "#ifndef BLOCK_IMPL\n";
619 Preamble += "#define BLOCK_IMPL\n";
620 Preamble += "struct __block_impl {\n";
621 Preamble += " void *isa;\n";
622 Preamble += " int Flags;\n";
Steve Naroff30484702009-12-06 21:14:13 +0000623 Preamble += " int Reserved;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000624 Preamble += " void *FuncPtr;\n";
625 Preamble += "};\n";
Steve Naroff61d879e2008-12-16 15:50:30 +0000626 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroff287a2bf2009-12-06 01:52:22 +0000627 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000628 Preamble += "extern \"C\" __declspec(dllexport) "
629 "void _Block_object_assign(void *, const void *, const int);\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000630 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
631 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
632 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
633 Preamble += "#else\n";
Steve Naroff7bf01ea2010-01-05 18:09:31 +0000634 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
635 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000636 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
637 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
638 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000639 Preamble += "#endif\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000640 if (LangOpts.Microsoft) {
Steve Narofff122ff02008-12-08 17:30:33 +0000641 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
642 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Chris Lattner8d269dc2010-04-13 17:33:56 +0000643 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
Steve Naroffcb04e882008-10-27 18:50:14 +0000644 Preamble += "#define __attribute__(X)\n";
Chris Lattner8d269dc2010-04-13 17:33:56 +0000645 Preamble += "#endif\n";
Fariborz Jahanianf0462ff2010-01-15 22:29:39 +0000646 Preamble += "#define __weak\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000647 }
Fariborz Jahanian7fac6552010-01-05 19:21:35 +0000648 else {
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000649 Preamble += "#define __block\n";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +0000650 Preamble += "#define __weak\n";
651 }
Fariborz Jahaniandb217c42010-03-02 01:19:04 +0000652 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
653 // as this avoids warning in any 64bit/32bit compilation model.
654 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
Chris Lattner187f6262008-01-31 19:38:44 +0000655}
656
657
Chris Lattner3c799d72007-10-24 17:06:59 +0000658//===----------------------------------------------------------------------===//
659// Top Level Driver Code
660//===----------------------------------------------------------------------===//
661
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000662void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremenek31e7f0f2010-02-05 21:28:51 +0000663 if (Diags.hasErrorOccurred())
664 return;
665
Chris Lattner0bd1c972007-10-16 21:07:07 +0000666 // Two cases: either the decl could be in the main file, or it could be in a
667 // #included file. If the former, rewrite it now. If the later, check to see
668 // if we rewrote the #include/#import.
669 SourceLocation Loc = D->getLocation();
Chris Lattner8a425862009-01-16 07:36:28 +0000670 Loc = SM->getInstantiationLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000671
Chris Lattner0bd1c972007-10-16 21:07:07 +0000672 // If this is for a builtin, ignore it.
673 if (Loc.isInvalid()) return;
674
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000675 // Look for built-in declarations that we need to refer during the rewrite.
676 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000677 RewriteFunctionDecl(FD);
Steve Naroff08899ff2008-04-15 22:42:06 +0000678 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000679 // declared in <Foundation/NSString.h>
Chris Lattner86d7d912008-11-24 03:54:41 +0000680 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000681 ConstantStringClassReference = FVD;
682 return;
683 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000684 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff161a92b2007-10-26 20:53:56 +0000685 RewriteInterfaceDecl(MD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000686 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000687 RewriteCategoryDecl(CD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000688 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff921385f2007-10-30 16:42:30 +0000689 RewriteProtocolDecl(PD);
Mike Stump11289f42009-09-09 15:08:12 +0000690 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000691 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000692 RewriteForwardProtocolDecl(FP);
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000693 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
694 // Recurse into linkage specifications
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000695 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
696 DIEnd = LSD->decls_end();
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000697 DI != DIEnd; ++DI)
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000698 HandleTopLevelSingleDecl(*DI);
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000699 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000700 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekd61ed3b2008-04-14 21:24:13 +0000701 if (SM->isFromMainFile(Loc))
Chris Lattner0bd1c972007-10-16 21:07:07 +0000702 return HandleDeclInMainFile(D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000703}
704
Chris Lattner3c799d72007-10-24 17:06:59 +0000705//===----------------------------------------------------------------------===//
706// Syntactic (non-AST) Rewriting Code
707//===----------------------------------------------------------------------===//
708
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000709void RewriteObjC::RewriteInclude() {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000710 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000711 llvm::StringRef MainBuf = SM->getBufferData(MainFileID);
712 const char *MainBufStart = MainBuf.begin();
713 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian80258362008-01-19 00:30:35 +0000714 size_t ImportLen = strlen("import");
Mike Stump11289f42009-09-09 15:08:12 +0000715
Fariborz Jahanian137d6932008-01-19 01:03:17 +0000716 // Loop over the whole file, looking for includes.
Fariborz Jahanian80258362008-01-19 00:30:35 +0000717 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
718 if (*BufPtr == '#') {
719 if (++BufPtr == MainBufEnd)
720 return;
721 while (*BufPtr == ' ' || *BufPtr == '\t')
722 if (++BufPtr == MainBufEnd)
723 return;
724 if (!strncmp(BufPtr, "import", ImportLen)) {
725 // replace import with include
Mike Stump11289f42009-09-09 15:08:12 +0000726 SourceLocation ImportLoc =
Fariborz Jahanian80258362008-01-19 00:30:35 +0000727 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000728 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian80258362008-01-19 00:30:35 +0000729 BufPtr += ImportLen;
730 }
731 }
732 }
Chris Lattner0bd1c972007-10-16 21:07:07 +0000733}
734
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000735void RewriteObjC::RewriteTabs() {
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000736 llvm::StringRef MainBuf = SM->getBufferData(MainFileID);
737 const char *MainBufStart = MainBuf.begin();
738 const char *MainBufEnd = MainBuf.end();
Mike Stump11289f42009-09-09 15:08:12 +0000739
Chris Lattner3c799d72007-10-24 17:06:59 +0000740 // Loop over the whole file, looking for tabs.
741 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
742 if (*BufPtr != '\t')
743 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000744
Chris Lattner3c799d72007-10-24 17:06:59 +0000745 // Okay, we found a tab. This tab will turn into at least one character,
746 // but it depends on which 'virtual column' it is in. Compute that now.
747 unsigned VCol = 0;
748 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
749 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
750 ++VCol;
Mike Stump11289f42009-09-09 15:08:12 +0000751
Chris Lattner3c799d72007-10-24 17:06:59 +0000752 // Okay, now that we know the virtual column, we know how many spaces to
753 // insert. We assume 8-character tab-stops.
754 unsigned Spaces = 8-(VCol & 7);
Mike Stump11289f42009-09-09 15:08:12 +0000755
Chris Lattner3c799d72007-10-24 17:06:59 +0000756 // Get the location of the tab.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000757 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
758 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Mike Stump11289f42009-09-09 15:08:12 +0000759
Chris Lattner3c799d72007-10-24 17:06:59 +0000760 // Rewrite the single tab character into a sequence of spaces.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000761 ReplaceText(TabLoc, 1, llvm::StringRef(" ", Spaces));
Chris Lattner3c799d72007-10-24 17:06:59 +0000762 }
Chris Lattner16a0de42007-10-11 18:38:32 +0000763}
764
Steve Naroff9af94912008-12-02 15:48:25 +0000765static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
766 ObjCIvarDecl *OID) {
767 std::string S;
768 S = "((struct ";
769 S += ClassDecl->getIdentifier()->getName();
770 S += "_IMPL *)self)->";
Daniel Dunbar70e7ead2009-10-18 20:26:27 +0000771 S += OID->getName();
Steve Naroff9af94912008-12-02 15:48:25 +0000772 return S;
773}
774
Steve Naroffc038b3a2008-12-02 17:36:43 +0000775void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
776 ObjCImplementationDecl *IMD,
777 ObjCCategoryImplDecl *CID) {
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000778 static bool objcGetPropertyDefined = false;
779 static bool objcSetPropertyDefined = false;
Steve Naroffe1908e32008-12-01 20:33:01 +0000780 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000781 InsertText(startLoc, "// ");
Steve Naroff9af94912008-12-02 15:48:25 +0000782 const char *startBuf = SM->getCharacterData(startLoc);
783 assert((*startBuf == '@') && "bogus @synthesize location");
784 const char *semiBuf = strchr(startBuf, ';');
785 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek5a201952009-02-07 01:47:29 +0000786 SourceLocation onePastSemiLoc =
787 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroff9af94912008-12-02 15:48:25 +0000788
789 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
790 return; // FIXME: is this correct?
Mike Stump11289f42009-09-09 15:08:12 +0000791
Steve Naroff9af94912008-12-02 15:48:25 +0000792 // Generate the 'getter' function.
Steve Naroff9af94912008-12-02 15:48:25 +0000793 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroff9af94912008-12-02 15:48:25 +0000794 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroff9af94912008-12-02 15:48:25 +0000795 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000796
Steve Naroff003d00e2008-12-02 16:05:55 +0000797 if (!OID)
798 return;
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000799 unsigned Attributes = PD->getPropertyAttributes();
800 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
801 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
802 ObjCPropertyDecl::OBJC_PR_copy));
Steve Naroff003d00e2008-12-02 16:05:55 +0000803 std::string Getr;
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000804 if (GenGetProperty && !objcGetPropertyDefined) {
805 objcGetPropertyDefined = true;
806 // FIXME. Is this attribute correct in all cases?
807 Getr = "\nextern \"C\" __declspec(dllimport) "
808 "id objc_getProperty(id, SEL, long, bool);\n";
809 }
Steve Naroff003d00e2008-12-02 16:05:55 +0000810 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
811 Getr += "{ ";
812 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroff06297042008-12-02 17:54:50 +0000813 // See objc-act.c:objc_synthesize_new_getter() for details.
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000814 if (GenGetProperty) {
815 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
816 Getr += "typedef ";
817 const FunctionType *FPRetType = 0;
818 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
819 FPRetType);
820 Getr += " _TYPE";
821 if (FPRetType) {
822 Getr += ")"; // close the precedence "scope" for "*".
823
824 // Now, emit the argument types (if any).
825 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
826 Getr += "(";
827 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
828 if (i) Getr += ", ";
829 std::string ParamStr = FT->getArgType(i).getAsString();
830 Getr += ParamStr;
831 }
832 if (FT->isVariadic()) {
833 if (FT->getNumArgs()) Getr += ", ";
834 Getr += "...";
835 }
836 Getr += ")";
837 } else
838 Getr += "()";
839 }
840 Getr += ";\n";
841 Getr += "return (_TYPE)";
842 Getr += "objc_getProperty(self, _cmd, ";
843 SynthesizeIvarOffsetComputation(ClassDecl, OID, Getr);
844 Getr += ", 1)";
845 }
846 else
847 Getr += "return " + getIvarAccessString(ClassDecl, OID);
Steve Naroff003d00e2008-12-02 16:05:55 +0000848 Getr += "; }";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000849 InsertText(onePastSemiLoc, Getr);
Steve Naroff9af94912008-12-02 15:48:25 +0000850 if (PD->isReadOnly())
851 return;
Mike Stump11289f42009-09-09 15:08:12 +0000852
Steve Naroff9af94912008-12-02 15:48:25 +0000853 // Generate the 'setter' function.
854 std::string Setr;
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000855 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
856 ObjCPropertyDecl::OBJC_PR_copy);
857 if (GenSetProperty && !objcSetPropertyDefined) {
858 objcSetPropertyDefined = true;
859 // FIXME. Is this attribute correct in all cases?
860 Setr = "\nextern \"C\" __declspec(dllimport) "
861 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
862 }
863
Steve Naroff9af94912008-12-02 15:48:25 +0000864 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroff9af94912008-12-02 15:48:25 +0000865 Setr += "{ ";
Steve Naroff003d00e2008-12-02 16:05:55 +0000866 // Synthesize an explicit cast to initialize the ivar.
Steve Narofff326f402008-12-03 00:56:33 +0000867 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000868 if (GenSetProperty) {
869 Setr += "objc_setProperty (self, _cmd, ";
870 SynthesizeIvarOffsetComputation(ClassDecl, OID, Setr);
871 Setr += ", (id)";
872 Setr += PD->getNameAsCString();
873 Setr += ", ";
874 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
875 Setr += "0, ";
876 else
877 Setr += "1, ";
878 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
879 Setr += "1)";
880 else
881 Setr += "0)";
882 }
883 else {
884 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
885 Setr += PD->getNameAsCString();
886 }
Steve Naroff003d00e2008-12-02 16:05:55 +0000887 Setr += "; }";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000888 InsertText(onePastSemiLoc, Setr);
Steve Naroffe1908e32008-12-01 20:33:01 +0000889}
Chris Lattner16a0de42007-10-11 18:38:32 +0000890
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000891void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattner3c799d72007-10-24 17:06:59 +0000892 // Get the start location and compute the semi location.
893 SourceLocation startLoc = ClassDecl->getLocation();
894 const char *startBuf = SM->getCharacterData(startLoc);
895 const char *semiPtr = strchr(startBuf, ';');
Mike Stump11289f42009-09-09 15:08:12 +0000896
Chris Lattner3c799d72007-10-24 17:06:59 +0000897 // Translate to typedef's that forward reference structs with the same name
898 // as the class. As a convenience, we include the original declaration
899 // as a comment.
900 std::string typedefString;
Fariborz Jahanian1c2cb6d2010-01-11 22:48:40 +0000901 typedefString += "// @class ";
902 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
903 I != E; ++I) {
904 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
905 typedefString += ForwardDecl->getNameAsString();
906 if (I+1 != E)
907 typedefString += ", ";
908 else
909 typedefString += ";\n";
910 }
911
Chris Lattner9ee23b72009-02-20 18:04:31 +0000912 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
913 I != E; ++I) {
Ted Kremenek9b124e12009-11-18 00:28:11 +0000914 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff1b232132007-11-09 12:50:28 +0000915 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000916 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000917 typedefString += "\n";
918 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000919 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000920 typedefString += "\n";
Steve Naroff98eb8d12007-11-05 14:36:37 +0000921 typedefString += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000922 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000923 typedefString += ";\n#endif\n";
Steve Naroff574440f2007-10-24 22:48:43 +0000924 }
Mike Stump11289f42009-09-09 15:08:12 +0000925
Steve Naroff574440f2007-10-24 22:48:43 +0000926 // Replace the @class with typedefs corresponding to the classes.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000927 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
Chris Lattner3c799d72007-10-24 17:06:59 +0000928}
929
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000930void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000931 // When method is a synthesized one, such as a getter/setter there is
932 // nothing to rewrite.
933 if (Method->isSynthesized())
934 return;
Steve Naroff3ce37a62007-12-14 23:37:57 +0000935 SourceLocation LocStart = Method->getLocStart();
936 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000937
Chris Lattner88ea93e2009-02-04 01:06:56 +0000938 if (SM->getInstantiationLineNumber(LocEnd) >
939 SM->getInstantiationLineNumber(LocStart)) {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000940 InsertText(LocStart, "#if 0\n");
941 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff3ce37a62007-12-14 23:37:57 +0000942 } else {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000943 InsertText(LocStart, "// ");
Steve Naroff5448cf62007-10-30 13:30:57 +0000944 }
945}
946
Mike Stump11289f42009-09-09 15:08:12 +0000947void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000948 SourceLocation Loc = prop->getAtLoc();
Mike Stump11289f42009-09-09 15:08:12 +0000949
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000950 ReplaceText(Loc, 0, "// ");
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000951 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahaniane8a30162007-11-07 00:09:37 +0000952}
953
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000954void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000955 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000956
Steve Naroff5448cf62007-10-30 13:30:57 +0000957 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000958 ReplaceText(LocStart, 0, "// ");
Mike Stump11289f42009-09-09 15:08:12 +0000959
Fariborz Jahanian68ebe632010-02-10 01:15:09 +0000960 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
961 E = CatDecl->prop_end(); I != E; ++I)
962 RewriteProperty(*I);
963
Mike Stump11289f42009-09-09 15:08:12 +0000964 for (ObjCCategoryDecl::instmeth_iterator
965 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000966 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000967 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +0000968 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000969 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000970 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000971 RewriteMethodDeclaration(*I);
972
Steve Naroff5448cf62007-10-30 13:30:57 +0000973 // Lastly, comment out the @end.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000974 ReplaceText(CatDecl->getAtEndRange().getBegin(), 0, "// ");
Steve Naroff5448cf62007-10-30 13:30:57 +0000975}
976
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000977void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Narofff921385f2007-10-30 16:42:30 +0000978 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000979
Steve Narofff921385f2007-10-30 16:42:30 +0000980 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000981 ReplaceText(LocStart, 0, "// ");
Mike Stump11289f42009-09-09 15:08:12 +0000982
983 for (ObjCProtocolDecl::instmeth_iterator
984 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000985 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000986 RewriteMethodDeclaration(*I);
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000987 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000988 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000989 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000990 RewriteMethodDeclaration(*I);
991
Steve Narofff921385f2007-10-30 16:42:30 +0000992 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +0000993 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000994 ReplaceText(LocEnd, 0, "// ");
Steve Naroffa509f042007-11-14 15:03:57 +0000995
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000996 // Must comment out @optional/@required
997 const char *startBuf = SM->getCharacterData(LocStart);
998 const char *endBuf = SM->getCharacterData(LocEnd);
999 for (const char *p = startBuf; p < endBuf; p++) {
1000 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Steve Naroffa509f042007-11-14 15:03:57 +00001001 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001002 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump11289f42009-09-09 15:08:12 +00001003
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +00001004 }
1005 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Steve Naroffa509f042007-11-14 15:03:57 +00001006 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001007 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump11289f42009-09-09 15:08:12 +00001008
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +00001009 }
1010 }
Steve Narofff921385f2007-10-30 16:42:30 +00001011}
1012
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001013void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanianda6165c2007-11-14 00:42:16 +00001014 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffc17b0562007-11-14 03:37:28 +00001015 if (LocStart.isInvalid())
1016 assert(false && "Invalid SourceLocation");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +00001017 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001018 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +00001019}
1020
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001021void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1022 const FunctionType *&FPRetType) {
1023 if (T->isObjCQualifiedIdType())
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +00001024 ResultStr += "id";
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001025 else if (T->isFunctionPointerType() ||
1026 T->isBlockPointerType()) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001027 // needs special handling, since pointer-to-functions have special
1028 // syntax (where a decaration models use).
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001029 QualType retType = T;
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001030 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001031 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001032 PointeeTy = PT->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001033 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001034 PointeeTy = BPT->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00001035 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001036 ResultStr += FPRetType->getResultType().getAsString();
1037 ResultStr += "(*";
Steve Naroffb067bbd2008-07-16 14:40:40 +00001038 }
1039 } else
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001040 ResultStr += T.getAsString();
1041}
1042
1043void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
1044 std::string &ResultStr) {
1045 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1046 const FunctionType *FPRetType = 0;
1047 ResultStr += "\nstatic ";
1048 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001049 ResultStr += " ";
Mike Stump11289f42009-09-09 15:08:12 +00001050
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001051 // Unique method name
Fariborz Jahanian56338352007-11-13 21:02:00 +00001052 std::string NameStr;
Mike Stump11289f42009-09-09 15:08:12 +00001053
Douglas Gregorffca3a22009-01-09 17:18:27 +00001054 if (OMD->isInstanceMethod())
Fariborz Jahanian56338352007-11-13 21:02:00 +00001055 NameStr += "_I_";
1056 else
1057 NameStr += "_C_";
Mike Stump11289f42009-09-09 15:08:12 +00001058
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001059 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +00001060 NameStr += "_";
Mike Stump11289f42009-09-09 15:08:12 +00001061
1062 if (ObjCCategoryImplDecl *CID =
Steve Naroff11b387f2009-01-08 19:41:02 +00001063 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001064 NameStr += CID->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +00001065 NameStr += "_";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001066 }
Mike Stump11289f42009-09-09 15:08:12 +00001067 // Append selector names, replacing ':' with '_'
Chris Lattnere4b95692008-11-24 03:33:13 +00001068 {
1069 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001070 int len = selString.size();
1071 for (int i = 0; i < len; i++)
1072 if (selString[i] == ':')
1073 selString[i] = '_';
Fariborz Jahanian56338352007-11-13 21:02:00 +00001074 NameStr += selString;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001075 }
Fariborz Jahanian56338352007-11-13 21:02:00 +00001076 // Remember this name for metadata emission
1077 MethodInternalNames[OMD] = NameStr;
1078 ResultStr += NameStr;
Mike Stump11289f42009-09-09 15:08:12 +00001079
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001080 // Rewrite arguments
1081 ResultStr += "(";
Mike Stump11289f42009-09-09 15:08:12 +00001082
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001083 // invisible arguments
Douglas Gregorffca3a22009-01-09 17:18:27 +00001084 if (OMD->isInstanceMethod()) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001085 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001086 selfTy = Context->getPointerType(selfTy);
Steve Naroffdc5b6b22008-03-12 00:25:36 +00001087 if (!LangOpts.Microsoft) {
1088 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
1089 ResultStr += "struct ";
1090 }
1091 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001092 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00001093 ResultStr += " *";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001094 }
1095 else
Steve Naroffd9803712009-04-29 16:37:50 +00001096 ResultStr += Context->getObjCClassType().getAsString();
Mike Stump11289f42009-09-09 15:08:12 +00001097
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001098 ResultStr += " self, ";
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001099 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001100 ResultStr += " _cmd";
Mike Stump11289f42009-09-09 15:08:12 +00001101
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001102 // Method arguments.
Chris Lattnera4997152009-02-20 18:43:26 +00001103 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1104 E = OMD->param_end(); PI != E; ++PI) {
1105 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001106 ResultStr += ", ";
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001107 if (PDecl->getType()->isObjCQualifiedIdType()) {
1108 ResultStr += "id ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001109 ResultStr += PDecl->getNameAsString();
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001110 } else {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001111 std::string Name = PDecl->getNameAsString();
Steve Naroffa5c0db82008-12-11 21:05:33 +00001112 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroff44df6a22008-10-30 14:45:29 +00001113 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001114 const BlockPointerType *BPT = PDecl->getType()->getAs<BlockPointerType>();
Douglas Gregor7de59662009-05-29 20:38:28 +00001115 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name,
1116 Context->PrintingPolicy);
Steve Naroff44df6a22008-10-30 14:45:29 +00001117 } else
Douglas Gregor7de59662009-05-29 20:38:28 +00001118 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001119 ResultStr += Name;
1120 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001121 }
Fariborz Jahanianeab81cd2008-01-21 20:14:23 +00001122 if (OMD->isVariadic())
1123 ResultStr += ", ...";
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001124 ResultStr += ") ";
Mike Stump11289f42009-09-09 15:08:12 +00001125
Steve Naroffb067bbd2008-07-16 14:40:40 +00001126 if (FPRetType) {
1127 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump11289f42009-09-09 15:08:12 +00001128
Steve Naroffb067bbd2008-07-16 14:40:40 +00001129 // Now, emit the argument types (if any).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001130 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001131 ResultStr += "(";
1132 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1133 if (i) ResultStr += ", ";
1134 std::string ParamStr = FT->getArgType(i).getAsString();
1135 ResultStr += ParamStr;
1136 }
1137 if (FT->isVariadic()) {
1138 if (FT->getNumArgs()) ResultStr += ", ";
1139 ResultStr += "...";
1140 }
1141 ResultStr += ")";
1142 } else {
1143 ResultStr += "()";
1144 }
1145 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001146}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001147void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001148 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1149 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump11289f42009-09-09 15:08:12 +00001150
Fariborz Jahanian02d964b2010-02-15 21:11:41 +00001151 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump11289f42009-09-09 15:08:12 +00001152
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001153 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001154 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1155 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001156 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001157 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001158 ObjCMethodDecl *OMD = *I;
1159 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001160 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001161 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redla7b98a72009-04-26 20:35:05 +00001162
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001163 const char *startBuf = SM->getCharacterData(LocStart);
1164 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001165 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001166 }
Mike Stump11289f42009-09-09 15:08:12 +00001167
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001168 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001169 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1170 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001171 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001172 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001173 ObjCMethodDecl *OMD = *I;
1174 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001175 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001176 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +00001177
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001178 const char *startBuf = SM->getCharacterData(LocStart);
1179 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001180 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001181 }
Steve Naroffe1908e32008-12-01 20:33:01 +00001182 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001183 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001184 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001185 I != E; ++I) {
Steve Naroffc038b3a2008-12-02 17:36:43 +00001186 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffe1908e32008-12-01 20:33:01 +00001187 }
1188
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001189 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001190}
1191
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001192void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffc5484042007-10-30 02:23:23 +00001193 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001194 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff2f55b982007-11-01 03:35:41 +00001195 // we haven't seen a forward decl - generate a typedef.
Steve Naroff03f27672007-11-14 23:02:56 +00001196 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001197 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001198 ResultStr += "\n";
1199 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001200 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001201 ResultStr += "\n";
Steve Naroffa1e115e2008-03-10 23:16:54 +00001202 ResultStr += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001203 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001204 ResultStr += ";\n#endif\n";
Steve Naroff2f55b982007-11-01 03:35:41 +00001205 // Mark this typedef as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001206 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff2f55b982007-11-01 03:35:41 +00001207 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001208 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump11289f42009-09-09 15:08:12 +00001209
1210 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001211 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff0c0f5ba2009-01-11 01:06:09 +00001212 RewriteProperty(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001213 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001214 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001215 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001216 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001217 for (ObjCInterfaceDecl::classmeth_iterator
1218 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001219 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001220 RewriteMethodDeclaration(*I);
1221
Steve Naroff4cd61ac2007-10-30 03:43:13 +00001222 // Lastly, comment out the @end.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001223 ReplaceText(ClassDecl->getAtEndRange().getBegin(), 0, "// ");
Steve Naroff161a92b2007-10-26 20:53:56 +00001224}
1225
Steve Naroff08628db2008-12-09 12:56:34 +00001226Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1227 SourceRange SrcRange) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00001228 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1229 // This allows us to reuse all the fun and games in SynthMessageExpr().
1230 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1231 ObjCMessageExpr *MsgExpr;
1232 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1233 llvm::SmallVector<Expr *, 1> ExprVec;
1234 ExprVec.push_back(newStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001235
Steve Naroff1042ff32008-12-08 16:43:47 +00001236 Stmt *Receiver = PropRefExpr->getBase();
1237 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1238 if (PRE && PropGetters[PRE]) {
1239 // This allows us to handle chain/nested property getters.
1240 Receiver = PropGetters[PRE];
1241 }
Ted Kremenek2c809302010-02-11 22:41:21 +00001242 MsgExpr = new (Context) ObjCMessageExpr(*Context, dyn_cast<Expr>(Receiver),
Mike Stump11289f42009-09-09 15:08:12 +00001243 PDecl->getSetterName(), PDecl->getType(),
1244 PDecl->getSetterMethodDecl(),
1245 SourceLocation(), SourceLocation(),
Steve Naroff4588d0f2008-12-04 16:24:46 +00001246 &ExprVec[0], 1);
1247 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001248
Steve Naroff4588d0f2008-12-04 16:24:46 +00001249 // Now do the actual rewrite.
Steve Naroff08628db2008-12-09 12:56:34 +00001250 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffdf705772008-12-10 14:53:27 +00001251 //delete BinOp;
Ted Kremenek5a201952009-02-07 01:47:29 +00001252 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1253 // to things that stay around.
1254 Context->Deallocate(MsgExpr);
Steve Naroff4588d0f2008-12-04 16:24:46 +00001255 return ReplacingStmt;
Steve Narofff326f402008-12-03 00:56:33 +00001256}
1257
Steve Naroff4588d0f2008-12-04 16:24:46 +00001258Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Narofff326f402008-12-03 00:56:33 +00001259 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1260 // This allows us to reuse all the fun and games in SynthMessageExpr().
1261 ObjCMessageExpr *MsgExpr;
1262 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
Mike Stump11289f42009-09-09 15:08:12 +00001263
Steve Naroff1042ff32008-12-08 16:43:47 +00001264 Stmt *Receiver = PropRefExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00001265
Steve Naroff1042ff32008-12-08 16:43:47 +00001266 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1267 if (PRE && PropGetters[PRE]) {
1268 // This allows us to handle chain/nested property getters.
1269 Receiver = PropGetters[PRE];
1270 }
Ted Kremenek2c809302010-02-11 22:41:21 +00001271 MsgExpr = new (Context) ObjCMessageExpr(*Context, dyn_cast<Expr>(Receiver),
Mike Stump11289f42009-09-09 15:08:12 +00001272 PDecl->getGetterName(), PDecl->getType(),
1273 PDecl->getGetterMethodDecl(),
1274 SourceLocation(), SourceLocation(),
Steve Narofff326f402008-12-03 00:56:33 +00001275 0, 0);
1276
Steve Naroff22216db2008-12-04 23:50:32 +00001277 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001278
1279 if (!PropParentMap)
1280 PropParentMap = new ParentMap(CurrentBody);
1281
1282 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1283 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1284 // We stash away the ReplacingStmt since actually doing the
1285 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1286 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek5a201952009-02-07 01:47:29 +00001287 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1288 // to things that stay around.
1289 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001290 return PropRefExpr; // return the original...
1291 } else {
1292 ReplaceStmt(PropRefExpr, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001293 // delete PropRefExpr; elsewhere...
Ted Kremenek5a201952009-02-07 01:47:29 +00001294 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1295 // to things that stay around.
1296 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001297 return ReplacingStmt;
1298 }
Steve Narofff326f402008-12-03 00:56:33 +00001299}
1300
Mike Stump11289f42009-09-09 15:08:12 +00001301Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001302 SourceLocation OrigStart,
1303 bool &replaced) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001304 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001305 const Expr *BaseExpr = IV->getBase();
Steve Naroff677ab3a2008-10-27 17:20:55 +00001306 if (CurMethodDef) {
Fariborz Jahanianf9e8c2b2010-01-26 18:28:51 +00001307 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001308 ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001309 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianf0ed69c2010-01-26 20:37:44 +00001310 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Naroffb1c02372008-05-08 17:52:16 +00001311 // lookup which class implements the instance variable.
1312 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001313 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001314 clsDeclared);
Steve Naroffb1c02372008-05-08 17:52:16 +00001315 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001316
Steve Naroffb1c02372008-05-08 17:52:16 +00001317 // Synthesize an explicit cast to gain access to the ivar.
1318 std::string RecName = clsDeclared->getIdentifier()->getName();
1319 RecName += "_IMPL";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001320 IdentifierInfo *II = &Context->Idents.get(RecName);
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001321 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001322 SourceLocation(), II);
Steve Naroffb1c02372008-05-08 17:52:16 +00001323 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1324 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall97513962010-01-15 18:39:57 +00001325 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1326 CastExpr::CK_Unknown,
1327 IV->getBase());
Steve Naroffb1c02372008-05-08 17:52:16 +00001328 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001329 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1330 IV->getBase()->getLocEnd(),
1331 castExpr);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001332 replaced = true;
Mike Stump11289f42009-09-09 15:08:12 +00001333 if (IV->isFreeIvar() &&
Steve Naroff677ab3a2008-10-27 17:20:55 +00001334 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001335 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1336 IV->getLocation(),
1337 D->getType());
Steve Naroff22216db2008-12-04 23:50:32 +00001338 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb1c02372008-05-08 17:52:16 +00001339 return ME;
Steve Naroff05caa482007-11-15 11:33:00 +00001340 }
Fariborz Jahanian81310812010-01-28 01:41:20 +00001341 // Get the new text
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001342 // Cannot delete IV->getBase(), since PE points to it.
1343 // Replace the old base with the cast. This is important when doing
1344 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001345 IV->setBase(PE);
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001346 return IV;
Steve Naroff05caa482007-11-15 11:33:00 +00001347 }
Steve Naroff24840f62008-04-18 21:55:08 +00001348 } else { // we are outside a method.
Steve Naroff29ce4e52008-05-06 23:20:07 +00001349 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump11289f42009-09-09 15:08:12 +00001350
Steve Naroff29ce4e52008-05-06 23:20:07 +00001351 // Explicit ivar refs need to have a cast inserted.
1352 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian12e2e862010-01-12 17:31:23 +00001353 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Fariborz Jahanian9146e442010-01-11 17:50:35 +00001354 ObjCInterfaceType *iFaceDecl =
1355 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001356 // lookup which class implements the instance variable.
1357 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001358 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001359 clsDeclared);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001360 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001361
Steve Naroff29ce4e52008-05-06 23:20:07 +00001362 // Synthesize an explicit cast to gain access to the ivar.
1363 std::string RecName = clsDeclared->getIdentifier()->getName();
1364 RecName += "_IMPL";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001365 IdentifierInfo *II = &Context->Idents.get(RecName);
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001366 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001367 SourceLocation(), II);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001368 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1369 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall97513962010-01-15 18:39:57 +00001370 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1371 CastExpr::CK_Unknown,
1372 IV->getBase());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001373 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001374 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner34873d22008-05-28 16:38:23 +00001375 IV->getBase()->getLocEnd(), castExpr);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001376 replaced = true;
Steve Naroff29ce4e52008-05-06 23:20:07 +00001377 // Cannot delete IV->getBase(), since PE points to it.
1378 // Replace the old base with the cast. This is important when doing
1379 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001380 IV->setBase(PE);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001381 return IV;
1382 }
Steve Naroff05caa482007-11-15 11:33:00 +00001383 }
Steve Naroff24840f62008-04-18 21:55:08 +00001384 return IV;
Steve Narofff60782b2007-11-15 02:58:25 +00001385}
1386
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001387Stmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) {
1388 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1389 CI != E; ++CI) {
1390 if (*CI) {
1391 Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced);
1392 if (newStmt)
1393 *CI = newStmt;
1394 }
1395 }
1396 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
1397 SourceRange OrigStmtRange = S->getSourceRange();
1398 Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(),
1399 replaced);
1400 return newStmt;
Fariborz Jahanian31433382010-02-05 17:48:10 +00001401 }
1402 if (ObjCMessageExpr *MsgRefExpr = dyn_cast<ObjCMessageExpr>(S)) {
1403 Stmt *newStmt = SynthMessageExpr(MsgRefExpr);
1404 return newStmt;
1405 }
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001406 return S;
1407}
1408
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001409/// SynthCountByEnumWithState - To print:
1410/// ((unsigned int (*)
1411/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001412/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001413/// sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001414/// "countByEnumeratingWithState:objects:count:"),
1415/// &enumState,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001416/// (id *)items, (unsigned int)16)
1417///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001418void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001419 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1420 "id *, unsigned int))(void *)objc_msgSend)";
1421 buf += "\n\t\t";
1422 buf += "((id)l_collection,\n\t\t";
1423 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1424 buf += "\n\t\t";
1425 buf += "&enumState, "
1426 "(id *)items, (unsigned int)16)";
1427}
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001428
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001429/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1430/// statement to exit to its outer synthesized loop.
1431///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001432Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001433 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1434 return S;
1435 // replace break with goto __break_label
1436 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001437
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001438 SourceLocation startLoc = S->getLocStart();
1439 buf = "goto __break_label_";
1440 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001441 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001442
1443 return 0;
1444}
1445
1446/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1447/// statement to continue with its inner synthesized loop.
1448///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001449Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001450 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1451 return S;
1452 // replace continue with goto __continue_label
1453 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001454
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001455 SourceLocation startLoc = S->getLocStart();
1456 buf = "goto __continue_label_";
1457 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001458 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump11289f42009-09-09 15:08:12 +00001459
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001460 return 0;
1461}
1462
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001463/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001464/// It rewrites:
1465/// for ( type elem in collection) { stmts; }
Mike Stump11289f42009-09-09 15:08:12 +00001466
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001467/// Into:
1468/// {
Mike Stump11289f42009-09-09 15:08:12 +00001469/// type elem;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001470/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001471/// id items[16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001472/// id l_collection = (id)collection;
Mike Stump11289f42009-09-09 15:08:12 +00001473/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001474/// objects:items count:16];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001475/// if (limit) {
1476/// unsigned long startMutations = *enumState.mutationsPtr;
1477/// do {
1478/// unsigned long counter = 0;
1479/// do {
Mike Stump11289f42009-09-09 15:08:12 +00001480/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001481/// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001482/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001483/// stmts;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001484/// __continue_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001485/// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001486/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001487/// objects:items count:16]);
1488/// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001489/// __break_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001490/// }
1491/// else
1492/// elem = nil;
1493/// }
1494///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001495Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattnera779d692008-01-31 05:10:40 +00001496 SourceLocation OrigEnd) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001497 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001498 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001499 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump11289f42009-09-09 15:08:12 +00001500 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001501 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001502
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001503 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001504 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001505 const char *elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001506 std::string elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001507 std::string buf;
1508 buf = "\n{\n\t";
1509 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1510 // type elem;
Chris Lattner529efc72009-03-28 06:33:19 +00001511 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek292b3842008-10-06 22:16:13 +00001512 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001513 if (ElementType->isObjCQualifiedIdType() ||
1514 ElementType->isObjCQualifiedInterfaceType())
1515 // Simply use 'id' for all qualified types.
1516 elementTypeAsString = "id";
1517 else
1518 elementTypeAsString = ElementType.getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001519 buf += elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001520 buf += " ";
Chris Lattner86d7d912008-11-24 03:54:41 +00001521 elementName = D->getNameAsCString();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001522 buf += elementName;
1523 buf += ";\n\t";
1524 }
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001525 else {
1526 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner86d7d912008-11-24 03:54:41 +00001527 elementName = DR->getDecl()->getNameAsCString();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001528 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1529 if (VD->getType()->isObjCQualifiedIdType() ||
1530 VD->getType()->isObjCQualifiedInterfaceType())
1531 // Simply use 'id' for all qualified types.
1532 elementTypeAsString = "id";
1533 else
1534 elementTypeAsString = VD->getType().getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001535 }
Mike Stump11289f42009-09-09 15:08:12 +00001536
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001537 // struct __objcFastEnumerationState enumState = { 0 };
1538 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1539 // id items[16];
1540 buf += "id items[16];\n\t";
1541 // id l_collection = (id)
1542 buf += "id l_collection = (id)";
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001543 // Find start location of 'collection' the hard way!
1544 const char *startCollectionBuf = startBuf;
1545 startCollectionBuf += 3; // skip 'for'
1546 startCollectionBuf = strchr(startCollectionBuf, '(');
1547 startCollectionBuf++; // skip '('
1548 // find 'in' and skip it.
1549 while (*startCollectionBuf != ' ' ||
1550 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1551 (*(startCollectionBuf+3) != ' ' &&
1552 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1553 startCollectionBuf++;
1554 startCollectionBuf += 3;
Mike Stump11289f42009-09-09 15:08:12 +00001555
1556 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001557 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001558 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001559 SourceLocation rightParenLoc = S->getRParenLoc();
1560 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1561 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001562 buf = ";\n\t";
Mike Stump11289f42009-09-09 15:08:12 +00001563
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001564 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1565 // objects:items count:16];
1566 // which is synthesized into:
Mike Stump11289f42009-09-09 15:08:12 +00001567 // unsigned int limit =
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001568 // ((unsigned int (*)
1569 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001570 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001571 // sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001572 // "countByEnumeratingWithState:objects:count:"),
1573 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001574 // (id *)items, (unsigned int)16);
1575 buf += "unsigned long limit =\n\t\t";
1576 SynthCountByEnumWithState(buf);
1577 buf += ";\n\t";
1578 /// if (limit) {
1579 /// unsigned long startMutations = *enumState.mutationsPtr;
1580 /// do {
1581 /// unsigned long counter = 0;
1582 /// do {
Mike Stump11289f42009-09-09 15:08:12 +00001583 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001584 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001585 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001586 buf += "if (limit) {\n\t";
1587 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1588 buf += "do {\n\t\t";
1589 buf += "unsigned long counter = 0;\n\t\t";
1590 buf += "do {\n\t\t\t";
1591 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1592 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1593 buf += elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001594 buf += " = (";
1595 buf += elementTypeAsString;
1596 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001597 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001598 ReplaceText(lparenLoc, 1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001599
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001600 /// __continue_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001601 /// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001602 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001603 /// objects:items count:16]);
1604 /// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001605 /// __break_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001606 /// }
1607 /// else
1608 /// elem = nil;
1609 /// }
Mike Stump11289f42009-09-09 15:08:12 +00001610 ///
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001611 buf = ";\n\t";
1612 buf += "__continue_label_";
1613 buf += utostr(ObjCBcLabelNo.back());
1614 buf += ": ;";
1615 buf += "\n\t\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001616 buf += "} while (counter < limit);\n\t";
1617 buf += "} while (limit = ";
1618 SynthCountByEnumWithState(buf);
1619 buf += ");\n\t";
1620 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001621 buf += " = ((";
1622 buf += elementTypeAsString;
1623 buf += ")0);\n\t";
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001624 buf += "__break_label_";
1625 buf += utostr(ObjCBcLabelNo.back());
1626 buf += ": ;\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001627 buf += "}\n\t";
1628 buf += "else\n\t\t";
1629 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001630 buf += " = ((";
1631 buf += elementTypeAsString;
1632 buf += ")0);\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001633 buf += "}\n";
Mike Stump11289f42009-09-09 15:08:12 +00001634
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001635 // Insert all these *after* the statement body.
Sebastian Redla7b98a72009-04-26 20:35:05 +00001636 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Narofff0ff8792008-07-21 18:26:02 +00001637 if (isa<CompoundStmt>(S->getBody())) {
1638 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001639 InsertText(endBodyLoc, buf);
Steve Narofff0ff8792008-07-21 18:26:02 +00001640 } else {
1641 /* Need to treat single statements specially. For example:
1642 *
1643 * for (A *a in b) if (stuff()) break;
1644 * for (A *a in b) xxxyy;
1645 *
1646 * The following code simply scans ahead to the semi to find the actual end.
1647 */
1648 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1649 const char *semiBuf = strchr(stmtBuf, ';');
1650 assert(semiBuf && "Can't find ';'");
1651 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001652 InsertText(endBodyLoc, buf);
Steve Narofff0ff8792008-07-21 18:26:02 +00001653 }
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001654 Stmts.pop_back();
1655 ObjCBcLabelNo.pop_back();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001656 return 0;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001657}
1658
Mike Stump11289f42009-09-09 15:08:12 +00001659/// RewriteObjCSynchronizedStmt -
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001660/// This routine rewrites @synchronized(expr) stmt;
1661/// into:
1662/// objc_sync_enter(expr);
1663/// @try stmt @finally { objc_sync_exit(expr); }
1664///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001665Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001666 // Get the start location and compute the semi location.
1667 SourceLocation startLoc = S->getLocStart();
1668 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001669
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001670 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump11289f42009-09-09 15:08:12 +00001671
1672 std::string buf;
Steve Naroffb2fc0522008-08-21 13:03:03 +00001673 buf = "objc_sync_enter((id)";
1674 const char *lparenBuf = startBuf;
1675 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001676 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001677 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1678 // the sync expression is typically a message expression that's already
Steve Naroffad7013b2008-08-19 13:04:19 +00001679 // been rewritten! (which implies the SourceLocation's are invalid).
1680 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001681 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffad7013b2008-08-19 13:04:19 +00001682 while (*endBuf != ')') endBuf--;
1683 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001684 buf = ");\n";
1685 // declare a new scope with two variables, _stack and _rethrow.
1686 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1687 buf += "int buf[18/*32-bit i386*/];\n";
1688 buf += "char *pointers[4];} _stack;\n";
1689 buf += "id volatile _rethrow = 0;\n";
1690 buf += "objc_exception_try_enter(&_stack);\n";
1691 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001692 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001693 startLoc = S->getSynchBody()->getLocEnd();
1694 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001695
Steve Naroffad7013b2008-08-19 13:04:19 +00001696 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001697 SourceLocation lastCurlyLoc = startLoc;
1698 buf = "}\nelse {\n";
1699 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroffd9803712009-04-29 16:37:50 +00001700 buf += "}\n";
1701 buf += "{ /* implicit finally clause */\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001702 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffec60b432009-12-05 21:43:12 +00001703
1704 std::string syncBuf;
1705 syncBuf += " objc_sync_exit(";
John McCall97513962010-01-15 18:39:57 +00001706 Expr *syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1707 CastExpr::CK_Unknown,
1708 S->getSynchExpr());
Ted Kremenek2d470fc2008-09-13 05:16:45 +00001709 std::string syncExprBufS;
1710 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00001711 syncExpr->printPretty(syncExprBuf, *Context, 0,
1712 PrintingPolicy(LangOpts));
Steve Naroffec60b432009-12-05 21:43:12 +00001713 syncBuf += syncExprBuf.str();
1714 syncBuf += ");";
1715
1716 buf += syncBuf;
1717 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001718 buf += "}\n";
1719 buf += "}";
Mike Stump11289f42009-09-09 15:08:12 +00001720
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001721 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffec60b432009-12-05 21:43:12 +00001722
1723 bool hasReturns = false;
1724 HasReturnStmts(S->getSynchBody(), hasReturns);
1725 if (hasReturns)
1726 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1727
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001728 return 0;
1729}
1730
Steve Naroffec60b432009-12-05 21:43:12 +00001731void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1732{
Steve Naroff6d6da252008-12-05 17:03:39 +00001733 // Perform a bottom up traversal of all children.
1734 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1735 CI != E; ++CI)
1736 if (*CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001737 WarnAboutReturnGotoStmts(*CI);
Steve Naroff6d6da252008-12-05 17:03:39 +00001738
Steve Naroffec60b432009-12-05 21:43:12 +00001739 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump11289f42009-09-09 15:08:12 +00001740 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff6d6da252008-12-05 17:03:39 +00001741 TryFinallyContainsReturnDiag);
1742 }
1743 return;
1744}
1745
Steve Naroffec60b432009-12-05 21:43:12 +00001746void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1747{
1748 // Perform a bottom up traversal of all children.
1749 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1750 CI != E; ++CI)
1751 if (*CI)
1752 HasReturnStmts(*CI, hasReturns);
1753
1754 if (isa<ReturnStmt>(S))
1755 hasReturns = true;
1756 return;
1757}
1758
1759void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1760 // Perform a bottom up traversal of all children.
1761 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1762 CI != E; ++CI)
1763 if (*CI) {
1764 RewriteTryReturnStmts(*CI);
1765 }
1766 if (isa<ReturnStmt>(S)) {
1767 SourceLocation startLoc = S->getLocStart();
1768 const char *startBuf = SM->getCharacterData(startLoc);
1769
1770 const char *semiBuf = strchr(startBuf, ';');
1771 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1772 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1773
1774 std::string buf;
1775 buf = "{ objc_exception_try_exit(&_stack); return";
1776
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001777 ReplaceText(startLoc, 6, buf);
1778 InsertText(onePastSemiLoc, "}");
Steve Naroffec60b432009-12-05 21:43:12 +00001779 }
1780 return;
1781}
1782
1783void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1784 // Perform a bottom up traversal of all children.
1785 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1786 CI != E; ++CI)
1787 if (*CI) {
1788 RewriteSyncReturnStmts(*CI, syncExitBuf);
1789 }
1790 if (isa<ReturnStmt>(S)) {
1791 SourceLocation startLoc = S->getLocStart();
1792 const char *startBuf = SM->getCharacterData(startLoc);
1793
1794 const char *semiBuf = strchr(startBuf, ';');
1795 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1796 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1797
1798 std::string buf;
1799 buf = "{ objc_exception_try_exit(&_stack);";
1800 buf += syncExitBuf;
1801 buf += " return";
1802
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001803 ReplaceText(startLoc, 6, buf);
1804 InsertText(onePastSemiLoc, "}");
Steve Naroffec60b432009-12-05 21:43:12 +00001805 }
1806 return;
1807}
1808
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001809Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001810 // Get the start location and compute the semi location.
1811 SourceLocation startLoc = S->getLocStart();
1812 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001813
Steve Naroffbf478ec2007-11-07 04:08:17 +00001814 assert((*startBuf == '@') && "bogus @try location");
1815
1816 std::string buf;
1817 // declare a new scope with two variables, _stack and _rethrow.
1818 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1819 buf += "int buf[18/*32-bit i386*/];\n";
1820 buf += "char *pointers[4];} _stack;\n";
1821 buf += "id volatile _rethrow = 0;\n";
1822 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff16018582007-11-07 18:43:40 +00001823 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffbf478ec2007-11-07 04:08:17 +00001824
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001825 ReplaceText(startLoc, 4, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001826
Steve Naroffbf478ec2007-11-07 04:08:17 +00001827 startLoc = S->getTryBody()->getLocEnd();
1828 startBuf = SM->getCharacterData(startLoc);
1829
1830 assert((*startBuf == '}') && "bogus @try block");
Mike Stump11289f42009-09-09 15:08:12 +00001831
Steve Naroffbf478ec2007-11-07 04:08:17 +00001832 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffce2dca12008-07-16 15:31:30 +00001833 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1834 if (catchList) {
1835 startLoc = startLoc.getFileLocWithOffset(1);
1836 buf = " /* @catch begin */ else {\n";
1837 buf += " id _caught = objc_exception_extract(&_stack);\n";
1838 buf += " objc_exception_try_enter (&_stack);\n";
1839 buf += " if (_setjmp(_stack.buf))\n";
1840 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1841 buf += " else { /* @catch continue */";
Mike Stump11289f42009-09-09 15:08:12 +00001842
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001843 InsertText(startLoc, buf);
Steve Narofffac18fe2008-09-09 19:59:12 +00001844 } else { /* no catch list */
1845 buf = "}\nelse {\n";
1846 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1847 buf += "}";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001848 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffce2dca12008-07-16 15:31:30 +00001849 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001850 bool sawIdTypedCatch = false;
1851 Stmt *lastCatchBody = 0;
Steve Naroffbf478ec2007-11-07 04:08:17 +00001852 while (catchList) {
Steve Naroff371b8fb2009-03-03 19:52:17 +00001853 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001854
Mike Stump11289f42009-09-09 15:08:12 +00001855 if (catchList == S->getCatchStmts())
Steve Naroffbf478ec2007-11-07 04:08:17 +00001856 buf = "if ("; // we are generating code for the first catch clause
1857 else
1858 buf = "else if (";
1859 startLoc = catchList->getLocStart();
1860 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001861
Steve Naroffbf478ec2007-11-07 04:08:17 +00001862 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump11289f42009-09-09 15:08:12 +00001863
Steve Naroffbf478ec2007-11-07 04:08:17 +00001864 const char *lParenLoc = strchr(startBuf, '(');
1865
Steve Naroffe6b7ffd2008-02-01 22:08:12 +00001866 if (catchList->hasEllipsis()) {
Steve Naroffedb5bc62008-02-01 20:02:07 +00001867 // Now rewrite the body...
1868 lastCatchBody = catchList->getCatchBody();
Steve Naroffedb5bc62008-02-01 20:02:07 +00001869 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1870 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001871 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1872 "bogus @catch paren location");
Steve Naroffedb5bc62008-02-01 20:02:07 +00001873 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001874
Steve Naroffedb5bc62008-02-01 20:02:07 +00001875 buf += "1) { id _tmp = _caught;";
Daniel Dunbardec484a2009-08-19 19:10:30 +00001876 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff371b8fb2009-03-03 19:52:17 +00001877 } else if (catchDecl) {
1878 QualType t = catchDecl->getType();
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001879 if (t == Context->getObjCIdType()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001880 buf += "1) { ";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001881 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroffbf478ec2007-11-07 04:08:17 +00001882 sawIdTypedCatch = true;
Fariborz Jahanian59516092010-01-12 01:22:23 +00001883 } else if (t->isObjCObjectPointerType()) {
1884 QualType InterfaceTy = t->getPointeeType();
1885 const ObjCInterfaceType *cls = // Should be a pointer to a class.
1886 InterfaceTy->getAs<ObjCInterfaceType>();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001887 if (cls) {
Steve Naroff16018582007-11-07 18:43:40 +00001888 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001889 buf += cls->getDecl()->getNameAsString();
Steve Naroff16018582007-11-07 18:43:40 +00001890 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001891 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroffbf478ec2007-11-07 04:08:17 +00001892 }
1893 }
1894 // Now rewrite the body...
1895 lastCatchBody = catchList->getCatchBody();
1896 SourceLocation rParenLoc = catchList->getRParenLoc();
1897 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1898 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1899 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1900 assert((*rParenBuf == ')') && "bogus @catch paren location");
1901 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001902
Mike Stump11289f42009-09-09 15:08:12 +00001903 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroffbf478ec2007-11-07 04:08:17 +00001904 // declares the @catch parameter).
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001905 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff371b8fb2009-03-03 19:52:17 +00001906 } else {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001907 assert(false && "@catch rewrite bug");
Steve Naroffa733c7f2007-11-07 15:32:26 +00001908 }
Steve Naroffedb5bc62008-02-01 20:02:07 +00001909 // make sure all the catch bodies get rewritten!
Steve Naroffbf478ec2007-11-07 04:08:17 +00001910 catchList = catchList->getNextCatchStmt();
1911 }
1912 // Complete the catch list...
1913 if (lastCatchBody) {
1914 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001915 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1916 "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001917
Steve Naroff4adbe312008-09-11 15:29:03 +00001918 // Insert the last (implicit) else clause *before* the right curly brace.
1919 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1920 buf = "} /* last catch end */\n";
1921 buf += "else {\n";
1922 buf += " _rethrow = _caught;\n";
1923 buf += " objc_exception_try_exit(&_stack);\n";
1924 buf += "} } /* @catch end */\n";
1925 if (!S->getFinallyStmt())
1926 buf += "}\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001927 InsertText(bodyLoc, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001928
Steve Naroffbf478ec2007-11-07 04:08:17 +00001929 // Set lastCurlyLoc
1930 lastCurlyLoc = lastCatchBody->getLocEnd();
1931 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001932 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001933 startLoc = finalStmt->getLocStart();
1934 startBuf = SM->getCharacterData(startLoc);
1935 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump11289f42009-09-09 15:08:12 +00001936
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001937 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump11289f42009-09-09 15:08:12 +00001938
Steve Naroffbf478ec2007-11-07 04:08:17 +00001939 Stmt *body = finalStmt->getFinallyBody();
1940 SourceLocation startLoc = body->getLocStart();
1941 SourceLocation endLoc = body->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001942 assert(*SM->getCharacterData(startLoc) == '{' &&
1943 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001944 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001945 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001946
Steve Naroffbf478ec2007-11-07 04:08:17 +00001947 startLoc = startLoc.getFileLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001948 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Steve Naroffbf478ec2007-11-07 04:08:17 +00001949 endLoc = endLoc.getFileLocWithOffset(-1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001950 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump11289f42009-09-09 15:08:12 +00001951
Steve Naroffbf478ec2007-11-07 04:08:17 +00001952 // Set lastCurlyLoc
1953 lastCurlyLoc = body->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00001954
Steve Naroff6d6da252008-12-05 17:03:39 +00001955 // Now check for any return/continue/go statements within the @try.
Steve Naroffec60b432009-12-05 21:43:12 +00001956 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff4adbe312008-09-11 15:29:03 +00001957 } else { /* no finally clause - make sure we synthesize an implicit one */
1958 buf = "{ /* implicit finally clause */\n";
1959 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1960 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1961 buf += "}";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001962 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffec60b432009-12-05 21:43:12 +00001963
1964 // Now check for any return/continue/go statements within the @try.
1965 // The implicit finally clause won't called if the @try contains any
1966 // jump statements.
1967 bool hasReturns = false;
1968 HasReturnStmts(S->getTryBody(), hasReturns);
1969 if (hasReturns)
1970 RewriteTryReturnStmts(S->getTryBody());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001971 }
1972 // Now emit the final closing curly brace...
1973 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001974 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001975 return 0;
1976}
1977
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001978Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001979 return 0;
1980}
1981
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001982Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001983 return 0;
1984}
1985
Mike Stump11289f42009-09-09 15:08:12 +00001986// This can't be done with ReplaceStmt(S, ThrowExpr), since
1987// the throw expression is typically a message expression that's already
Steve Naroffa733c7f2007-11-07 15:32:26 +00001988// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001989Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroffa733c7f2007-11-07 15:32:26 +00001990 // Get the start location and compute the semi location.
1991 SourceLocation startLoc = S->getLocStart();
1992 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001993
Steve Naroffa733c7f2007-11-07 15:32:26 +00001994 assert((*startBuf == '@') && "bogus @throw location");
1995
1996 std::string buf;
1997 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffc7d2df22008-01-19 00:42:38 +00001998 if (S->getThrowExpr())
1999 buf = "objc_exception_throw(";
2000 else // add an implicit argument
2001 buf = "objc_exception_throw(_caught";
Mike Stump11289f42009-09-09 15:08:12 +00002002
Steve Naroff29788342008-07-25 15:41:30 +00002003 // handle "@ throw" correctly.
2004 const char *wBuf = strchr(startBuf, 'w');
2005 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002006 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00002007
Steve Naroffa733c7f2007-11-07 15:32:26 +00002008 const char *semiBuf = strchr(startBuf, ';');
2009 assert((*semiBuf == ';') && "@throw: can't find ';'");
2010 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002011 ReplaceText(semiLoc, 1, ");");
Steve Naroffa733c7f2007-11-07 15:32:26 +00002012 return 0;
2013}
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00002014
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002015Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerc6d91c02007-10-17 22:35:30 +00002016 // Create a new string expression.
2017 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlssond8499822007-10-29 05:01:08 +00002018 std::string StrEncoding;
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00002019 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002020 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
2021 StrEncoding.length(), false,StrType,
2022 SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00002023 ReplaceStmt(Exp, Replacement);
Mike Stump11289f42009-09-09 15:08:12 +00002024
Chris Lattner4431a1b2007-11-30 22:53:43 +00002025 // Replace this subexpr in the parent.
Steve Naroff22216db2008-12-04 23:50:32 +00002026 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattner69534692007-10-24 16:57:36 +00002027 return Replacement;
Chris Lattnera7c19fe2007-10-16 22:36:42 +00002028}
2029
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002030Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff2654e182008-12-22 22:16:07 +00002031 if (!SelGetUidFunctionDecl)
2032 SynthSelGetUidFunctionDecl();
Steve Naroffe4f9b232007-11-05 14:50:49 +00002033 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2034 // Create a call to sel_registerName("selName").
2035 llvm::SmallVector<Expr*, 8> SelExprs;
2036 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002037 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00002038 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00002039 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00002040 false, argType, SourceLocation()));
Steve Naroffe4f9b232007-11-05 14:50:49 +00002041 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2042 &SelExprs[0], SelExprs.size());
Chris Lattner2e0d2602008-01-31 19:37:57 +00002043 ReplaceStmt(Exp, SelExp);
Steve Naroff22216db2008-12-04 23:50:32 +00002044 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffe4f9b232007-11-05 14:50:49 +00002045 return SelExp;
2046}
2047
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002048CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002049 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2050 SourceLocation EndLoc) {
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002051 // Get the type, we will need to reference it in a couple spots.
Steve Naroff574440f2007-10-24 22:48:43 +00002052 QualType msgSendType = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002053
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002054 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek5a201952009-02-07 01:47:29 +00002055 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002056
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002057 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattner3c799d72007-10-24 17:06:59 +00002058 QualType pToFunc = Context->getPointerType(msgSendType);
Mike Stump11289f42009-09-09 15:08:12 +00002059 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc,
Anders Carlssona2615922009-07-31 00:48:10 +00002060 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002061 DRE,
Douglas Gregora11693b2008-11-12 17:17:38 +00002062 /*isLvalue=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002063
John McCall9dd450b2009-09-21 23:43:11 +00002064 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00002065
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002066 CallExpr *Exp =
2067 new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
2068 EndLoc);
2069 return Exp;
Steve Naroff574440f2007-10-24 22:48:43 +00002070}
2071
Steve Naroff50d42052007-11-01 13:24:47 +00002072static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2073 const char *&startRef, const char *&endRef) {
2074 while (startBuf < endBuf) {
2075 if (*startBuf == '<')
2076 startRef = startBuf; // mark the start.
2077 if (*startBuf == '>') {
Steve Naroff1b232132007-11-09 12:50:28 +00002078 if (startRef && *startRef == '<') {
2079 endRef = startBuf; // mark the end.
2080 return true;
2081 }
2082 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002083 }
2084 startBuf++;
2085 }
2086 return false;
2087}
2088
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002089static void scanToNextArgument(const char *&argRef) {
2090 int angle = 0;
2091 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2092 if (*argRef == '<')
2093 angle++;
2094 else if (*argRef == '>')
2095 angle--;
2096 argRef++;
2097 }
2098 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2099}
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002100
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002101bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian80c54b02010-02-03 21:29:28 +00002102 if (T->isObjCQualifiedIdType())
2103 return true;
Fariborz Jahanian06769f92010-02-02 18:35:07 +00002104 if (const PointerType *PT = T->getAs<PointerType>()) {
2105 if (PT->getPointeeType()->isObjCQualifiedIdType())
2106 return true;
2107 }
2108 if (T->isObjCObjectPointerType()) {
2109 T = T->getPointeeType();
2110 return T->isObjCQualifiedInterfaceType();
2111 }
2112 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002113}
2114
Steve Naroff873bd842008-07-29 18:15:38 +00002115void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2116 QualType Type = E->getType();
2117 if (needToScanForQualifiers(Type)) {
Steve Naroffdbfc6932008-11-19 21:15:47 +00002118 SourceLocation Loc, EndLoc;
Mike Stump11289f42009-09-09 15:08:12 +00002119
Steve Naroffdbfc6932008-11-19 21:15:47 +00002120 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2121 Loc = ECE->getLParenLoc();
2122 EndLoc = ECE->getRParenLoc();
2123 } else {
2124 Loc = E->getLocStart();
2125 EndLoc = E->getLocEnd();
2126 }
2127 // This will defend against trying to rewrite synthesized expressions.
2128 if (Loc.isInvalid() || EndLoc.isInvalid())
2129 return;
2130
Steve Naroff873bd842008-07-29 18:15:38 +00002131 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffdbfc6932008-11-19 21:15:47 +00002132 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff873bd842008-07-29 18:15:38 +00002133 const char *startRef = 0, *endRef = 0;
2134 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2135 // Get the locations of the startRef, endRef.
2136 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2137 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2138 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002139 InsertText(LessLoc, "/*");
2140 InsertText(GreaterLoc, "*/");
Steve Naroff873bd842008-07-29 18:15:38 +00002141 }
2142 }
2143}
2144
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002145void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002146 SourceLocation Loc;
2147 QualType Type;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002148 const FunctionProtoType *proto = 0;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002149 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2150 Loc = VD->getLocation();
2151 Type = VD->getType();
2152 }
2153 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2154 Loc = FD->getLocation();
2155 // Check for ObjC 'id' and class types that have been adorned with protocol
2156 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall9dd450b2009-09-21 23:43:11 +00002157 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002158 assert(funcType && "missing function type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002159 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002160 if (!proto)
2161 return;
2162 Type = proto->getResultType();
2163 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00002164 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2165 Loc = FD->getLocation();
2166 Type = FD->getType();
2167 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002168 else
2169 return;
Mike Stump11289f42009-09-09 15:08:12 +00002170
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002171 if (needToScanForQualifiers(Type)) {
Steve Naroff50d42052007-11-01 13:24:47 +00002172 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002173
Steve Naroff50d42052007-11-01 13:24:47 +00002174 const char *endBuf = SM->getCharacterData(Loc);
2175 const char *startBuf = endBuf;
Steve Naroff930e0992008-05-31 05:02:17 +00002176 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroff50d42052007-11-01 13:24:47 +00002177 startBuf--; // scan backward (from the decl location) for return type.
2178 const char *startRef = 0, *endRef = 0;
2179 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2180 // Get the locations of the startRef, endRef.
2181 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2182 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2183 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002184 InsertText(LessLoc, "/*");
2185 InsertText(GreaterLoc, "*/");
Steve Naroff37e011c2007-10-31 04:38:33 +00002186 }
2187 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002188 if (!proto)
2189 return; // most likely, was a variable
Steve Naroff50d42052007-11-01 13:24:47 +00002190 // Now check arguments.
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002191 const char *startBuf = SM->getCharacterData(Loc);
2192 const char *startFuncBuf = startBuf;
Steve Naroff50d42052007-11-01 13:24:47 +00002193 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2194 if (needToScanForQualifiers(proto->getArgType(i))) {
2195 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002196
Steve Naroff50d42052007-11-01 13:24:47 +00002197 const char *endBuf = startBuf;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002198 // scan forward (from the decl location) for argument types.
2199 scanToNextArgument(endBuf);
Steve Naroff50d42052007-11-01 13:24:47 +00002200 const char *startRef = 0, *endRef = 0;
2201 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2202 // Get the locations of the startRef, endRef.
Mike Stump11289f42009-09-09 15:08:12 +00002203 SourceLocation LessLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002204 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump11289f42009-09-09 15:08:12 +00002205 SourceLocation GreaterLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002206 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00002207 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002208 InsertText(LessLoc, "/*");
2209 InsertText(GreaterLoc, "*/");
Steve Naroff50d42052007-11-01 13:24:47 +00002210 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002211 startBuf = ++endBuf;
2212 }
2213 else {
Steve Naroffc884aa82008-08-06 15:58:23 +00002214 // If the function name is derived from a macro expansion, then the
2215 // argument buffer will not follow the name. Need to speak with Chris.
2216 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002217 startBuf++; // scan forward (from the decl location) for argument types.
2218 startBuf++;
2219 }
Steve Naroff50d42052007-11-01 13:24:47 +00002220 }
Steve Naroff37e011c2007-10-31 04:38:33 +00002221}
2222
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002223void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2224 QualType QT = ND->getType();
2225 const Type* TypePtr = QT->getAs<Type>();
2226 if (!isa<TypeOfExprType>(TypePtr))
2227 return;
2228 while (isa<TypeOfExprType>(TypePtr)) {
2229 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2230 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2231 TypePtr = QT->getAs<Type>();
2232 }
2233 // FIXME. This will not work for multiple declarators; as in:
2234 // __typeof__(a) b,c,d;
2235 std::string TypeAsString(QT.getAsString());
2236 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2237 const char *startBuf = SM->getCharacterData(DeclLoc);
2238 if (ND->getInit()) {
2239 std::string Name(ND->getNameAsString());
2240 TypeAsString += " " + Name + " = ";
2241 Expr *E = ND->getInit();
2242 SourceLocation startLoc;
2243 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2244 startLoc = ECE->getLParenLoc();
2245 else
2246 startLoc = E->getLocStart();
2247 startLoc = SM->getInstantiationLoc(startLoc);
2248 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002249 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002250 }
2251 else {
2252 SourceLocation X = ND->getLocEnd();
2253 X = SM->getInstantiationLoc(X);
2254 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002255 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002256 }
2257}
2258
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002259// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002260void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002261 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2262 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002263 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002264 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002265 &ArgTys[0], ArgTys.size(),
2266 false /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002267 false, false, 0, 0,
2268 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002269 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002270 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002271 SelGetUidIdent, getFuncType, 0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002272 FunctionDecl::Extern,
2273 FunctionDecl::None, false);
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002274}
2275
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002276void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002277 // declared in <objc/objc.h>
Douglas Gregor1e21c192009-01-09 01:47:02 +00002278 if (FD->getIdentifier() &&
2279 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002280 SelGetUidFunctionDecl = FD;
Steve Naroff37e011c2007-10-31 04:38:33 +00002281 return;
2282 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002283 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002284}
2285
Fariborz Jahaniana459c442010-02-12 17:52:31 +00002286static void RewriteBlockPointerType(std::string& Str, QualType Type) {
2287 std::string TypeString(Type.getAsString());
2288 const char *argPtr = TypeString.c_str();
2289 if (!strchr(argPtr, '^')) {
2290 Str += TypeString;
2291 return;
2292 }
2293 while (*argPtr) {
2294 Str += (*argPtr == '^' ? '*' : *argPtr);
2295 argPtr++;
2296 }
2297}
2298
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002299// FIXME. Consolidate this routine with RewriteBlockPointerType.
2300static void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD) {
2301 QualType Type = VD->getType();
2302 std::string TypeString(Type.getAsString());
2303 const char *argPtr = TypeString.c_str();
2304 int paren = 0;
2305 while (*argPtr) {
2306 switch (*argPtr) {
2307 case '(':
2308 Str += *argPtr;
2309 paren++;
2310 break;
2311 case ')':
2312 Str += *argPtr;
2313 paren--;
2314 break;
2315 case '^':
2316 Str += '*';
2317 if (paren == 1)
2318 Str += VD->getNameAsString();
2319 break;
2320 default:
2321 Str += *argPtr;
2322 break;
2323 }
2324 argPtr++;
2325 }
2326}
2327
2328
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002329void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2330 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2331 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2332 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2333 if (!proto)
2334 return;
2335 QualType Type = proto->getResultType();
2336 std::string FdStr = Type.getAsString();
2337 FdStr += " ";
2338 FdStr += FD->getNameAsCString();
2339 FdStr += "(";
2340 unsigned numArgs = proto->getNumArgs();
2341 for (unsigned i = 0; i < numArgs; i++) {
2342 QualType ArgType = proto->getArgType(i);
Fariborz Jahaniana459c442010-02-12 17:52:31 +00002343 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002344 if (i+1 < numArgs)
2345 FdStr += ", ";
2346 }
2347 FdStr += ");\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002348 InsertText(FunLocStart, FdStr);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002349 CurFunctionDeclToDeclareForBlock = 0;
2350}
2351
Steve Naroff17978c42008-03-11 17:37:02 +00002352// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002353void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroff17978c42008-03-11 17:37:02 +00002354 if (SuperContructorFunctionDecl)
2355 return;
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002356 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroff17978c42008-03-11 17:37:02 +00002357 llvm::SmallVector<QualType, 16> ArgTys;
2358 QualType argT = Context->getObjCIdType();
2359 assert(!argT.isNull() && "Can't find 'id' type");
2360 ArgTys.push_back(argT);
2361 ArgTys.push_back(argT);
2362 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2363 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002364 false, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002365 false, false, 0, 0,
2366 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002367 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002368 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002369 msgSendIdent, msgSendType, 0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002370 FunctionDecl::Extern,
2371 FunctionDecl::None, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002372}
2373
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002374// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002375void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002376 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2377 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002378 QualType argT = Context->getObjCIdType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002379 assert(!argT.isNull() && "Can't find 'id' type");
2380 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002381 argT = Context->getObjCSelType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002382 assert(!argT.isNull() && "Can't find 'SEL' type");
2383 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002384 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002385 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002386 true /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002387 false, false, 0, 0,
2388 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002389 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002390 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002391 msgSendIdent, msgSendType, 0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002392 FunctionDecl::Extern,
2393 FunctionDecl::None, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002394}
2395
Steve Naroff7fa2f042007-11-15 10:28:18 +00002396// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002397void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002398 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2399 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002400 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002401 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002402 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002403 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2404 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2405 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002406 argT = Context->getObjCSelType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002407 assert(!argT.isNull() && "Can't find 'SEL' type");
2408 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002409 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff7fa2f042007-11-15 10:28:18 +00002410 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002411 true /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002412 false, false, 0, 0,
2413 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002414 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002415 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002416 msgSendIdent, msgSendType, 0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002417 FunctionDecl::Extern,
2418 FunctionDecl::None, false);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002419}
2420
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002421// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002422void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002423 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2424 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002425 QualType argT = Context->getObjCIdType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002426 assert(!argT.isNull() && "Can't find 'id' type");
2427 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002428 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002429 assert(!argT.isNull() && "Can't find 'SEL' type");
2430 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002431 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002432 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002433 true /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002434 false, false, 0, 0,
2435 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002436 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002437 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002438 msgSendIdent, msgSendType, 0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002439 FunctionDecl::Extern,
2440 FunctionDecl::None, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002441}
2442
Mike Stump11289f42009-09-09 15:08:12 +00002443// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002444// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002445void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump11289f42009-09-09 15:08:12 +00002446 IdentifierInfo *msgSendIdent =
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002447 &Context->Idents.get("objc_msgSendSuper_stret");
2448 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002449 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002450 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002451 &Context->Idents.get("objc_super"));
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002452 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2453 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2454 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002455 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002456 assert(!argT.isNull() && "Can't find 'SEL' type");
2457 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002458 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002459 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002460 true /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002461 false, false, 0, 0,
2462 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002463 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002464 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002465 msgSendIdent, msgSendType, 0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002466 FunctionDecl::Extern,
2467 FunctionDecl::None, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002468}
2469
Steve Naroff2e4e3852008-05-08 22:02:18 +00002470// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002471void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002472 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2473 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002474 QualType argT = Context->getObjCIdType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002475 assert(!argT.isNull() && "Can't find 'id' type");
2476 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002477 argT = Context->getObjCSelType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002478 assert(!argT.isNull() && "Can't find 'SEL' type");
2479 ArgTys.push_back(argT);
Steve Naroff2e4e3852008-05-08 22:02:18 +00002480 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002481 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002482 true /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002483 false, false, 0, 0,
2484 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002485 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002486 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002487 msgSendIdent, msgSendType, 0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002488 FunctionDecl::Extern,
2489 FunctionDecl::None, false);
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002490}
2491
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002492// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002493void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002494 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2495 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002496 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002497 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002498 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002499 false /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002500 false, false, 0, 0,
2501 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002502 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002503 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002504 getClassIdent, getClassType, 0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002505 FunctionDecl::Extern,
2506 FunctionDecl::None, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002507}
2508
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002509// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2510void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2511 IdentifierInfo *getSuperClassIdent =
2512 &Context->Idents.get("class_getSuperclass");
2513 llvm::SmallVector<QualType, 16> ArgTys;
2514 ArgTys.push_back(Context->getObjCClassType());
2515 QualType getClassType = Context->getFunctionType(Context->getObjCClassType(),
2516 &ArgTys[0], ArgTys.size(),
2517 false /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002518 false, false, 0, 0,
2519 FunctionType::ExtInfo());
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002520 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002521 SourceLocation(),
2522 getSuperClassIdent,
2523 getClassType, 0,
2524 FunctionDecl::Extern,
2525 FunctionDecl::None,
2526 false);
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002527}
2528
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002529// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002530void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002531 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2532 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002533 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002534 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002535 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002536 false /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002537 false, false, 0, 0,
2538 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002539 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002540 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002541 getClassIdent, getClassType, 0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002542 FunctionDecl::Extern,
2543 FunctionDecl::None, false);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002544}
2545
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002546Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffce8e8862008-03-15 00:55:56 +00002547 QualType strType = getConstantStringStructType();
2548
2549 std::string S = "__NSConstantStringImpl_";
Steve Naroffa6141f02008-05-31 03:35:42 +00002550
2551 std::string tmpName = InFileName;
2552 unsigned i;
2553 for (i=0; i < tmpName.length(); i++) {
2554 char c = tmpName.at(i);
2555 // replace any non alphanumeric characters with '_'.
2556 if (!isalpha(c) && (c < '0' || c > '9'))
2557 tmpName[i] = '_';
2558 }
2559 S += tmpName;
2560 S += "_";
Steve Naroffce8e8862008-03-15 00:55:56 +00002561 S += utostr(NumObjCStringLiterals++);
2562
Steve Naroff00a31762008-03-27 22:29:16 +00002563 Preamble += "static __NSConstantStringImpl " + S;
2564 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2565 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffce8e8862008-03-15 00:55:56 +00002566 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek2d470fc2008-09-13 05:16:45 +00002567 std::string prettyBufS;
2568 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00002569 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2570 PrintingPolicy(LangOpts));
Steve Naroff00a31762008-03-27 22:29:16 +00002571 Preamble += prettyBuf.str();
2572 Preamble += ",";
Steve Naroff94ed6dc2009-12-06 01:48:44 +00002573 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002574
2575 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002576 &Context->Idents.get(S), strType, 0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002577 VarDecl::Static, VarDecl::None);
Ted Kremenek5a201952009-02-07 01:47:29 +00002578 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2579 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002580 Context->getPointerType(DRE->getType()),
Steve Naroffce8e8862008-03-15 00:55:56 +00002581 SourceLocation());
Steve Naroff265a6b92007-11-08 14:30:50 +00002582 // cast to NSConstantString *
John McCall97513962010-01-15 18:39:57 +00002583 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2584 CastExpr::CK_Unknown, Unop);
Chris Lattner2e0d2602008-01-31 19:37:57 +00002585 ReplaceStmt(Exp, cast);
Steve Naroff22216db2008-12-04 23:50:32 +00002586 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff265a6b92007-11-08 14:30:50 +00002587 return cast;
Steve Naroffa397efd2007-11-03 11:27:19 +00002588}
2589
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002590bool RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002591 // check if we are sending a message to 'super'
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002592 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return false;
2593 return isa<ObjCSuperExpr>(recExpr);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002594}
2595
2596// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002597QualType RewriteObjC::getSuperStructType() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002598 if (!SuperStructDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002599 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002600 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002601 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002602 QualType FieldTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002603
Steve Naroff7fa2f042007-11-15 10:28:18 +00002604 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002605 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002606 // struct objc_class *super;
Mike Stump11289f42009-09-09 15:08:12 +00002607 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor91f84212008-12-11 16:49:14 +00002608
Steve Naroff7fa2f042007-11-15 10:28:18 +00002609 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002610 for (unsigned i = 0; i < 2; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002611 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2612 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002613 FieldTypes[i], 0,
2614 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002615 /*Mutable=*/false));
Douglas Gregor91f84212008-12-11 16:49:14 +00002616 }
Mike Stump11289f42009-09-09 15:08:12 +00002617
Douglas Gregord5058122010-02-11 01:19:42 +00002618 SuperStructDecl->completeDefinition();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002619 }
2620 return Context->getTagDeclType(SuperStructDecl);
2621}
2622
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002623QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffce8e8862008-03-15 00:55:56 +00002624 if (!ConstantStringDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002625 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002626 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002627 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffce8e8862008-03-15 00:55:56 +00002628 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002629
Steve Naroffce8e8862008-03-15 00:55:56 +00002630 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002631 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffce8e8862008-03-15 00:55:56 +00002632 // int flags;
Mike Stump11289f42009-09-09 15:08:12 +00002633 FieldTypes[1] = Context->IntTy;
Steve Naroffce8e8862008-03-15 00:55:56 +00002634 // char *str;
Mike Stump11289f42009-09-09 15:08:12 +00002635 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffce8e8862008-03-15 00:55:56 +00002636 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002637 FieldTypes[3] = Context->LongTy;
Douglas Gregor91f84212008-12-11 16:49:14 +00002638
Steve Naroffce8e8862008-03-15 00:55:56 +00002639 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002640 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002641 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2642 ConstantStringDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00002643 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002644 FieldTypes[i], 0,
Douglas Gregor91f84212008-12-11 16:49:14 +00002645 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002646 /*Mutable=*/true));
Douglas Gregor91f84212008-12-11 16:49:14 +00002647 }
2648
Douglas Gregord5058122010-02-11 01:19:42 +00002649 ConstantStringDecl->completeDefinition();
Steve Naroffce8e8862008-03-15 00:55:56 +00002650 }
2651 return Context->getTagDeclType(ConstantStringDecl);
2652}
2653
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002654Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2655 SourceLocation StartLoc,
2656 SourceLocation EndLoc) {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002657 if (!SelGetUidFunctionDecl)
2658 SynthSelGetUidFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002659 if (!MsgSendFunctionDecl)
2660 SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002661 if (!MsgSendSuperFunctionDecl)
2662 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002663 if (!MsgSendStretFunctionDecl)
2664 SynthMsgSendStretFunctionDecl();
2665 if (!MsgSendSuperStretFunctionDecl)
2666 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002667 if (!MsgSendFpretFunctionDecl)
2668 SynthMsgSendFpretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002669 if (!GetClassFunctionDecl)
2670 SynthGetClassFunctionDecl();
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002671 if (!GetSuperClassFunctionDecl)
2672 SynthGetSuperClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002673 if (!GetMetaClassFunctionDecl)
2674 SynthGetMetaClassFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002675
Steve Naroff7fa2f042007-11-15 10:28:18 +00002676 // default to objc_msgSend().
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002677 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2678 // May need to use objc_msgSend_stret() as well.
2679 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroffd9803712009-04-29 16:37:50 +00002680 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2681 QualType resultType = mDecl->getResultType();
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002682 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002683 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002684 else if (resultType->isRealFloatingType())
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002685 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002686 }
Mike Stump11289f42009-09-09 15:08:12 +00002687
Steve Naroff574440f2007-10-24 22:48:43 +00002688 // Synthesize a call to objc_msgSend().
2689 llvm::SmallVector<Expr*, 8> MsgExprs;
2690 IdentifierInfo *clsName = Exp->getClassName();
Mike Stump11289f42009-09-09 15:08:12 +00002691
Steve Naroff574440f2007-10-24 22:48:43 +00002692 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2693 if (clsName) { // class message.
Steve Naroff6c79f972008-07-24 19:44:33 +00002694 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2695 // the 'super' idiom within a class method.
Daniel Dunbar07d07852009-10-18 21:17:35 +00002696 if (clsName->getName() == "super") {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002697 MsgSendFlavor = MsgSendSuperFunctionDecl;
2698 if (MsgSendStretFlavor)
2699 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2700 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002701
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002702 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002703
2704 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002705
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002706 // set the receiver to self, the first argument to all methods.
Steve Naroffd9803712009-04-29 16:37:50 +00002707 InitExprs.push_back(
John McCall97513962010-01-15 18:39:57 +00002708 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2709 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002710 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroffd9803712009-04-29 16:37:50 +00002711 Context->getObjCIdType(),
John McCall97513962010-01-15 18:39:57 +00002712 SourceLocation()))
2713 ); // set the 'receiver'.
Steve Naroffd9803712009-04-29 16:37:50 +00002714
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002715 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002716 llvm::SmallVector<Expr*, 8> ClsExprs;
2717 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002718 ClsExprs.push_back(StringLiteral::Create(*Context,
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002719 ClassDecl->getIdentifier()->getNameStart(),
2720 ClassDecl->getIdentifier()->getLength(),
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002721 false, argType, SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002722 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002723 &ClsExprs[0],
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002724 ClsExprs.size(),
2725 StartLoc,
2726 EndLoc);
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002727 // (Class)objc_getClass("CurrentClass")
2728 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2729 Context->getObjCClassType(),
2730 CastExpr::CK_Unknown, Cls);
2731 ClsExprs.clear();
2732 ClsExprs.push_back(ArgExpr);
2733 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2734 &ClsExprs[0], ClsExprs.size(),
2735 StartLoc, EndLoc);
2736
2737 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002738 // To turn off a warning, type-cast to 'id'
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002739 InitExprs.push_back( // set 'super class', using class_getSuperclass().
John McCall97513962010-01-15 18:39:57 +00002740 NoTypeInfoCStyleCastExpr(Context,
2741 Context->getObjCIdType(),
2742 CastExpr::CK_Unknown, Cls));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002743 // struct objc_super
2744 QualType superType = getSuperStructType();
Steve Naroff0b844f02008-03-11 18:14:26 +00002745 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002746
Steve Naroff0b844f02008-03-11 18:14:26 +00002747 if (LangOpts.Microsoft) {
2748 SynthSuperContructorFunctionDecl();
2749 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002750 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff0b844f02008-03-11 18:14:26 +00002751 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002752 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002753 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002754 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002755 // The code for super is a little tricky to prevent collision with
2756 // the structure definition in the header. The rewriter has it's own
2757 // internal definition (__rw_objc_super) that is uses. This is why
2758 // we need the cast below. For example:
2759 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2760 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002761 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002762 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002763 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00002764 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2765 Context->getPointerType(superType),
2766 CastExpr::CK_Unknown, SuperRep);
Mike Stump11289f42009-09-09 15:08:12 +00002767 } else {
Steve Naroff0b844f02008-03-11 18:14:26 +00002768 // (struct objc_super) { <exprs from above> }
Ted Kremenekac034612010-04-13 23:39:13 +00002769 InitListExpr *ILE =
2770 new (Context) InitListExpr(*Context, SourceLocation(),
2771 &InitExprs[0], InitExprs.size(),
2772 SourceLocation());
John McCalle15bbff2010-01-18 19:35:47 +00002773 TypeSourceInfo *superTInfo
2774 = Context->getTrivialTypeSourceInfo(superType);
John McCall5d7aa7f2010-01-19 22:33:45 +00002775 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2776 superType, ILE, false);
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002777 // struct objc_super *
Ted Kremenek5a201952009-02-07 01:47:29 +00002778 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002779 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002780 SourceLocation());
Steve Naroff0b844f02008-03-11 18:14:26 +00002781 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002782 MsgExprs.push_back(SuperRep);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002783 } else {
2784 llvm::SmallVector<Expr*, 8> ClsExprs;
2785 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002786 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002787 clsName->getNameStart(),
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002788 clsName->getLength(),
2789 false, argType,
2790 SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002791 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002792 &ClsExprs[0],
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002793 ClsExprs.size(),
2794 StartLoc, EndLoc);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002795 MsgExprs.push_back(Cls);
2796 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002797 } else { // instance message.
2798 Expr *recExpr = Exp->getReceiver();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002799
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002800 if (isSuperReceiver(recExpr)) {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002801 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002802 if (MsgSendStretFlavor)
2803 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff7fa2f042007-11-15 10:28:18 +00002804 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002805 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002806 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002807
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002808 InitExprs.push_back(
John McCall97513962010-01-15 18:39:57 +00002809 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2810 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002811 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroff97adf602008-07-16 22:35:27 +00002812 Context->getObjCIdType(),
John McCall97513962010-01-15 18:39:57 +00002813 SourceLocation()))
2814 ); // set the 'receiver'.
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002815
2816 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Steve Naroff7fa2f042007-11-15 10:28:18 +00002817 llvm::SmallVector<Expr*, 8> ClsExprs;
2818 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002819 ClsExprs.push_back(StringLiteral::Create(*Context,
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002820 ClassDecl->getIdentifier()->getNameStart(),
2821 ClassDecl->getIdentifier()->getLength(),
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002822 false, argType, SourceLocation()));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002823 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002824 &ClsExprs[0],
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002825 ClsExprs.size(),
2826 StartLoc, EndLoc);
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002827 // (Class)objc_getClass("CurrentClass")
2828 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2829 Context->getObjCClassType(),
2830 CastExpr::CK_Unknown, Cls);
2831 ClsExprs.clear();
2832 ClsExprs.push_back(ArgExpr);
2833 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2834 &ClsExprs[0], ClsExprs.size(),
2835 StartLoc, EndLoc);
2836
2837 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Fariborz Jahaniand5db92b2007-12-05 17:29:46 +00002838 // To turn off a warning, type-cast to 'id'
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002839 InitExprs.push_back(
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002840 // set 'super class', using class_getSuperclass().
John McCall97513962010-01-15 18:39:57 +00002841 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2842 CastExpr::CK_Unknown, Cls));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002843 // struct objc_super
2844 QualType superType = getSuperStructType();
Steve Naroff17978c42008-03-11 17:37:02 +00002845 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002846
Steve Naroff17978c42008-03-11 17:37:02 +00002847 if (LangOpts.Microsoft) {
2848 SynthSuperContructorFunctionDecl();
2849 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002850 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff17978c42008-03-11 17:37:02 +00002851 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002852 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002853 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002854 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002855 // The code for super is a little tricky to prevent collision with
2856 // the structure definition in the header. The rewriter has it's own
2857 // internal definition (__rw_objc_super) that is uses. This is why
2858 // we need the cast below. For example:
2859 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2860 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002861 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002862 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002863 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00002864 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2865 Context->getPointerType(superType),
2866 CastExpr::CK_Unknown, SuperRep);
Steve Naroff17978c42008-03-11 17:37:02 +00002867 } else {
2868 // (struct objc_super) { <exprs from above> }
Ted Kremenekac034612010-04-13 23:39:13 +00002869 InitListExpr *ILE =
2870 new (Context) InitListExpr(*Context, SourceLocation(),
2871 &InitExprs[0], InitExprs.size(),
2872 SourceLocation());
John McCalle15bbff2010-01-18 19:35:47 +00002873 TypeSourceInfo *superTInfo
2874 = Context->getTrivialTypeSourceInfo(superType);
John McCall5d7aa7f2010-01-19 22:33:45 +00002875 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2876 superType, ILE, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002877 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002878 MsgExprs.push_back(SuperRep);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002879 } else {
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002880 // Remove all type-casts because it may contain objc-style types; e.g.
2881 // Foo<Proto> *.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002882 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002883 recExpr = CE->getSubExpr();
John McCall97513962010-01-15 18:39:57 +00002884 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2885 CastExpr::CK_Unknown, recExpr);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002886 MsgExprs.push_back(recExpr);
2887 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002888 }
Steve Naroffa397efd2007-11-03 11:27:19 +00002889 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff574440f2007-10-24 22:48:43 +00002890 llvm::SmallVector<Expr*, 8> SelExprs;
2891 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002892 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00002893 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00002894 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00002895 false, argType, SourceLocation()));
Steve Naroff574440f2007-10-24 22:48:43 +00002896 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002897 &SelExprs[0], SelExprs.size(),
2898 StartLoc,
2899 EndLoc);
Steve Naroff574440f2007-10-24 22:48:43 +00002900 MsgExprs.push_back(SelExp);
Mike Stump11289f42009-09-09 15:08:12 +00002901
Steve Naroff574440f2007-10-24 22:48:43 +00002902 // Now push any user supplied arguments.
2903 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroffe7f18192007-11-14 23:54:14 +00002904 Expr *userExpr = Exp->getArg(i);
Steve Narofff60782b2007-11-15 02:58:25 +00002905 // Make all implicit casts explicit...ICE comes in handy:-)
2906 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2907 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregore200adc2008-10-27 19:41:14 +00002908 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002909 ? Context->getObjCIdType()
Douglas Gregore200adc2008-10-27 19:41:14 +00002910 : ICE->getType();
John McCall97513962010-01-15 18:39:57 +00002911 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CastExpr::CK_Unknown,
2912 userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002913 }
2914 // Make id<P...> cast into an 'id' cast.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002915 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002916 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregorf19b2312008-10-28 15:36:24 +00002917 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002918 userExpr = CE->getSubExpr();
John McCall97513962010-01-15 18:39:57 +00002919 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2920 CastExpr::CK_Unknown, userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002921 }
Mike Stump11289f42009-09-09 15:08:12 +00002922 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002923 MsgExprs.push_back(userExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00002924 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2925 // out the argument in the original expression (since we aren't deleting
2926 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2927 //Exp->setArg(i, 0);
Steve Naroff574440f2007-10-24 22:48:43 +00002928 }
Steve Narofff36987c2007-11-04 22:37:50 +00002929 // Generate the funky cast.
2930 CastExpr *cast;
2931 llvm::SmallVector<QualType, 8> ArgTypes;
2932 QualType returnType;
Mike Stump11289f42009-09-09 15:08:12 +00002933
Steve Narofff36987c2007-11-04 22:37:50 +00002934 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff44864e42007-11-15 10:43:57 +00002935 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2936 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2937 else
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002938 ArgTypes.push_back(Context->getObjCIdType());
2939 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattnera4997152009-02-20 18:43:26 +00002940 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Narofff36987c2007-11-04 22:37:50 +00002941 // Push any user argument types.
Chris Lattnera4997152009-02-20 18:43:26 +00002942 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2943 E = OMD->param_end(); PI != E; ++PI) {
2944 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump11289f42009-09-09 15:08:12 +00002945 ? Context->getObjCIdType()
Chris Lattnera4997152009-02-20 18:43:26 +00002946 : (*PI)->getType();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002947 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00002948 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002949 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002950 t = Context->getPointerType(BPT->getPointeeType());
2951 }
Steve Naroff98eb8d12007-11-05 14:36:37 +00002952 ArgTypes.push_back(t);
2953 }
Chris Lattnera4997152009-02-20 18:43:26 +00002954 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2955 ? Context->getObjCIdType() : OMD->getResultType();
Fariborz Jahanianf89eb2b2010-02-24 01:25:40 +00002956 if (isTopLevelBlockPointerType(returnType)) {
2957 const BlockPointerType *BPT = returnType->getAs<BlockPointerType>();
2958 returnType = Context->getPointerType(BPT->getPointeeType());
2959 }
Steve Narofff36987c2007-11-04 22:37:50 +00002960 } else {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002961 returnType = Context->getObjCIdType();
Steve Narofff36987c2007-11-04 22:37:50 +00002962 }
2963 // Get the type, we will need to reference it in a couple spots.
Steve Naroff7fa2f042007-11-15 10:28:18 +00002964 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002965
Steve Narofff36987c2007-11-04 22:37:50 +00002966 // Create a reference to the objc_msgSend() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002967 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002968 SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00002969
Mike Stump11289f42009-09-09 15:08:12 +00002970 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Narofff36987c2007-11-04 22:37:50 +00002971 // If we don't do this cast, we get the following bizarre warning/note:
2972 // xx.m:13: warning: function called through a non-compatible type
2973 // xx.m:13: note: if this code is reached, the program will abort
John McCall97513962010-01-15 18:39:57 +00002974 cast = NoTypeInfoCStyleCastExpr(Context,
2975 Context->getPointerType(Context->VoidTy),
2976 CastExpr::CK_Unknown, DRE);
Mike Stump11289f42009-09-09 15:08:12 +00002977
Steve Narofff36987c2007-11-04 22:37:50 +00002978 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002979 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002980 &ArgTypes[0], ArgTypes.size(),
Steve Naroff327f0f42008-03-18 02:02:04 +00002981 // If we don't have a method decl, force a variadic cast.
Douglas Gregor36c569f2010-02-21 22:15:06 +00002982 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002983 false, false, 0, 0,
2984 FunctionType::ExtInfo());
Steve Narofff36987c2007-11-04 22:37:50 +00002985 castType = Context->getPointerType(castType);
John McCall97513962010-01-15 18:39:57 +00002986 cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown,
2987 cast);
Steve Narofff36987c2007-11-04 22:37:50 +00002988
2989 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002990 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump11289f42009-09-09 15:08:12 +00002991
John McCall9dd450b2009-09-21 23:43:11 +00002992 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002993 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002994 MsgExprs.size(),
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002995 FT->getResultType(), EndLoc);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002996 Stmt *ReplacingStmt = CE;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002997 if (MsgSendStretFlavor) {
2998 // We have the method which returns a struct/union. Must also generate
2999 // call to objc_msgSend_stret and hang both varieties on a conditional
3000 // expression which dictate which one to envoke depending on size of
3001 // method's return type.
Mike Stump11289f42009-09-09 15:08:12 +00003002
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003003 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003004 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003005 SourceLocation());
3006 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall97513962010-01-15 18:39:57 +00003007 cast = NoTypeInfoCStyleCastExpr(Context,
3008 Context->getPointerType(Context->VoidTy),
3009 CastExpr::CK_Unknown, STDRE);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003010 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00003011 castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00003012 &ArgTypes[0], ArgTypes.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00003013 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003014 false, false, 0, 0,
3015 FunctionType::ExtInfo());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003016 castType = Context->getPointerType(castType);
John McCall97513962010-01-15 18:39:57 +00003017 cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown,
3018 cast);
Mike Stump11289f42009-09-09 15:08:12 +00003019
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003020 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00003021 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00003022
John McCall9dd450b2009-09-21 23:43:11 +00003023 FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003024 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00003025 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003026 FT->getResultType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00003027
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003028 // Build sizeof(returnType)
Mike Stump11289f42009-09-09 15:08:12 +00003029 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCallbcd03502009-12-07 02:54:59 +00003030 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl6f282892008-11-11 17:56:53 +00003031 Context->getSizeType(),
3032 SourceLocation(), SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003033 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3034 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3035 // For X86 it is more complicated and some kind of target specific routine
3036 // is needed to decide what to do.
Mike Stump11289f42009-09-09 15:08:12 +00003037 unsigned IntSize =
Chris Lattner37e05872008-03-05 18:54:05 +00003038 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Mike Stump11289f42009-09-09 15:08:12 +00003039 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003040 Context->IntTy,
3041 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00003042 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
3043 BinaryOperator::LE,
3044 Context->IntTy,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003045 SourceLocation());
3046 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump11289f42009-09-09 15:08:12 +00003047 ConditionalOperator *CondExpr =
Douglas Gregor7e112b02009-08-26 14:37:04 +00003048 new (Context) ConditionalOperator(lessThanExpr,
3049 SourceLocation(), CE,
3050 SourceLocation(), STCE, returnType);
Ted Kremenek5a201952009-02-07 01:47:29 +00003051 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003052 }
Mike Stump11289f42009-09-09 15:08:12 +00003053 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003054 return ReplacingStmt;
3055}
3056
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003057Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00003058 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3059 Exp->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003060
Steve Naroff574440f2007-10-24 22:48:43 +00003061 // Now do the actual rewrite.
Chris Lattner2e0d2602008-01-31 19:37:57 +00003062 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00003063
3064 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003065 return ReplacingStmt;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00003066}
3067
Steve Naroffd9803712009-04-29 16:37:50 +00003068// typedef struct objc_object Protocol;
3069QualType RewriteObjC::getProtocolType() {
3070 if (!ProtocolTypeDecl) {
John McCallbcd03502009-12-07 02:54:59 +00003071 TypeSourceInfo *TInfo
3072 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroffd9803712009-04-29 16:37:50 +00003073 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00003074 SourceLocation(),
Steve Naroffd9803712009-04-29 16:37:50 +00003075 &Context->Idents.get("Protocol"),
John McCallbcd03502009-12-07 02:54:59 +00003076 TInfo);
Steve Naroffd9803712009-04-29 16:37:50 +00003077 }
3078 return Context->getTypeDeclType(ProtocolTypeDecl);
3079}
3080
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00003081/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroffd9803712009-04-29 16:37:50 +00003082/// a synthesized/forward data reference (to the protocol's metadata).
3083/// The forward references (and metadata) are generated in
3084/// RewriteObjC::HandleTranslationUnit().
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003085Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroffd9803712009-04-29 16:37:50 +00003086 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3087 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump11289f42009-09-09 15:08:12 +00003088 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregorc4df4072010-04-19 22:54:31 +00003089 ID, getProtocolType(), 0,
3090 VarDecl::Extern, VarDecl::None);
Steve Naroffd9803712009-04-29 16:37:50 +00003091 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
3092 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
3093 Context->getPointerType(DRE->getType()),
3094 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00003095 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3096 CastExpr::CK_Unknown,
3097 DerefExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00003098 ReplaceStmt(Exp, castExpr);
3099 ProtocolExprDecls.insert(Exp->getProtocol());
Mike Stump11289f42009-09-09 15:08:12 +00003100 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00003101 return castExpr;
Mike Stump11289f42009-09-09 15:08:12 +00003102
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00003103}
3104
Mike Stump11289f42009-09-09 15:08:12 +00003105bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003106 const char *endBuf) {
3107 while (startBuf < endBuf) {
3108 if (*startBuf == '#') {
3109 // Skip whitespace.
3110 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3111 ;
3112 if (!strncmp(startBuf, "if", strlen("if")) ||
3113 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3114 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3115 !strncmp(startBuf, "define", strlen("define")) ||
3116 !strncmp(startBuf, "undef", strlen("undef")) ||
3117 !strncmp(startBuf, "else", strlen("else")) ||
3118 !strncmp(startBuf, "elif", strlen("elif")) ||
3119 !strncmp(startBuf, "endif", strlen("endif")) ||
3120 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3121 !strncmp(startBuf, "include", strlen("include")) ||
3122 !strncmp(startBuf, "import", strlen("import")) ||
3123 !strncmp(startBuf, "include_next", strlen("include_next")))
3124 return true;
3125 }
3126 startBuf++;
3127 }
3128 return false;
3129}
3130
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003131/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003132/// an objective-c class with ivars.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003133void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003134 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003135 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Mike Stump11289f42009-09-09 15:08:12 +00003136 assert(CDecl->getNameAsCString() &&
Douglas Gregor77324f32008-11-17 14:58:09 +00003137 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00003138 // Do not synthesize more than once.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003139 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00003140 return;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003141 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003142 int NumIvars = CDecl->ivar_size();
Steve Naroffdde78982007-11-14 19:25:57 +00003143 SourceLocation LocStart = CDecl->getLocStart();
3144 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00003145
Steve Naroffdde78982007-11-14 19:25:57 +00003146 const char *startBuf = SM->getCharacterData(LocStart);
3147 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00003148
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003149 // If no ivars and no root or if its root, directly or indirectly,
3150 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003151 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
3152 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner184e65d2009-04-14 23:22:57 +00003153 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003154 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003155 return;
3156 }
Mike Stump11289f42009-09-09 15:08:12 +00003157
3158 // FIXME: This has potential of causing problem. If
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003159 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003160 Result += "\nstruct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003161 Result += CDecl->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00003162 if (LangOpts.Microsoft)
3163 Result += "_IMPL";
Steve Naroffdc5b6b22008-03-12 00:25:36 +00003164
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003165 if (NumIvars > 0) {
Steve Naroffdde78982007-11-14 19:25:57 +00003166 const char *cursor = strchr(startBuf, '{');
Mike Stump11289f42009-09-09 15:08:12 +00003167 assert((cursor && endBuf)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003168 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003169 // If the buffer contains preprocessor directives, we do more fine-grained
3170 // rewrites. This is intended to fix code that looks like (which occurs in
3171 // NSURL.h, for example):
3172 //
3173 // #ifdef XYZ
3174 // @interface Foo : NSObject
3175 // #else
3176 // @interface FooBar : NSObject
3177 // #endif
3178 // {
3179 // int i;
3180 // }
3181 // @end
3182 //
3183 // This clause is segregated to avoid breaking the common case.
3184 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump11289f42009-09-09 15:08:12 +00003185 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003186 CDecl->getClassLoc();
3187 const char *endHeader = SM->getCharacterData(L);
Chris Lattner184e65d2009-04-14 23:22:57 +00003188 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003189
Chris Lattnerf5b77512009-02-20 18:18:36 +00003190 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003191 // advance to the end of the referenced protocols.
3192 while (endHeader < cursor && *endHeader != '>') endHeader++;
3193 endHeader++;
3194 }
3195 // rewrite the original header
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003196 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003197 } else {
3198 // rewrite the original header *without* disturbing the '{'
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003199 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003200 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003201 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroffdde78982007-11-14 19:25:57 +00003202 Result = "\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003203 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003204 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003205 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003206 Result += "_IVARS;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003207
Steve Naroffdde78982007-11-14 19:25:57 +00003208 // insert the super class structure definition.
Chris Lattner1780a852008-01-31 19:42:41 +00003209 SourceLocation OnePastCurly =
3210 LocStart.getFileLocWithOffset(cursor-startBuf+1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003211 InsertText(OnePastCurly, Result);
Steve Naroffdde78982007-11-14 19:25:57 +00003212 }
3213 cursor++; // past '{'
Mike Stump11289f42009-09-09 15:08:12 +00003214
Steve Naroffdde78982007-11-14 19:25:57 +00003215 // Now comment out any visibility specifiers.
3216 while (cursor < endBuf) {
3217 if (*cursor == '@') {
3218 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner174a8252007-11-14 22:57:51 +00003219 // Skip whitespace.
3220 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3221 /*scan*/;
3222
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003223 // FIXME: presence of @public, etc. inside comment results in
3224 // this transformation as well, which is still correct c-code.
Steve Naroffdde78982007-11-14 19:25:57 +00003225 if (!strncmp(cursor, "public", strlen("public")) ||
3226 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffaf91b9a2008-04-04 22:34:24 +00003227 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003228 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003229 InsertText(atLoc, "// ");
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003230 }
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003231 // FIXME: If there are cases where '<' is used in ivar declaration part
3232 // of user code, then scan the ivar list and use needToScanForQualifiers
3233 // for type checking.
3234 else if (*cursor == '<') {
3235 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003236 InsertText(atLoc, "/* ");
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003237 cursor = strchr(cursor, '>');
3238 cursor++;
3239 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003240 InsertText(atLoc, " */");
Steve Naroff295570a2008-10-30 12:09:33 +00003241 } else if (*cursor == '^') { // rewrite block specifier.
3242 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003243 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003244 }
Steve Naroffdde78982007-11-14 19:25:57 +00003245 cursor++;
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003246 }
Steve Naroffdde78982007-11-14 19:25:57 +00003247 // Don't forget to add a ';'!!
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003248 InsertText(LocEnd.getFileLocWithOffset(1), ";");
Steve Naroffdde78982007-11-14 19:25:57 +00003249 } else { // we don't have any instance variables - insert super struct.
Chris Lattner184e65d2009-04-14 23:22:57 +00003250 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Naroffdde78982007-11-14 19:25:57 +00003251 Result += " {\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003252 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003253 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003254 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003255 Result += "_IVARS;\n};\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003256 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003257 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003258 // Mark this struct as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003259 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff13e74872008-05-06 18:26:51 +00003260 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003261}
3262
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003263// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003264/// class methods.
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003265template<typename MethodIterator>
3266void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3267 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +00003268 bool IsInstanceMethod,
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003269 const char *prefix,
Chris Lattner211f8b82007-10-25 17:07:24 +00003270 const char *ClassName,
3271 std::string &Result) {
Chris Lattner31bc07e2007-12-12 07:46:12 +00003272 if (MethodBegin == MethodEnd) return;
Mike Stump11289f42009-09-09 15:08:12 +00003273
Chris Lattner31bc07e2007-12-12 07:46:12 +00003274 if (!objc_impl_method) {
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003275 /* struct _objc_method {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003276 SEL _cmd;
3277 char *method_types;
3278 void *_imp;
3279 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003280 */
Chris Lattner211f8b82007-10-25 17:07:24 +00003281 Result += "\nstruct _objc_method {\n";
3282 Result += "\tSEL _cmd;\n";
3283 Result += "\tchar *method_types;\n";
3284 Result += "\tvoid *_imp;\n";
3285 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003286
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003287 objc_impl_method = true;
Fariborz Jahanian74a1cfa2007-10-19 00:36:46 +00003288 }
Mike Stump11289f42009-09-09 15:08:12 +00003289
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003290 // Build _objc_method_list for class's methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003291
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003292 /* struct {
3293 struct _objc_method_list *next_method;
3294 int method_count;
3295 struct _objc_method method_list[];
3296 }
3297 */
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003298 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003299 Result += "\nstatic struct {\n";
3300 Result += "\tstruct _objc_method_list *next_method;\n";
3301 Result += "\tint method_count;\n";
3302 Result += "\tstruct _objc_method method_list[";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003303 Result += utostr(NumMethods);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003304 Result += "];\n} _OBJC_";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003305 Result += prefix;
3306 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3307 Result += "_METHODS_";
3308 Result += ClassName;
Steve Naroffb327e492008-03-12 17:18:30 +00003309 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003310 Result += IsInstanceMethod ? "inst" : "cls";
3311 Result += "_meth\")))= ";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003312 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003313
Chris Lattner31bc07e2007-12-12 07:46:12 +00003314 Result += "\t,{{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003315 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattner31bc07e2007-12-12 07:46:12 +00003316 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003317 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattner31bc07e2007-12-12 07:46:12 +00003318 Result += "\", \"";
3319 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003320 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003321 Result += MethodInternalNames[*MethodBegin];
3322 Result += "}\n";
3323 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3324 Result += "\t ,{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003325 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003326 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003327 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003328 Result += "\", \"";
3329 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003330 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003331 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanian56338352007-11-13 21:02:00 +00003332 Result += "}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003333 }
Chris Lattner31bc07e2007-12-12 07:46:12 +00003334 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003335}
3336
Steve Naroffd9803712009-04-29 16:37:50 +00003337/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner390d39a2008-07-21 21:32:27 +00003338void RewriteObjC::
Steve Naroffd9803712009-04-29 16:37:50 +00003339RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix,
3340 const char *ClassName, std::string &Result) {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003341 static bool objc_protocol_methods = false;
Steve Naroffd9803712009-04-29 16:37:50 +00003342
3343 // Output struct protocol_methods holder of method selector and type.
3344 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3345 /* struct protocol_methods {
3346 SEL _cmd;
3347 char *method_types;
3348 }
3349 */
3350 Result += "\nstruct _protocol_methods {\n";
3351 Result += "\tstruct objc_selector *_cmd;\n";
3352 Result += "\tchar *method_types;\n";
3353 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003354
Steve Naroffd9803712009-04-29 16:37:50 +00003355 objc_protocol_methods = true;
3356 }
3357 // Do not synthesize the protocol more than once.
3358 if (ObjCSynthesizedProtocols.count(PDecl))
3359 return;
Mike Stump11289f42009-09-09 15:08:12 +00003360
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003361 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3362 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3363 PDecl->instmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003364 /* struct _objc_protocol_method_list {
3365 int protocol_method_count;
3366 struct protocol_methods protocols[];
3367 }
Steve Naroff251084d2008-03-12 01:06:30 +00003368 */
Steve Naroffd9803712009-04-29 16:37:50 +00003369 Result += "\nstatic struct {\n";
3370 Result += "\tint protocol_method_count;\n";
3371 Result += "\tstruct _protocol_methods protocol_methods[";
3372 Result += utostr(NumMethods);
3373 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3374 Result += PDecl->getNameAsString();
3375 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3376 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003377
Steve Naroffd9803712009-04-29 16:37:50 +00003378 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003379 for (ObjCProtocolDecl::instmeth_iterator
3380 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003381 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003382 if (I == PDecl->instmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003383 Result += "\t ,{{(struct objc_selector *)\"";
3384 else
3385 Result += "\t ,{(struct objc_selector *)\"";
3386 Result += (*I)->getSelector().getAsString().c_str();
3387 std::string MethodTypeString;
3388 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3389 Result += "\", \"";
3390 Result += MethodTypeString;
3391 Result += "\"}\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003392 }
Steve Naroffd9803712009-04-29 16:37:50 +00003393 Result += "\t }\n};\n";
3394 }
Mike Stump11289f42009-09-09 15:08:12 +00003395
Steve Naroffd9803712009-04-29 16:37:50 +00003396 // Output class methods declared in this protocol.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003397 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3398 PDecl->classmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003399 if (NumMethods > 0) {
3400 /* struct _objc_protocol_method_list {
3401 int protocol_method_count;
3402 struct protocol_methods protocols[];
3403 }
3404 */
3405 Result += "\nstatic struct {\n";
3406 Result += "\tint protocol_method_count;\n";
3407 Result += "\tstruct _protocol_methods protocol_methods[";
3408 Result += utostr(NumMethods);
3409 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3410 Result += PDecl->getNameAsString();
3411 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3412 "{\n\t";
3413 Result += utostr(NumMethods);
3414 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003415
Steve Naroffd9803712009-04-29 16:37:50 +00003416 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003417 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003418 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003419 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003420 if (I == PDecl->classmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003421 Result += "\t ,{{(struct objc_selector *)\"";
3422 else
3423 Result += "\t ,{(struct objc_selector *)\"";
3424 Result += (*I)->getSelector().getAsString().c_str();
3425 std::string MethodTypeString;
3426 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3427 Result += "\", \"";
3428 Result += MethodTypeString;
3429 Result += "\"}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003430 }
Steve Naroffd9803712009-04-29 16:37:50 +00003431 Result += "\t }\n};\n";
3432 }
3433
3434 // Output:
3435 /* struct _objc_protocol {
3436 // Objective-C 1.0 extensions
3437 struct _objc_protocol_extension *isa;
3438 char *protocol_name;
3439 struct _objc_protocol **protocol_list;
3440 struct _objc_protocol_method_list *instance_methods;
3441 struct _objc_protocol_method_list *class_methods;
Mike Stump11289f42009-09-09 15:08:12 +00003442 };
Steve Naroffd9803712009-04-29 16:37:50 +00003443 */
3444 static bool objc_protocol = false;
3445 if (!objc_protocol) {
3446 Result += "\nstruct _objc_protocol {\n";
3447 Result += "\tstruct _objc_protocol_extension *isa;\n";
3448 Result += "\tchar *protocol_name;\n";
3449 Result += "\tstruct _objc_protocol **protocol_list;\n";
3450 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3451 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003452 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003453
Steve Naroffd9803712009-04-29 16:37:50 +00003454 objc_protocol = true;
Chris Lattner388f6e92008-07-21 21:33:21 +00003455 }
Mike Stump11289f42009-09-09 15:08:12 +00003456
Steve Naroffd9803712009-04-29 16:37:50 +00003457 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3458 Result += PDecl->getNameAsString();
3459 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3460 "{\n\t0, \"";
3461 Result += PDecl->getNameAsString();
3462 Result += "\", 0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003463 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003464 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3465 Result += PDecl->getNameAsString();
3466 Result += ", ";
3467 }
3468 else
3469 Result += "0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003470 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003471 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3472 Result += PDecl->getNameAsString();
3473 Result += "\n";
3474 }
3475 else
3476 Result += "0\n";
3477 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003478
Steve Naroffd9803712009-04-29 16:37:50 +00003479 // Mark this protocol as having been generated.
3480 if (!ObjCSynthesizedProtocols.insert(PDecl))
3481 assert(false && "protocol already synthesized");
3482
3483}
3484
3485void RewriteObjC::
3486RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3487 const char *prefix, const char *ClassName,
3488 std::string &Result) {
3489 if (Protocols.empty()) return;
Mike Stump11289f42009-09-09 15:08:12 +00003490
Steve Naroffd9803712009-04-29 16:37:50 +00003491 for (unsigned i = 0; i != Protocols.size(); i++)
3492 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3493
Chris Lattner388f6e92008-07-21 21:33:21 +00003494 // Output the top lovel protocol meta-data for the class.
3495 /* struct _objc_protocol_list {
3496 struct _objc_protocol_list *next;
3497 int protocol_count;
3498 struct _objc_protocol *class_protocols[];
3499 }
3500 */
3501 Result += "\nstatic struct {\n";
3502 Result += "\tstruct _objc_protocol_list *next;\n";
3503 Result += "\tint protocol_count;\n";
3504 Result += "\tstruct _objc_protocol *class_protocols[";
3505 Result += utostr(Protocols.size());
3506 Result += "];\n} _OBJC_";
3507 Result += prefix;
3508 Result += "_PROTOCOLS_";
3509 Result += ClassName;
3510 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3511 "{\n\t0, ";
3512 Result += utostr(Protocols.size());
3513 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003514
Chris Lattner388f6e92008-07-21 21:33:21 +00003515 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003516 Result += Protocols[0]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003517 Result += " \n";
Mike Stump11289f42009-09-09 15:08:12 +00003518
Chris Lattner388f6e92008-07-21 21:33:21 +00003519 for (unsigned i = 1; i != Protocols.size(); i++) {
3520 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003521 Result += Protocols[i]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003522 Result += "\n";
3523 }
3524 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003525}
3526
Steve Naroffd9803712009-04-29 16:37:50 +00003527
Mike Stump11289f42009-09-09 15:08:12 +00003528/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003529/// implementation.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003530void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003531 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003532 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003533 // Find category declaration for this implementation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003534 ObjCCategoryDecl *CDecl;
Mike Stump11289f42009-09-09 15:08:12 +00003535 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003536 CDecl = CDecl->getNextClassCategory())
3537 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3538 break;
Mike Stump11289f42009-09-09 15:08:12 +00003539
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003540 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003541 FullCategoryName += '_';
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003542 FullCategoryName += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003543
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003544 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003545 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003546 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003547
3548 // If any of our property implementations have associated getters or
3549 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003550 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3551 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003552 Prop != PropEnd; ++Prop) {
3553 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3554 continue;
3555 if (!(*Prop)->getPropertyIvarDecl())
3556 continue;
3557 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3558 if (!PD)
3559 continue;
3560 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3561 InstanceMethods.push_back(Getter);
3562 if (PD->isReadOnly())
3563 continue;
3564 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3565 InstanceMethods.push_back(Setter);
3566 }
3567 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003568 true, "CATEGORY_", FullCategoryName.c_str(),
3569 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003570
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003571 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003572 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003573 false, "CATEGORY_", FullCategoryName.c_str(),
3574 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003575
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003576 // Protocols referenced in class declaration?
Fariborz Jahanian989e0392007-11-13 22:09:49 +00003577 // Null CDecl is case of a category implementation with no category interface
3578 if (CDecl)
Steve Naroffd9803712009-04-29 16:37:50 +00003579 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3580 FullCategoryName.c_str(), Result);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003581 /* struct _objc_category {
3582 char *category_name;
3583 char *class_name;
3584 struct _objc_method_list *instance_methods;
3585 struct _objc_method_list *class_methods;
3586 struct _objc_protocol_list *protocols;
3587 // Objective-C 1.0 extensions
3588 uint32_t size; // sizeof (struct _objc_category)
Mike Stump11289f42009-09-09 15:08:12 +00003589 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003590 // @property decl.
Mike Stump11289f42009-09-09 15:08:12 +00003591 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003592 */
Mike Stump11289f42009-09-09 15:08:12 +00003593
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003594 static bool objc_category = false;
3595 if (!objc_category) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003596 Result += "\nstruct _objc_category {\n";
3597 Result += "\tchar *category_name;\n";
3598 Result += "\tchar *class_name;\n";
3599 Result += "\tstruct _objc_method_list *instance_methods;\n";
3600 Result += "\tstruct _objc_method_list *class_methods;\n";
3601 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003602 Result += "\tunsigned int size;\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003603 Result += "\tstruct _objc_property_list *instance_properties;\n";
3604 Result += "};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003605 objc_category = true;
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003606 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003607 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3608 Result += FullCategoryName;
Steve Naroffb327e492008-03-12 17:18:30 +00003609 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003610 Result += IDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003611 Result += "\"\n\t, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003612 Result += ClassDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003613 Result += "\"\n";
Mike Stump11289f42009-09-09 15:08:12 +00003614
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003615 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003616 Result += "\t, (struct _objc_method_list *)"
3617 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3618 Result += FullCategoryName;
3619 Result += "\n";
3620 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003621 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003622 Result += "\t, 0\n";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003623 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003624 Result += "\t, (struct _objc_method_list *)"
3625 "&_OBJC_CATEGORY_CLASS_METHODS_";
3626 Result += FullCategoryName;
3627 Result += "\n";
3628 }
3629 else
3630 Result += "\t, 0\n";
Mike Stump11289f42009-09-09 15:08:12 +00003631
Chris Lattnerf5b77512009-02-20 18:18:36 +00003632 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump11289f42009-09-09 15:08:12 +00003633 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003634 Result += FullCategoryName;
3635 Result += "\n";
3636 }
3637 else
3638 Result += "\t, 0\n";
3639 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003640}
3641
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003642/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3643/// ivar offset.
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00003644void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCContainerDecl *IDecl,
Mike Stump11289f42009-09-09 15:08:12 +00003645 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003646 std::string &Result) {
Steve Naroffde7d0f62008-07-16 18:22:22 +00003647 if (ivar->isBitField()) {
3648 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3649 // place all bitfields at offset 0.
3650 Result += "0";
3651 } else {
3652 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003653 Result += IDecl->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003654 if (LangOpts.Microsoft)
3655 Result += "_IMPL";
3656 Result += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003657 Result += ivar->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003658 Result += ")";
3659 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003660}
3661
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003662//===----------------------------------------------------------------------===//
3663// Meta Data Emission
3664//===----------------------------------------------------------------------===//
3665
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003666void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003667 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003668 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00003669
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003670 // Explictly declared @interface's are already synthesized.
Steve Naroffaac654a2009-04-20 20:09:33 +00003671 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump11289f42009-09-09 15:08:12 +00003672 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003673 // produce correct synthesis as yet.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003674 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003675 }
Mike Stump11289f42009-09-09 15:08:12 +00003676
Chris Lattner30d23e82007-12-12 07:56:42 +00003677 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003678 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump11289f42009-09-09 15:08:12 +00003679 ? IDecl->ivar_size()
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003680 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003681 if (NumIvars > 0) {
3682 static bool objc_ivar = false;
3683 if (!objc_ivar) {
3684 /* struct _objc_ivar {
3685 char *ivar_name;
3686 char *ivar_type;
3687 int ivar_offset;
Mike Stump11289f42009-09-09 15:08:12 +00003688 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003689 */
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003690 Result += "\nstruct _objc_ivar {\n";
3691 Result += "\tchar *ivar_name;\n";
3692 Result += "\tchar *ivar_type;\n";
3693 Result += "\tint ivar_offset;\n";
3694 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003695
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003696 objc_ivar = true;
3697 }
3698
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003699 /* struct {
3700 int ivar_count;
3701 struct _objc_ivar ivar_list[nIvars];
Mike Stump11289f42009-09-09 15:08:12 +00003702 };
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003703 */
Mike Stump11289f42009-09-09 15:08:12 +00003704 Result += "\nstatic struct {\n";
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003705 Result += "\tint ivar_count;\n";
3706 Result += "\tstruct _objc_ivar ivar_list[";
3707 Result += utostr(NumIvars);
3708 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003709 Result += IDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003710 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003711 "{\n\t";
3712 Result += utostr(NumIvars);
3713 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003714
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003715 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor5f662052009-04-23 03:23:08 +00003716 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003717 if (!IDecl->ivar_empty()) {
Fariborz Jahanianaef66222010-02-19 00:31:17 +00003718 for (ObjCInterfaceDecl::ivar_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003719 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor5f662052009-04-23 03:23:08 +00003720 IV != IVEnd; ++IV)
3721 IVars.push_back(*IV);
Fariborz Jahanianaef66222010-02-19 00:31:17 +00003722 IVI = IDecl->ivar_begin();
3723 IVE = IDecl->ivar_end();
Chris Lattner30d23e82007-12-12 07:56:42 +00003724 } else {
3725 IVI = CDecl->ivar_begin();
3726 IVE = CDecl->ivar_end();
3727 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003728 Result += "\t,{{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003729 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003730 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003731 std::string TmpString, StrEncoding;
3732 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3733 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003734 Result += StrEncoding;
3735 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003736 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003737 Result += "}\n";
Chris Lattner30d23e82007-12-12 07:56:42 +00003738 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003739 Result += "\t ,{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003740 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003741 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003742 std::string TmpString, StrEncoding;
3743 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3744 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003745 Result += StrEncoding;
3746 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003747 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003748 Result += "}\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003749 }
Mike Stump11289f42009-09-09 15:08:12 +00003750
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003751 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003752 }
Mike Stump11289f42009-09-09 15:08:12 +00003753
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003754 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003755 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003756 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003757
3758 // If any of our property implementations have associated getters or
3759 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003760 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3761 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003762 Prop != PropEnd; ++Prop) {
3763 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3764 continue;
3765 if (!(*Prop)->getPropertyIvarDecl())
3766 continue;
3767 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3768 if (!PD)
3769 continue;
3770 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3771 InstanceMethods.push_back(Getter);
3772 if (PD->isReadOnly())
3773 continue;
3774 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3775 InstanceMethods.push_back(Setter);
3776 }
3777 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003778 true, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003779
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003780 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003781 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003782 false, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003783
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003784 // Protocols referenced in class declaration?
Steve Naroffd9803712009-04-29 16:37:50 +00003785 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3786 "CLASS", CDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003787
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003788 // Declaration of class/meta-class metadata
3789 /* struct _objc_class {
3790 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003791 const char *super_class_name;
3792 char *name;
3793 long version;
3794 long info;
3795 long instance_size;
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003796 struct _objc_ivar_list *ivars;
3797 struct _objc_method_list *methods;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003798 struct objc_cache *cache;
3799 struct objc_protocol_list *protocols;
3800 const char *ivar_layout;
3801 struct _objc_class_ext *ext;
Mike Stump11289f42009-09-09 15:08:12 +00003802 };
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003803 */
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003804 static bool objc_class = false;
3805 if (!objc_class) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003806 Result += "\nstruct _objc_class {\n";
3807 Result += "\tstruct _objc_class *isa;\n";
3808 Result += "\tconst char *super_class_name;\n";
3809 Result += "\tchar *name;\n";
3810 Result += "\tlong version;\n";
3811 Result += "\tlong info;\n";
3812 Result += "\tlong instance_size;\n";
3813 Result += "\tstruct _objc_ivar_list *ivars;\n";
3814 Result += "\tstruct _objc_method_list *methods;\n";
3815 Result += "\tstruct objc_cache *cache;\n";
3816 Result += "\tstruct _objc_protocol_list *protocols;\n";
3817 Result += "\tconst char *ivar_layout;\n";
3818 Result += "\tstruct _objc_class_ext *ext;\n";
3819 Result += "};\n";
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003820 objc_class = true;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003821 }
Mike Stump11289f42009-09-09 15:08:12 +00003822
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003823 // Meta-class metadata generation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003824 ObjCInterfaceDecl *RootClass = 0;
3825 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003826 while (SuperClass) {
3827 RootClass = SuperClass;
3828 SuperClass = SuperClass->getSuperClass();
3829 }
3830 SuperClass = CDecl->getSuperClass();
Mike Stump11289f42009-09-09 15:08:12 +00003831
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003832 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003833 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003834 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003835 "{\n\t(struct _objc_class *)\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003836 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003837 Result += "\"";
3838
3839 if (SuperClass) {
3840 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003841 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003842 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003843 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003844 Result += "\"";
3845 }
3846 else {
3847 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003848 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003849 Result += "\"";
3850 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003851 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003852 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003853 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003854 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff0b844f02008-03-11 18:14:26 +00003855 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003856 Result += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003857 Result += "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003858 }
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003859 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003860 Result += ", 0\n";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003861 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003862 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003863 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003864 Result += ",0,0\n";
3865 }
Fariborz Jahanian486f7182007-10-24 20:54:23 +00003866 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003867 Result += "\t,0,0,0,0\n";
3868 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003869
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003870 // class metadata generation.
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003871 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003872 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003873 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003874 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003875 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003876 if (SuperClass) {
3877 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003878 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003879 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003880 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003881 Result += "\"";
3882 }
3883 else {
3884 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003885 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003886 Result += "\"";
3887 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003888 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003889 Result += ", 0,1";
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003890 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003891 Result += ",0";
3892 else {
3893 // class has size. Must synthesize its size.
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00003894 Result += ",sizeof(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003895 Result += CDecl->getNameAsString();
Steve Naroff14a07462008-03-10 23:33:22 +00003896 if (LangOpts.Microsoft)
3897 Result += "_IMPL";
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003898 Result += ")";
3899 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003900 if (NumIvars > 0) {
Steve Naroff17978c42008-03-11 17:37:02 +00003901 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003902 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003903 Result += "\n\t";
3904 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003905 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003906 Result += ",0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003907 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003908 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003909 Result += CDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003910 Result += ", 0\n\t";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003911 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003912 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003913 Result += ",0,0";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003914 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003915 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003916 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003917 Result += ", 0,0\n";
3918 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003919 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003920 Result += ",0,0,0\n";
3921 Result += "};\n";
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003922}
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003923
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003924/// RewriteImplementations - This routine rewrites all method implementations
3925/// and emits meta-data.
3926
Steve Narofff8cfd162008-11-13 20:07:04 +00003927void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003928 int ClsDefCount = ClassImplementation.size();
3929 int CatDefCount = CategoryImplementation.size();
Mike Stump11289f42009-09-09 15:08:12 +00003930
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003931 // Rewrite implemented methods
3932 for (int i = 0; i < ClsDefCount; i++)
3933 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003934
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00003935 for (int i = 0; i < CatDefCount; i++)
3936 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofff8cfd162008-11-13 20:07:04 +00003937}
Mike Stump11289f42009-09-09 15:08:12 +00003938
Steve Narofff8cfd162008-11-13 20:07:04 +00003939void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3940 int ClsDefCount = ClassImplementation.size();
3941 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00003942
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003943 // For each implemented class, write out all its meta data.
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003944 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003945 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump11289f42009-09-09 15:08:12 +00003946
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003947 // For each implemented category, write out all its meta data.
3948 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003949 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroffd9803712009-04-29 16:37:50 +00003950
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003951 // Write objc_symtab metadata
3952 /*
3953 struct _objc_symtab
3954 {
3955 long sel_ref_cnt;
3956 SEL *refs;
3957 short cls_def_cnt;
3958 short cat_def_cnt;
3959 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump11289f42009-09-09 15:08:12 +00003960 };
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003961 */
Mike Stump11289f42009-09-09 15:08:12 +00003962
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003963 Result += "\nstruct _objc_symtab {\n";
3964 Result += "\tlong sel_ref_cnt;\n";
3965 Result += "\tSEL *refs;\n";
3966 Result += "\tshort cls_def_cnt;\n";
3967 Result += "\tshort cat_def_cnt;\n";
3968 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3969 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003970
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003971 Result += "static struct _objc_symtab "
Steve Naroffb327e492008-03-12 17:18:30 +00003972 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003973 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003974 + ", " + utostr(CatDefCount) + "\n";
3975 for (int i = 0; i < ClsDefCount; i++) {
3976 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003977 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003978 Result += "\n";
3979 }
Mike Stump11289f42009-09-09 15:08:12 +00003980
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003981 for (int i = 0; i < CatDefCount; i++) {
3982 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003983 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003984 Result += "_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003985 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003986 Result += "\n";
3987 }
Mike Stump11289f42009-09-09 15:08:12 +00003988
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003989 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003990
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003991 // Write objc_module metadata
Mike Stump11289f42009-09-09 15:08:12 +00003992
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003993 /*
3994 struct _objc_module {
3995 long version;
3996 long size;
3997 const char *name;
3998 struct _objc_symtab *symtab;
3999 }
4000 */
Mike Stump11289f42009-09-09 15:08:12 +00004001
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004002 Result += "\nstruct _objc_module {\n";
4003 Result += "\tlong version;\n";
4004 Result += "\tlong size;\n";
4005 Result += "\tconst char *name;\n";
4006 Result += "\tstruct _objc_symtab *symtab;\n";
4007 Result += "};\n\n";
4008 Result += "static struct _objc_module "
Steve Naroffb327e492008-03-12 17:18:30 +00004009 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00004010 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00004011 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004012 Result += "};\n\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00004013
4014 if (LangOpts.Microsoft) {
Steve Naroffd9803712009-04-29 16:37:50 +00004015 if (ProtocolExprDecls.size()) {
4016 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
4017 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump11289f42009-09-09 15:08:12 +00004018 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00004019 E = ProtocolExprDecls.end(); I != E; ++I) {
4020 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
4021 Result += (*I)->getNameAsString();
4022 Result += " = &_OBJC_PROTOCOL_";
4023 Result += (*I)->getNameAsString();
4024 Result += ";\n";
4025 }
4026 Result += "#pragma data_seg(pop)\n\n";
4027 }
Steve Naroff945a3b12008-03-10 20:43:59 +00004028 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffcab93d52008-05-07 00:06:16 +00004029 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00004030 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
4031 Result += "&_OBJC_MODULES;\n";
4032 Result += "#pragma data_seg(pop)\n\n";
4033 }
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004034}
Chris Lattnera7c19fe2007-10-16 22:36:42 +00004035
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004036void RewriteObjC::RewriteByRefString(std::string &ResultStr,
4037 const std::string &Name,
4038 ValueDecl *VD) {
4039 assert(BlockByRefDeclNo.count(VD) &&
4040 "RewriteByRefString: ByRef decl missing");
4041 ResultStr += "struct __Block_byref_" + Name +
4042 "_" + utostr(BlockByRefDeclNo[VD]) ;
4043}
4044
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004045static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4046 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4047 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4048 return false;
4049}
4050
Steve Naroff677ab3a2008-10-27 17:20:55 +00004051std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4052 const char *funcName,
4053 std::string Tag) {
4054 const FunctionType *AFT = CE->getFunctionType();
4055 QualType RT = AFT->getResultType();
4056 std::string StructRef = "struct " + Tag;
4057 std::string S = "static " + RT.getAsString() + " __" +
4058 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00004059
Steve Naroff677ab3a2008-10-27 17:20:55 +00004060 BlockDecl *BD = CE->getBlockDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004061
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004062 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump11289f42009-09-09 15:08:12 +00004063 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Narofff26a1d42009-02-02 17:19:26 +00004064 // block (to reference imported block decl refs).
4065 S += "(" + StructRef + " *__cself)";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004066 } else if (BD->param_empty()) {
4067 S += "(" + StructRef + " *__cself)";
4068 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004069 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004070 assert(FT && "SynthesizeBlockFunc: No function proto");
4071 S += '(';
4072 // first add the implicit argument.
4073 S += StructRef + " *__cself, ";
4074 std::string ParamStr;
4075 for (BlockDecl::param_iterator AI = BD->param_begin(),
4076 E = BD->param_end(); AI != E; ++AI) {
4077 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004078 ParamStr = (*AI)->getNameAsString();
Douglas Gregor7de59662009-05-29 20:38:28 +00004079 (*AI)->getType().getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004080 S += ParamStr;
4081 }
4082 if (FT->isVariadic()) {
4083 if (!BD->param_empty()) S += ", ";
4084 S += "...";
4085 }
4086 S += ')';
4087 }
4088 S += " {\n";
Mike Stump11289f42009-09-09 15:08:12 +00004089
Steve Naroff677ab3a2008-10-27 17:20:55 +00004090 // Create local declarations to avoid rewriting all closure decl ref exprs.
4091 // First, emit a declaration for all "by ref" decls.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004092 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004093 E = BlockByRefDecls.end(); I != E; ++I) {
4094 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004095 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004096 std::string TypeString;
4097 RewriteByRefString(TypeString, Name, (*I));
4098 TypeString += " *";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004099 Name = TypeString + Name;
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004100 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump11289f42009-09-09 15:08:12 +00004101 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004102 // Next, emit a declaration for all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004103 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004104 E = BlockByCopyDecls.end(); I != E; ++I) {
4105 S += " ";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004106 // Handle nested closure invocation. For example:
4107 //
4108 // void (^myImportedClosure)(void);
4109 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00004110 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00004111 // void (^anotherClosure)(void);
4112 // anotherClosure = ^(void) {
4113 // myImportedClosure(); // import and invoke the closure
4114 // };
4115 //
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00004116 if (isTopLevelBlockPointerType((*I)->getType())) {
4117 RewriteBlockPointerTypeVariable(S, (*I));
4118 S += " = (";
4119 RewriteBlockPointerType(S, (*I)->getType());
4120 S += ")";
4121 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4122 }
4123 else {
Fariborz Jahanianb6a68c02010-02-16 17:26:03 +00004124 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004125 QualType QT = (*I)->getType();
4126 if (HasLocalVariableExternalStorage(*I))
4127 QT = Context->getPointerType(QT);
4128 QT.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00004129 S += Name + " = __cself->" +
4130 (*I)->getNameAsString() + "; // bound by copy\n";
4131 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004132 }
4133 std::string RewrittenStr = RewrittenBlockExprs[CE];
4134 const char *cstr = RewrittenStr.c_str();
4135 while (*cstr++ != '{') ;
4136 S += cstr;
4137 S += "\n";
4138 return S;
4139}
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00004140
Steve Naroff677ab3a2008-10-27 17:20:55 +00004141std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4142 const char *funcName,
4143 std::string Tag) {
4144 std::string StructRef = "struct " + Tag;
4145 std::string S = "static void __";
Mike Stump11289f42009-09-09 15:08:12 +00004146
Steve Naroff677ab3a2008-10-27 17:20:55 +00004147 S += funcName;
4148 S += "_block_copy_" + utostr(i);
4149 S += "(" + StructRef;
4150 S += "*dst, " + StructRef;
4151 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00004152 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004153 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00004154 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004155 S += (*I)->getNameAsString();
Steve Naroff5ac4eac2008-12-11 20:51:38 +00004156 S += ", (void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004157 S += (*I)->getNameAsString();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004158 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004159 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00004160 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004161 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004162 }
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00004163 S += "}\n";
4164
Steve Naroff677ab3a2008-10-27 17:20:55 +00004165 S += "\nstatic void __";
4166 S += funcName;
4167 S += "_block_dispose_" + utostr(i);
4168 S += "(" + StructRef;
4169 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00004170 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004171 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00004172 S += "_Block_object_dispose((void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004173 S += (*I)->getNameAsString();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004174 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004175 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00004176 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004177 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004178 }
Mike Stump11289f42009-09-09 15:08:12 +00004179 S += "}\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004180 return S;
4181}
4182
Steve Naroff30484702009-12-06 21:14:13 +00004183std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4184 std::string Desc) {
Steve Naroff295570a2008-10-30 12:09:33 +00004185 std::string S = "\nstruct " + Tag;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004186 std::string Constructor = " " + Tag;
Mike Stump11289f42009-09-09 15:08:12 +00004187
Steve Naroff677ab3a2008-10-27 17:20:55 +00004188 S += " {\n struct __block_impl impl;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004189 S += " struct " + Desc;
4190 S += "* Desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00004191
Steve Naroff30484702009-12-06 21:14:13 +00004192 Constructor += "(void *fp, "; // Invoke function pointer.
4193 Constructor += "struct " + Desc; // Descriptor pointer.
4194 Constructor += " *desc";
Mike Stump11289f42009-09-09 15:08:12 +00004195
Steve Naroff677ab3a2008-10-27 17:20:55 +00004196 if (BlockDeclRefs.size()) {
4197 // Output all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004198 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004199 E = BlockByCopyDecls.end(); I != E; ++I) {
4200 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004201 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004202 std::string ArgName = "_" + FieldName;
4203 // Handle nested closure invocation. For example:
4204 //
4205 // void (^myImportedBlock)(void);
4206 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00004207 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00004208 // void (^anotherBlock)(void);
4209 // anotherBlock = ^(void) {
4210 // myImportedBlock(); // import and invoke the closure
4211 // };
4212 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00004213 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004214 S += "struct __block_impl *";
4215 Constructor += ", void *" + ArgName;
4216 } else {
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004217 QualType QT = (*I)->getType();
4218 if (HasLocalVariableExternalStorage(*I))
4219 QT = Context->getPointerType(QT);
4220 QT.getAsStringInternal(FieldName, Context->PrintingPolicy);
4221 QT.getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004222 Constructor += ", " + ArgName;
4223 }
4224 S += FieldName + ";\n";
4225 }
4226 // Output all "by ref" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004227 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004228 E = BlockByRefDecls.end(); I != E; ++I) {
4229 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004230 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004231 std::string ArgName = "_" + FieldName;
4232 // Handle nested closure invocation. For example:
4233 //
4234 // void (^myImportedBlock)(void);
4235 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00004236 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00004237 // void (^anotherBlock)(void);
4238 // anotherBlock = ^(void) {
4239 // myImportedBlock(); // import and invoke the closure
4240 // };
4241 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00004242 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004243 S += "struct __block_impl *";
4244 Constructor += ", void *" + ArgName;
4245 } else {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004246 std::string TypeString;
4247 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004248 TypeString += " *";
4249 FieldName = TypeString + FieldName;
4250 ArgName = TypeString + ArgName;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004251 Constructor += ", " + ArgName;
4252 }
4253 S += FieldName + "; // by ref\n";
4254 }
4255 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004256 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00004257 if (GlobalVarDecl)
4258 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4259 else
4260 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004261 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump11289f42009-09-09 15:08:12 +00004262
Steve Naroff30484702009-12-06 21:14:13 +00004263 Constructor += " Desc = desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00004264
Steve Naroff677ab3a2008-10-27 17:20:55 +00004265 // Initialize all "by copy" arguments.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004266 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004267 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004268 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004269 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00004270 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004271 Constructor += Name + " = (struct __block_impl *)_";
4272 else
4273 Constructor += Name + " = _";
4274 Constructor += Name + ";\n";
4275 }
4276 // Initialize all "by ref" arguments.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004277 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004278 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004279 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004280 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00004281 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004282 Constructor += Name + " = (struct __block_impl *)_";
4283 else
4284 Constructor += Name + " = _";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004285 Constructor += Name + "->__forwarding;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004286 }
4287 } else {
4288 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004289 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00004290 if (GlobalVarDecl)
4291 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4292 else
4293 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004294 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4295 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004296 }
4297 Constructor += " ";
4298 Constructor += "}\n";
4299 S += Constructor;
4300 S += "};\n";
4301 return S;
4302}
4303
Steve Naroff30484702009-12-06 21:14:13 +00004304std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4305 std::string ImplTag, int i,
4306 const char *FunName,
4307 unsigned hasCopy) {
4308 std::string S = "\nstatic struct " + DescTag;
4309
4310 S += " {\n unsigned long reserved;\n";
4311 S += " unsigned long Block_size;\n";
4312 if (hasCopy) {
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004313 S += " void (*copy)(struct ";
4314 S += ImplTag; S += "*, struct ";
4315 S += ImplTag; S += "*);\n";
4316
4317 S += " void (*dispose)(struct ";
4318 S += ImplTag; S += "*);\n";
Steve Naroff30484702009-12-06 21:14:13 +00004319 }
4320 S += "} ";
4321
4322 S += DescTag + "_DATA = { 0, sizeof(struct ";
4323 S += ImplTag + ")";
4324 if (hasCopy) {
4325 S += ", __" + std::string(FunName) + "_block_copy_" + utostr(i);
4326 S += ", __" + std::string(FunName) + "_block_dispose_" + utostr(i);
4327 }
4328 S += "};\n";
4329 return S;
4330}
4331
Steve Naroff677ab3a2008-10-27 17:20:55 +00004332void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004333 const char *FunName) {
4334 // Insert declaration for the function in which block literal is used.
Fariborz Jahanian5c26eee2010-01-15 18:14:52 +00004335 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004336 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00004337 bool RewriteSC = (GlobalVarDecl &&
4338 !Blocks.empty() &&
4339 GlobalVarDecl->getStorageClass() == VarDecl::Static &&
4340 GlobalVarDecl->getType().getCVRQualifiers());
4341 if (RewriteSC) {
4342 std::string SC(" void __");
4343 SC += GlobalVarDecl->getNameAsString();
4344 SC += "() {}";
4345 InsertText(FunLocStart, SC);
4346 }
4347
Steve Naroff677ab3a2008-10-27 17:20:55 +00004348 // Insert closures that were part of the function.
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004349 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4350 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004351 // Need to copy-in the inner copied-in variables not actually used in this
4352 // block.
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004353 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4354 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
4355 ValueDecl *VD = Exp->getDecl();
4356 BlockDeclRefs.push_back(Exp);
4357 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
4358 BlockByCopyDeclsPtrSet.insert(VD);
4359 BlockByCopyDecls.push_back(VD);
4360 }
4361 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4362 BlockByRefDeclsPtrSet.insert(VD);
4363 BlockByRefDecls.push_back(VD);
4364 }
4365 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004366
Steve Naroff30484702009-12-06 21:14:13 +00004367 std::string ImplTag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
4368 std::string DescTag = "__" + std::string(FunName) + "_block_desc_" + utostr(i);
Mike Stump11289f42009-09-09 15:08:12 +00004369
Steve Naroff30484702009-12-06 21:14:13 +00004370 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004371
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004372 InsertText(FunLocStart, CI);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004373
Steve Naroff30484702009-12-06 21:14:13 +00004374 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump11289f42009-09-09 15:08:12 +00004375
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004376 InsertText(FunLocStart, CF);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004377
4378 if (ImportedBlockDecls.size()) {
Steve Naroff30484702009-12-06 21:14:13 +00004379 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004380 InsertText(FunLocStart, HF);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004381 }
Steve Naroff30484702009-12-06 21:14:13 +00004382 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4383 ImportedBlockDecls.size() > 0);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004384 InsertText(FunLocStart, BD);
Mike Stump11289f42009-09-09 15:08:12 +00004385
Steve Naroff677ab3a2008-10-27 17:20:55 +00004386 BlockDeclRefs.clear();
4387 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004388 BlockByRefDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004389 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004390 BlockByCopyDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004391 ImportedBlockDecls.clear();
4392 }
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00004393 if (RewriteSC) {
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004394 // Must insert any 'const/volatile/static here. Since it has been
4395 // removed as result of rewriting of block literals.
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004396 std::string SC;
4397 if (GlobalVarDecl->getStorageClass() == VarDecl::Static)
4398 SC = "static ";
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004399 if (GlobalVarDecl->getType().isConstQualified())
4400 SC += "const ";
4401 if (GlobalVarDecl->getType().isVolatileQualified())
4402 SC += "volatile ";
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00004403 if (GlobalVarDecl->getType().isRestrictQualified())
4404 SC += "restrict ";
4405 InsertText(FunLocStart, SC);
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004406 }
4407
Steve Naroff677ab3a2008-10-27 17:20:55 +00004408 Blocks.clear();
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004409 InnerDeclRefsCount.clear();
4410 InnerDeclRefs.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004411 RewrittenBlockExprs.clear();
4412}
4413
4414void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4415 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner86d7d912008-11-24 03:54:41 +00004416 const char *FuncName = FD->getNameAsCString();
Mike Stump11289f42009-09-09 15:08:12 +00004417
Steve Naroff677ab3a2008-10-27 17:20:55 +00004418 SynthesizeBlockLiterals(FunLocStart, FuncName);
4419}
4420
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004421static void BuildUniqueMethodName(std::string &Name,
4422 ObjCMethodDecl *MD) {
4423 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4424 Name = IFace->getNameAsCString();
4425 Name += "__" + MD->getSelector().getAsString();
4426 // Convert colons to underscores.
4427 std::string::size_type loc = 0;
4428 while ((loc = Name.find(":", loc)) != std::string::npos)
4429 Name.replace(loc, 1, "_");
4430}
4431
Steve Naroff677ab3a2008-10-27 17:20:55 +00004432void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff295570a2008-10-30 12:09:33 +00004433 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4434 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianb5f99c32010-01-29 01:55:49 +00004435 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004436 std::string FuncName;
4437 BuildUniqueMethodName(FuncName, MD);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004438 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
4439}
4440
4441void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4442 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4443 CI != E; ++CI)
4444 if (*CI) {
4445 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4446 GetBlockDeclRefExprs(CBE->getBody());
4447 else
4448 GetBlockDeclRefExprs(*CI);
4449 }
4450 // Handle specific things.
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004451 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004452 // FIXME: Handle enums.
4453 if (!isa<FunctionDecl>(CDRE->getDecl()))
4454 BlockDeclRefs.push_back(CDRE);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004455 }
4456 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4457 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
4458 BlockDeclRefExpr *BDRE =
4459 new (Context)BlockDeclRefExpr(DRE->getDecl(), DRE->getType(),
4460 DRE->getLocation(), false);
4461 BlockDeclRefs.push_back(BDRE);
4462 }
4463
Steve Naroff677ab3a2008-10-27 17:20:55 +00004464 return;
4465}
4466
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004467void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4468 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004469 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004470 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4471 CI != E; ++CI)
4472 if (*CI) {
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004473 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4474 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004475 GetInnerBlockDeclRefExprs(CBE->getBody(),
4476 InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004477 InnerContexts);
4478 }
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004479 else
4480 GetInnerBlockDeclRefExprs(*CI,
4481 InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004482 InnerContexts);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004483
4484 }
4485 // Handle specific things.
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004486 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004487 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004488 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004489 InnerBlockDeclRefs.push_back(CDRE);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004490 }
4491 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4492 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4493 if (Var->isFunctionOrMethodVarDecl())
4494 ImportedLocalExternalDecls.insert(Var);
4495 }
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004496
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004497 return;
4498}
4499
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004500Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004501 // Navigate to relevant type information.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004502 const BlockPointerType *CPT = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004503
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004504 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004505 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004506 } else if (const BlockDeclRefExpr *CDRE =
4507 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004508 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004509 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004510 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004511 }
4512 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4513 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4514 }
4515 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4516 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4517 else if (const ConditionalOperator *CEXPR =
4518 dyn_cast<ConditionalOperator>(BlockExp)) {
4519 Expr *LHSExp = CEXPR->getLHS();
4520 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4521 Expr *RHSExp = CEXPR->getRHS();
4522 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4523 Expr *CONDExp = CEXPR->getCond();
4524 ConditionalOperator *CondExpr =
4525 new (Context) ConditionalOperator(CONDExp,
4526 SourceLocation(), cast<Expr>(LHSStmt),
4527 SourceLocation(), cast<Expr>(RHSStmt),
4528 Exp->getType());
4529 return CondExpr;
Fariborz Jahanian6ab7ed42009-12-18 01:15:21 +00004530 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4531 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004532 } else {
4533 assert(1 && "RewriteBlockClass: Bad type");
4534 }
4535 assert(CPT && "RewriteBlockClass: Bad type");
John McCall9dd450b2009-09-21 23:43:11 +00004536 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004537 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004538 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004539 // FTP will be null for closures that don't take arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004540
Steve Naroff350b6652008-10-30 10:07:53 +00004541 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
4542 SourceLocation(),
4543 &Context->Idents.get("__block_impl"));
4544 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff677ab3a2008-10-27 17:20:55 +00004545
Steve Naroff350b6652008-10-30 10:07:53 +00004546 // Generate a funky cast.
4547 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00004548
Steve Naroff350b6652008-10-30 10:07:53 +00004549 // Push the block argument type.
4550 ArgTypes.push_back(PtrBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004551 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004552 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff350b6652008-10-30 10:07:53 +00004553 E = FTP->arg_type_end(); I && (I != E); ++I) {
4554 QualType t = *I;
4555 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00004556 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004557 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff350b6652008-10-30 10:07:53 +00004558 t = Context->getPointerType(BPT->getPointeeType());
4559 }
4560 ArgTypes.push_back(t);
4561 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004562 }
Steve Naroff350b6652008-10-30 10:07:53 +00004563 // Now do the pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00004564 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00004565 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0,
4566 false, false, 0, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004567 FunctionType::ExtInfo());
Mike Stump11289f42009-09-09 15:08:12 +00004568
Steve Naroff350b6652008-10-30 10:07:53 +00004569 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump11289f42009-09-09 15:08:12 +00004570
John McCall97513962010-01-15 18:39:57 +00004571 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4572 CastExpr::CK_Unknown,
4573 const_cast<Expr*>(BlockExp));
Steve Naroff350b6652008-10-30 10:07:53 +00004574 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00004575 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4576 BlkCast);
Steve Naroff350b6652008-10-30 10:07:53 +00004577 //PE->dump();
Mike Stump11289f42009-09-09 15:08:12 +00004578
Douglas Gregor91f84212008-12-11 16:49:14 +00004579 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00004580 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004581 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek5a201952009-02-07 01:47:29 +00004582 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4583 FD->getType());
Mike Stump11289f42009-09-09 15:08:12 +00004584
John McCall97513962010-01-15 18:39:57 +00004585 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4586 CastExpr::CK_Unknown, ME);
Ted Kremenek5a201952009-02-07 01:47:29 +00004587 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump11289f42009-09-09 15:08:12 +00004588
Steve Naroff350b6652008-10-30 10:07:53 +00004589 llvm::SmallVector<Expr*, 8> BlkExprs;
4590 // Add the implicit argument.
4591 BlkExprs.push_back(BlkCast);
4592 // Add the user arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004593 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004594 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff350b6652008-10-30 10:07:53 +00004595 BlkExprs.push_back(*I);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004596 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004597 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4598 BlkExprs.size(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004599 Exp->getType(), SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00004600 return CE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004601}
4602
4603void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004604 Stmt *BlockCall = SynthesizeBlockCall(Exp, Exp->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00004605 ReplaceStmt(Exp, BlockCall);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004606}
4607
Steve Naroffd9803712009-04-29 16:37:50 +00004608// We need to return the rewritten expression to handle cases where the
4609// BlockDeclRefExpr is embedded in another expression being rewritten.
4610// For example:
4611//
4612// int main() {
4613// __block Foo *f;
4614// __block int i;
Mike Stump11289f42009-09-09 15:08:12 +00004615//
Steve Naroffd9803712009-04-29 16:37:50 +00004616// void (^myblock)() = ^() {
4617// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4618// i = 77;
4619// };
4620//}
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004621Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanian25c07fa2009-12-23 19:26:34 +00004622 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004623 // for each DeclRefExp where BYREFVAR is name of the variable.
4624 ValueDecl *VD;
4625 bool isArrow = true;
4626 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4627 VD = BDRE->getDecl();
4628 else {
4629 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4630 isArrow = false;
4631 }
4632
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004633 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4634 &Context->Idents.get("__forwarding"),
4635 Context->VoidPtrTy, 0,
4636 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004637 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4638 FD, SourceLocation(),
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004639 FD->getType());
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004640
4641 const char *Name = VD->getNameAsCString();
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004642 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4643 &Context->Idents.get(Name),
4644 Context->VoidPtrTy, 0,
4645 /*BitWidth=*/0, /*Mutable=*/true);
4646 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004647 DeclRefExp->getType());
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004648
4649
4650
Steve Narofff26a1d42009-02-02 17:19:26 +00004651 // Need parens to enforce precedence.
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004652 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4653 ME);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004654 ReplaceStmt(DeclRefExp, PE);
Steve Naroffd9803712009-04-29 16:37:50 +00004655 return PE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004656}
4657
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004658// Rewrites the imported local variable V with external storage
4659// (static, extern, etc.) as *V
4660//
4661Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4662 ValueDecl *VD = DRE->getDecl();
4663 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4664 if (!ImportedLocalExternalDecls.count(Var))
4665 return DRE;
4666 Expr *Exp = new (Context) UnaryOperator(DRE, UnaryOperator::Deref,
4667 DRE->getType(), DRE->getLocation());
4668 // Need parens to enforce precedence.
4669 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4670 Exp);
4671 ReplaceStmt(DRE, PE);
4672 return PE;
4673}
4674
Steve Naroffc989a7b2008-11-03 23:29:32 +00004675void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4676 SourceLocation LocStart = CE->getLParenLoc();
4677 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofff4b992a2008-10-28 20:29:00 +00004678
4679 // Need to avoid trying to rewrite synthesized casts.
4680 if (LocStart.isInvalid())
4681 return;
Steve Naroff3e7ced12008-11-03 11:20:24 +00004682 // Need to avoid trying to rewrite casts contained in macros.
4683 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4684 return;
Mike Stump11289f42009-09-09 15:08:12 +00004685
Steve Naroff677ab3a2008-10-27 17:20:55 +00004686 const char *startBuf = SM->getCharacterData(LocStart);
4687 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004688 QualType QT = CE->getType();
4689 const Type* TypePtr = QT->getAs<Type>();
4690 if (isa<TypeOfExprType>(TypePtr)) {
4691 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4692 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4693 std::string TypeAsString = "(";
Fariborz Jahanianf5067912010-02-18 01:20:22 +00004694 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004695 TypeAsString += ")";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004696 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004697 return;
4698 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004699 // advance the location to startArgList.
4700 const char *argPtr = startBuf;
Mike Stump11289f42009-09-09 15:08:12 +00004701
Steve Naroff677ab3a2008-10-27 17:20:55 +00004702 while (*argPtr++ && (argPtr < endBuf)) {
4703 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004704 case '^':
4705 // Replace the '^' with '*'.
4706 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004707 ReplaceText(LocStart, 1, "*");
Mike Stump281d6d72010-01-20 02:03:14 +00004708 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004709 }
4710 }
4711 return;
4712}
4713
4714void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4715 SourceLocation DeclLoc = FD->getLocation();
4716 unsigned parenCount = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004717
Steve Naroff677ab3a2008-10-27 17:20:55 +00004718 // We have 1 or more arguments that have closure pointers.
4719 const char *startBuf = SM->getCharacterData(DeclLoc);
4720 const char *startArgList = strchr(startBuf, '(');
Mike Stump11289f42009-09-09 15:08:12 +00004721
Steve Naroff677ab3a2008-10-27 17:20:55 +00004722 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004723
Steve Naroff677ab3a2008-10-27 17:20:55 +00004724 parenCount++;
4725 // advance the location to startArgList.
4726 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4727 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump11289f42009-09-09 15:08:12 +00004728
Steve Naroff677ab3a2008-10-27 17:20:55 +00004729 const char *argPtr = startArgList;
Mike Stump11289f42009-09-09 15:08:12 +00004730
Steve Naroff677ab3a2008-10-27 17:20:55 +00004731 while (*argPtr++ && parenCount) {
4732 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004733 case '^':
4734 // Replace the '^' with '*'.
4735 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004736 ReplaceText(DeclLoc, 1, "*");
Mike Stump281d6d72010-01-20 02:03:14 +00004737 break;
4738 case '(':
4739 parenCount++;
4740 break;
4741 case ')':
4742 parenCount--;
4743 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004744 }
4745 }
4746 return;
4747}
4748
4749bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004750 const FunctionProtoType *FTP;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004751 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004752 if (PT) {
John McCall9dd450b2009-09-21 23:43:11 +00004753 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004754 } else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004755 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004756 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall9dd450b2009-09-21 23:43:11 +00004757 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004758 }
4759 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004760 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004761 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +00004762 if (isTopLevelBlockPointerType(*I))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004763 return true;
4764 }
4765 return false;
4766}
4767
Ted Kremenek5a201952009-02-07 01:47:29 +00004768void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4769 const char *&RParen) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004770 const char *argPtr = strchr(Name, '(');
4771 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004772
Steve Naroff677ab3a2008-10-27 17:20:55 +00004773 LParen = argPtr; // output the start.
4774 argPtr++; // skip past the left paren.
4775 unsigned parenCount = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004776
Steve Naroff677ab3a2008-10-27 17:20:55 +00004777 while (*argPtr && parenCount) {
4778 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004779 case '(': parenCount++; break;
4780 case ')': parenCount--; break;
4781 default: break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004782 }
4783 if (parenCount) argPtr++;
4784 }
4785 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4786 RParen = argPtr; // output the end
4787}
4788
4789void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4790 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4791 RewriteBlockPointerFunctionArgs(FD);
4792 return;
Mike Stump11289f42009-09-09 15:08:12 +00004793 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004794 // Handle Variables and Typedefs.
4795 SourceLocation DeclLoc = ND->getLocation();
4796 QualType DeclT;
4797 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4798 DeclT = VD->getType();
4799 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4800 DeclT = TDD->getUnderlyingType();
4801 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4802 DeclT = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004803 else
Steve Naroff677ab3a2008-10-27 17:20:55 +00004804 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump11289f42009-09-09 15:08:12 +00004805
Steve Naroff677ab3a2008-10-27 17:20:55 +00004806 const char *startBuf = SM->getCharacterData(DeclLoc);
4807 const char *endBuf = startBuf;
4808 // scan backward (from the decl location) for the end of the previous decl.
4809 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4810 startBuf--;
Mike Stump11289f42009-09-09 15:08:12 +00004811
Steve Naroff677ab3a2008-10-27 17:20:55 +00004812 // *startBuf != '^' if we are dealing with a pointer to function that
4813 // may take block argument types (which will be handled below).
4814 if (*startBuf == '^') {
4815 // Replace the '^' with '*', computing a negative offset.
4816 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004817 ReplaceText(DeclLoc, 1, "*");
Steve Naroff677ab3a2008-10-27 17:20:55 +00004818 }
4819 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4820 // Replace the '^' with '*' for arguments.
4821 DeclLoc = ND->getLocation();
4822 startBuf = SM->getCharacterData(DeclLoc);
4823 const char *argListBegin, *argListEnd;
4824 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4825 while (argListBegin < argListEnd) {
4826 if (*argListBegin == '^') {
4827 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004828 ReplaceText(CaretLoc, 1, "*");
Steve Naroff677ab3a2008-10-27 17:20:55 +00004829 }
4830 argListBegin++;
4831 }
4832 }
4833 return;
4834}
4835
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004836
4837/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4838/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4839/// struct Block_byref_id_object *src) {
4840/// _Block_object_assign (&_dest->object, _src->object,
4841/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4842/// [|BLOCK_FIELD_IS_WEAK]) // object
4843/// _Block_object_assign(&_dest->object, _src->object,
4844/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4845/// [|BLOCK_FIELD_IS_WEAK]) // block
4846/// }
4847/// And:
4848/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4849/// _Block_object_dispose(_src->object,
4850/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4851/// [|BLOCK_FIELD_IS_WEAK]) // object
4852/// _Block_object_dispose(_src->object,
4853/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4854/// [|BLOCK_FIELD_IS_WEAK]) // block
4855/// }
4856
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004857std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4858 int flag) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004859 std::string S;
Benjamin Kramere056cea2010-01-10 19:57:50 +00004860 if (CopyDestroyCache.count(flag))
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004861 return S;
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004862 CopyDestroyCache.insert(flag);
4863 S = "static void __Block_byref_id_object_copy_";
4864 S += utostr(flag);
4865 S += "(void *dst, void *src) {\n";
4866
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004867 // offset into the object pointer is computed as:
4868 // void * + void* + int + int + void* + void *
4869 unsigned IntSize =
4870 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4871 unsigned VoidPtrSize =
4872 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4873
4874 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
4875 S += " _Block_object_assign((char*)dst + ";
4876 S += utostr(offset);
4877 S += ", *(void * *) ((char*)src + ";
4878 S += utostr(offset);
4879 S += "), ";
4880 S += utostr(flag);
4881 S += ");\n}\n";
4882
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004883 S += "static void __Block_byref_id_object_dispose_";
4884 S += utostr(flag);
4885 S += "(void *src) {\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004886 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4887 S += utostr(offset);
4888 S += "), ";
4889 S += utostr(flag);
4890 S += ");\n}\n";
4891 return S;
4892}
4893
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004894/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4895/// the declaration into:
4896/// struct __Block_byref_ND {
4897/// void *__isa; // NULL for everything except __weak pointers
4898/// struct __Block_byref_ND *__forwarding;
4899/// int32_t __flags;
4900/// int32_t __size;
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004901/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4902/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004903/// typex ND;
4904/// };
4905///
4906/// It then replaces declaration of ND variable with:
4907/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4908/// __size=sizeof(struct __Block_byref_ND),
4909/// ND=initializer-if-any};
4910///
4911///
4912void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004913 // Insert declaration for the function in which block literal is
4914 // used.
4915 if (CurFunctionDeclToDeclareForBlock)
4916 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004917 int flag = 0;
4918 int isa = 0;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004919 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahanian6005bd82010-02-26 22:49:11 +00004920 if (DeclLoc.isInvalid())
4921 // If type location is missing, it is because of missing type (a warning).
4922 // Use variable's location which is good for this case.
4923 DeclLoc = ND->getLocation();
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004924 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian92368a12009-12-30 20:38:08 +00004925 SourceLocation X = ND->getLocEnd();
4926 X = SM->getInstantiationLoc(X);
4927 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004928 std::string Name(ND->getNameAsString());
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004929 std::string ByrefType;
4930 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004931 ByrefType += " {\n";
4932 ByrefType += " void *__isa;\n";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004933 RewriteByRefString(ByrefType, Name, ND);
4934 ByrefType += " *__forwarding;\n";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004935 ByrefType += " int __flags;\n";
4936 ByrefType += " int __size;\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004937 // Add void *__Block_byref_id_object_copy;
4938 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004939 QualType Ty = ND->getType();
4940 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4941 if (HasCopyAndDispose) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004942 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4943 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004944 }
4945
4946 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004947 ByrefType += " " + Name + ";\n";
4948 ByrefType += "};\n";
4949 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004950 SourceLocation FunLocStart;
4951 if (CurFunctionDef)
4952 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4953 else {
4954 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4955 FunLocStart = CurMethodDef->getLocStart();
4956 }
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004957 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004958 if (Ty.isObjCGCWeak()) {
4959 flag |= BLOCK_FIELD_IS_WEAK;
4960 isa = 1;
4961 }
4962
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004963 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004964 flag = BLOCK_BYREF_CALLER;
4965 QualType Ty = ND->getType();
4966 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4967 if (Ty->isBlockPointerType())
4968 flag |= BLOCK_FIELD_IS_BLOCK;
4969 else
4970 flag |= BLOCK_FIELD_IS_OBJECT;
4971 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004972 if (!HF.empty())
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004973 InsertText(FunLocStart, HF);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004974 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004975
4976 // struct __Block_byref_ND ND =
4977 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4978 // initializer-if-any};
4979 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanianf7945432010-01-05 18:15:57 +00004980 unsigned flags = 0;
4981 if (HasCopyAndDispose)
4982 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004983 Name = ND->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004984 ByrefType.clear();
4985 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004986 std::string ForwardingCastType("(");
4987 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004988 if (!hasInit) {
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004989 ByrefType += " " + Name + " = {(void*)";
4990 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004991 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004992 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004993 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004994 ByrefType += "sizeof(";
4995 RewriteByRefString(ByrefType, Name, ND);
4996 ByrefType += ")";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004997 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004998 ByrefType += ", __Block_byref_id_object_copy_";
4999 ByrefType += utostr(flag);
5000 ByrefType += ", __Block_byref_id_object_dispose_";
5001 ByrefType += utostr(flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005002 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005003 ByrefType += "};\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005004 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(), ByrefType);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005005 }
5006 else {
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00005007 SourceLocation startLoc;
5008 Expr *E = ND->getInit();
5009 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5010 startLoc = ECE->getLParenLoc();
5011 else
5012 startLoc = E->getLocStart();
Fariborz Jahanianb8646ed2010-01-05 23:06:29 +00005013 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00005014 endBuf = SM->getCharacterData(startLoc);
5015
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005016 ByrefType += " " + Name;
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00005017 ByrefType += " = {(void*)";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00005018 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005019 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005020 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005021 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005022 ByrefType += "sizeof(";
5023 RewriteByRefString(ByrefType, Name, ND);
5024 ByrefType += "), ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005025 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005026 ByrefType += "__Block_byref_id_object_copy_";
5027 ByrefType += utostr(flag);
5028 ByrefType += ", __Block_byref_id_object_dispose_";
5029 ByrefType += utostr(flag);
5030 ByrefType += ", ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005031 }
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005032 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroff13468372009-12-23 17:24:33 +00005033
5034 // Complete the newly synthesized compound expression by inserting a right
5035 // curly brace before the end of the declaration.
5036 // FIXME: This approach avoids rewriting the initializer expression. It
5037 // also assumes there is only one declarator. For example, the following
5038 // isn't currently supported by this routine (in general):
5039 //
5040 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
5041 //
5042 const char *startBuf = SM->getCharacterData(startLoc);
5043 const char *semiBuf = strchr(startBuf, ';');
5044 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
5045 SourceLocation semiLoc =
5046 startLoc.getFileLocWithOffset(semiBuf-startBuf);
5047
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005048 InsertText(semiLoc, "}");
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005049 }
Fariborz Jahanian81203462009-12-22 00:48:54 +00005050 return;
5051}
5052
Mike Stump11289f42009-09-09 15:08:12 +00005053void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00005054 // Add initializers for any closure decl refs.
5055 GetBlockDeclRefExprs(Exp->getBody());
5056 if (BlockDeclRefs.size()) {
5057 // Unique all "by copy" declarations.
5058 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005059 if (!BlockDeclRefs[i]->isByRef()) {
5060 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5061 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5062 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5063 }
5064 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00005065 // Unique all "by ref" declarations.
5066 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5067 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005068 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5069 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5070 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5071 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00005072 }
5073 // Find any imported blocks...they will need special attention.
5074 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00005075 if (BlockDeclRefs[i]->isByRef() ||
5076 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian9bbc1482010-02-26 21:46:27 +00005077 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff677ab3a2008-10-27 17:20:55 +00005078 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff677ab3a2008-10-27 17:20:55 +00005079 }
5080}
5081
Steve Narofff4b992a2008-10-28 20:29:00 +00005082FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
5083 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005084 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump11289f42009-09-09 15:08:12 +00005085 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Douglas Gregorc4df4072010-04-19 22:54:31 +00005086 ID, FType, 0, FunctionDecl::Extern,
5087 FunctionDecl::None, false, false);
Steve Narofff4b992a2008-10-28 20:29:00 +00005088}
5089
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005090Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
5091 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005092 Blocks.push_back(Exp);
5093
5094 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005095
5096 // Add inner imported variables now used in current block.
5097 int countOfInnerDecls = 0;
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00005098 if (!InnerBlockDeclRefs.empty()) {
5099 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5100 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
5101 ValueDecl *VD = Exp->getDecl();
5102 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005103 // We need to save the copied-in variables in nested
5104 // blocks because it is needed at the end for some of the API generations.
5105 // See SynthesizeBlockLiterals routine.
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00005106 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5107 BlockDeclRefs.push_back(Exp);
5108 BlockByCopyDeclsPtrSet.insert(VD);
5109 BlockByCopyDecls.push_back(VD);
5110 }
5111 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
5112 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5113 BlockDeclRefs.push_back(Exp);
5114 BlockByRefDeclsPtrSet.insert(VD);
5115 BlockByRefDecls.push_back(VD);
5116 }
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005117 }
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00005118 // Find any imported blocks...they will need special attention.
5119 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5120 if (InnerBlockDeclRefs[i]->isByRef() ||
5121 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5122 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5123 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005124 }
5125 InnerDeclRefsCount.push_back(countOfInnerDecls);
5126
Steve Narofff4b992a2008-10-28 20:29:00 +00005127 std::string FuncName;
Mike Stump11289f42009-09-09 15:08:12 +00005128
Steve Narofff4b992a2008-10-28 20:29:00 +00005129 if (CurFunctionDef)
Chris Lattnere4b95692008-11-24 03:33:13 +00005130 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00005131 else if (CurMethodDef)
5132 BuildUniqueMethodName(FuncName, CurMethodDef);
5133 else if (GlobalVarDecl)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005134 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump11289f42009-09-09 15:08:12 +00005135
Steve Narofff4b992a2008-10-28 20:29:00 +00005136 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump11289f42009-09-09 15:08:12 +00005137
Steve Narofff4b992a2008-10-28 20:29:00 +00005138 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
5139 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump11289f42009-09-09 15:08:12 +00005140
Steve Narofff4b992a2008-10-28 20:29:00 +00005141 // Get a pointer to the function type so we can cast appropriately.
5142 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
5143
5144 FunctionDecl *FD;
5145 Expr *NewRep;
Mike Stump11289f42009-09-09 15:08:12 +00005146
Steve Narofff4b992a2008-10-28 20:29:00 +00005147 // Simulate a contructor call...
5148 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00005149 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00005150
Steve Narofff4b992a2008-10-28 20:29:00 +00005151 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00005152
Steve Naroffe2514232008-10-29 21:23:59 +00005153 // Initialize the block function.
Steve Narofff4b992a2008-10-28 20:29:00 +00005154 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00005155 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
5156 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00005157 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5158 CastExpr::CK_Unknown, Arg);
Mike Stump11289f42009-09-09 15:08:12 +00005159 InitExprs.push_back(castExpr);
5160
Steve Naroff30484702009-12-06 21:14:13 +00005161 // Initialize the block descriptor.
5162 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump11289f42009-09-09 15:08:12 +00005163
Steve Naroff30484702009-12-06 21:14:13 +00005164 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
5165 &Context->Idents.get(DescData.c_str()),
5166 Context->VoidPtrTy, 0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00005167 VarDecl::Static, VarDecl::None);
Steve Naroff30484702009-12-06 21:14:13 +00005168 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
5169 new (Context) DeclRefExpr(NewVD,
5170 Context->VoidPtrTy, SourceLocation()),
5171 UnaryOperator::AddrOf,
5172 Context->getPointerType(Context->VoidPtrTy),
5173 SourceLocation());
5174 InitExprs.push_back(DescRefExpr);
5175
Steve Narofff4b992a2008-10-28 20:29:00 +00005176 // Add initializers for any closure decl refs.
5177 if (BlockDeclRefs.size()) {
Steve Naroffe2514232008-10-29 21:23:59 +00005178 Expr *Exp;
Steve Narofff4b992a2008-10-28 20:29:00 +00005179 // Output all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005180 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00005181 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005182 if (isObjCType((*I)->getType())) {
Steve Naroffe2514232008-10-29 21:23:59 +00005183 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner86d7d912008-11-24 03:54:41 +00005184 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00005185 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroffa5c0db82008-12-11 21:05:33 +00005186 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner86d7d912008-11-24 03:54:41 +00005187 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00005188 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
John McCall97513962010-01-15 18:39:57 +00005189 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5190 CastExpr::CK_Unknown, Arg);
Steve Narofff4b992a2008-10-28 20:29:00 +00005191 } else {
Chris Lattner86d7d912008-11-24 03:54:41 +00005192 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00005193 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005194 if (HasLocalVariableExternalStorage(*I)) {
5195 QualType QT = (*I)->getType();
5196 QT = Context->getPointerType(QT);
5197 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf, QT,
5198 SourceLocation());
5199 }
5200
Steve Narofff4b992a2008-10-28 20:29:00 +00005201 }
Mike Stump11289f42009-09-09 15:08:12 +00005202 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00005203 }
5204 // Output all "by ref" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005205 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00005206 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005207 ValueDecl *ND = (*I);
5208 std::string Name(ND->getNameAsString());
5209 std::string RecName;
5210 RewriteByRefString(RecName, Name, ND);
5211 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5212 + sizeof("struct"));
5213 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
5214 SourceLocation(), II);
5215 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5216 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5217
Chris Lattner86d7d912008-11-24 03:54:41 +00005218 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00005219 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
5220 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00005221 Context->getPointerType(Exp->getType()),
Steve Naroffe2514232008-10-29 21:23:59 +00005222 SourceLocation());
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005223 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CastExpr::CK_Unknown, Exp);
Mike Stump11289f42009-09-09 15:08:12 +00005224 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00005225 }
5226 }
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00005227 if (ImportedBlockDecls.size()) {
5228 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5229 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff30484702009-12-06 21:14:13 +00005230 unsigned IntSize =
5231 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00005232 Expr *FlagExp = new (Context) IntegerLiteral(llvm::APInt(IntSize, flag),
5233 Context->IntTy, SourceLocation());
5234 InitExprs.push_back(FlagExp);
Steve Naroff30484702009-12-06 21:14:13 +00005235 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00005236 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
5237 FType, SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00005238 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00005239 Context->getPointerType(NewRep->getType()),
Steve Narofff4b992a2008-10-28 20:29:00 +00005240 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00005241 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CastExpr::CK_Unknown,
5242 NewRep);
Steve Narofff4b992a2008-10-28 20:29:00 +00005243 BlockDeclRefs.clear();
5244 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005245 BlockByRefDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00005246 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005247 BlockByCopyDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00005248 ImportedBlockDecls.clear();
5249 return NewRep;
5250}
5251
5252//===----------------------------------------------------------------------===//
5253// Function Body / Expression rewriting
5254//===----------------------------------------------------------------------===//
5255
Steve Naroff4588d0f2008-12-04 16:24:46 +00005256// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
5257// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
5258// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
5259// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
5260// Since the rewriter isn't capable of rewriting rewritten code, it's important
5261// we get this right.
5262void RewriteObjC::CollectPropertySetters(Stmt *S) {
5263 // Perform a bottom up traversal of all children.
5264 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5265 CI != E; ++CI)
5266 if (*CI)
5267 CollectPropertySetters(*CI);
5268
5269 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
5270 if (BinOp->isAssignmentOp()) {
5271 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
5272 PropSetters[PRE] = BinOp;
5273 }
5274 }
5275}
5276
Steve Narofff4b992a2008-10-28 20:29:00 +00005277Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump11289f42009-09-09 15:08:12 +00005278 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00005279 isa<DoStmt>(S) || isa<ForStmt>(S))
5280 Stmts.push_back(S);
5281 else if (isa<ObjCForCollectionStmt>(S)) {
5282 Stmts.push_back(S);
Chris Lattnerb71980f2010-01-09 21:45:57 +00005283 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofff4b992a2008-10-28 20:29:00 +00005284 }
Mike Stump11289f42009-09-09 15:08:12 +00005285
Steve Narofff4b992a2008-10-28 20:29:00 +00005286 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00005287
Steve Narofff4b992a2008-10-28 20:29:00 +00005288 // Perform a bottom up rewrite of all children.
5289 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5290 CI != E; ++CI)
5291 if (*CI) {
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00005292 Stmt *newStmt;
5293 Stmt *S = (*CI);
5294 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5295 Expr *OldBase = IvarRefExpr->getBase();
5296 bool replaced = false;
5297 newStmt = RewriteObjCNestedIvarRefExpr(S, replaced);
5298 if (replaced) {
5299 if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
5300 ReplaceStmt(OldBase, IRE->getBase());
5301 else
5302 ReplaceStmt(S, newStmt);
5303 }
5304 }
5305 else
5306 newStmt = RewriteFunctionBodyOrGlobalInitializer(S);
Mike Stump11289f42009-09-09 15:08:12 +00005307 if (newStmt)
Steve Narofff4b992a2008-10-28 20:29:00 +00005308 *CI = newStmt;
5309 }
Mike Stump11289f42009-09-09 15:08:12 +00005310
Steve Narofff4b992a2008-10-28 20:29:00 +00005311 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005312 llvm::SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00005313 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5314 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005315 ImportedLocalExternalDecls.clear();
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005316 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00005317 InnerBlockDeclRefs, InnerContexts);
Steve Narofff4b992a2008-10-28 20:29:00 +00005318 // Rewrite the block body in place.
5319 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005320 ImportedLocalExternalDecls.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00005321 // Now we snarf the rewritten text and stash it away for later use.
Ted Kremenekdb2ef372010-01-07 18:00:35 +00005322 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroffd8907b72008-10-29 18:15:37 +00005323 RewrittenBlockExprs[BE] = Str;
Mike Stump11289f42009-09-09 15:08:12 +00005324
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005325 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5326
Steve Narofff4b992a2008-10-28 20:29:00 +00005327 //blockTranscribed->dump();
Steve Naroffd8907b72008-10-29 18:15:37 +00005328 ReplaceStmt(S, blockTranscribed);
Steve Narofff4b992a2008-10-28 20:29:00 +00005329 return blockTranscribed;
5330 }
5331 // Handle specific things.
5332 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5333 return RewriteAtEncode(AtEncode);
Mike Stump11289f42009-09-09 15:08:12 +00005334
Steve Naroff4588d0f2008-12-04 16:24:46 +00005335 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
5336 BinaryOperator *BinOp = PropSetters[PropRefExpr];
5337 if (BinOp) {
5338 // Because the rewriter doesn't allow us to rewrite rewritten code,
5339 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroff08628db2008-12-09 12:56:34 +00005340 DisableReplaceStmt = true;
5341 // Save the source range. Even if we disable the replacement, the
5342 // rewritten node will have been inserted into the tree. If the synthesized
5343 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump11289f42009-09-09 15:08:12 +00005344 // self.errorHandler = handler ? handler :
Steve Naroff08628db2008-12-09 12:56:34 +00005345 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
5346 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroff4588d0f2008-12-04 16:24:46 +00005347 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroff08628db2008-12-09 12:56:34 +00005348 DisableReplaceStmt = false;
Steve Naroff22216db2008-12-04 23:50:32 +00005349 //
5350 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
5351 // we changed the RHS of BinOp, the rewriter would fail (since it needs
5352 // to see the original expression). Consider this example:
5353 //
5354 // Foo *obj1, *obj2;
5355 //
5356 // obj1.i = [obj2 rrrr];
5357 //
5358 // 'BinOp' for the previous expression looks like:
5359 //
5360 // (BinaryOperator 0x231ccf0 'int' '='
5361 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
5362 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
5363 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
5364 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
5365 //
5366 // 'newStmt' represents the rewritten message expression. For example:
5367 //
5368 // (CallExpr 0x231d300 'id':'struct objc_object *'
5369 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
5370 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
5371 // (CStyleCastExpr 0x231d220 'void *'
5372 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
5373 //
5374 // Note that 'newStmt' is passed to RewritePropertySetter so that it
5375 // can be used as the setter argument. ReplaceStmt() will still 'see'
5376 // the original RHS (since we haven't altered BinOp).
5377 //
Mike Stump11289f42009-09-09 15:08:12 +00005378 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff22216db2008-12-04 23:50:32 +00005379 // node. As a result, we now leak the original AST nodes.
5380 //
Steve Naroff08628db2008-12-09 12:56:34 +00005381 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroff4588d0f2008-12-04 16:24:46 +00005382 } else {
5383 return RewritePropertyGetter(PropRefExpr);
Steve Narofff326f402008-12-03 00:56:33 +00005384 }
5385 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005386 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5387 return RewriteAtSelector(AtSelector);
Mike Stump11289f42009-09-09 15:08:12 +00005388
Steve Narofff4b992a2008-10-28 20:29:00 +00005389 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5390 return RewriteObjCStringLiteral(AtString);
Mike Stump11289f42009-09-09 15:08:12 +00005391
Steve Narofff4b992a2008-10-28 20:29:00 +00005392 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00005393#if 0
Steve Narofff4b992a2008-10-28 20:29:00 +00005394 // Before we rewrite it, put the original message expression in a comment.
5395 SourceLocation startLoc = MessExpr->getLocStart();
5396 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00005397
Steve Narofff4b992a2008-10-28 20:29:00 +00005398 const char *startBuf = SM->getCharacterData(startLoc);
5399 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump11289f42009-09-09 15:08:12 +00005400
Steve Narofff4b992a2008-10-28 20:29:00 +00005401 std::string messString;
5402 messString += "// ";
5403 messString.append(startBuf, endBuf-startBuf+1);
5404 messString += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00005405
5406 // FIXME: Missing definition of
Steve Narofff4b992a2008-10-28 20:29:00 +00005407 // InsertText(clang::SourceLocation, char const*, unsigned int).
5408 // InsertText(startLoc, messString.c_str(), messString.size());
5409 // Tried this, but it didn't work either...
5410 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff4588d0f2008-12-04 16:24:46 +00005411#endif
Steve Narofff4b992a2008-10-28 20:29:00 +00005412 return RewriteMessageExpr(MessExpr);
5413 }
Mike Stump11289f42009-09-09 15:08:12 +00005414
Steve Narofff4b992a2008-10-28 20:29:00 +00005415 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5416 return RewriteObjCTryStmt(StmtTry);
5417
5418 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5419 return RewriteObjCSynchronizedStmt(StmtTry);
5420
5421 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5422 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump11289f42009-09-09 15:08:12 +00005423
Steve Narofff4b992a2008-10-28 20:29:00 +00005424 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5425 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump11289f42009-09-09 15:08:12 +00005426
5427 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofff4b992a2008-10-28 20:29:00 +00005428 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump11289f42009-09-09 15:08:12 +00005429 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofff4b992a2008-10-28 20:29:00 +00005430 OrigStmtRange.getEnd());
5431 if (BreakStmt *StmtBreakStmt =
5432 dyn_cast<BreakStmt>(S))
5433 return RewriteBreakStmt(StmtBreakStmt);
5434 if (ContinueStmt *StmtContinueStmt =
5435 dyn_cast<ContinueStmt>(S))
5436 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump11289f42009-09-09 15:08:12 +00005437
5438 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofff4b992a2008-10-28 20:29:00 +00005439 // and cast exprs.
5440 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5441 // FIXME: What we're doing here is modifying the type-specifier that
5442 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump11289f42009-09-09 15:08:12 +00005443 // a separate type-specifier that we can rewrite.
Steve Naroffe70a52a2009-12-05 15:55:59 +00005444 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5445 // the context of an ObjCForCollectionStmt. For example:
5446 // NSArray *someArray;
5447 // for (id <FooProtocol> index in someArray) ;
5448 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5449 // and it depends on the original text locations/positions.
Benjamin Krameracc5fa12009-12-05 22:16:51 +00005450 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroffe70a52a2009-12-05 15:55:59 +00005451 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump11289f42009-09-09 15:08:12 +00005452
Steve Narofff4b992a2008-10-28 20:29:00 +00005453 // Blocks rewrite rules.
5454 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5455 DI != DE; ++DI) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +00005456 Decl *SD = *DI;
Steve Narofff4b992a2008-10-28 20:29:00 +00005457 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005458 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005459 RewriteBlockPointerDecl(ND);
Mike Stump11289f42009-09-09 15:08:12 +00005460 else if (ND->getType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005461 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00005462 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005463 if (VD->hasAttr<BlocksAttr>()) {
5464 static unsigned uniqueByrefDeclCount = 0;
5465 assert(!BlockByRefDeclNo.count(ND) &&
5466 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5467 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005468 RewriteByRefVar(VD);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005469 }
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00005470 else
5471 RewriteTypeOfDecl(VD);
5472 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005473 }
5474 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005475 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005476 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005477 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005478 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5479 }
5480 }
5481 }
Mike Stump11289f42009-09-09 15:08:12 +00005482
Steve Narofff4b992a2008-10-28 20:29:00 +00005483 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5484 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump11289f42009-09-09 15:08:12 +00005485
5486 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00005487 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5488 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump11289f42009-09-09 15:08:12 +00005489 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5490 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005491 && "Statement stack mismatch");
5492 Stmts.pop_back();
5493 }
5494 // Handle blocks rewriting.
5495 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5496 if (BDRE->isByRef())
Steve Naroffd9803712009-04-29 16:37:50 +00005497 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofff4b992a2008-10-28 20:29:00 +00005498 }
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005499 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5500 ValueDecl *VD = DRE->getDecl();
5501 if (VD->hasAttr<BlocksAttr>())
5502 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005503 if (HasLocalVariableExternalStorage(VD))
5504 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005505 }
5506
Steve Narofff4b992a2008-10-28 20:29:00 +00005507 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff350b6652008-10-30 10:07:53 +00005508 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00005509 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00005510 ReplaceStmt(S, BlockCall);
5511 return BlockCall;
5512 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005513 }
Steve Naroffc989a7b2008-11-03 23:29:32 +00005514 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005515 RewriteCastExpr(CE);
5516 }
5517#if 0
5518 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek5a201952009-02-07 01:47:29 +00005519 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00005520 // Get the new text.
5521 std::string SStr;
5522 llvm::raw_string_ostream Buf(SStr);
Eli Friedman0905f142009-05-30 05:19:26 +00005523 Replacement->printPretty(Buf, *Context);
Steve Narofff4b992a2008-10-28 20:29:00 +00005524 const std::string &Str = Buf.str();
5525
5526 printf("CAST = %s\n", &Str[0]);
5527 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5528 delete S;
5529 return Replacement;
5530 }
5531#endif
5532 // Return this stmt unmodified.
5533 return S;
5534}
5535
Steve Naroffe70a52a2009-12-05 15:55:59 +00005536void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5537 for (RecordDecl::field_iterator i = RD->field_begin(),
5538 e = RD->field_end(); i != e; ++i) {
5539 FieldDecl *FD = *i;
5540 if (isTopLevelBlockPointerType(FD->getType()))
5541 RewriteBlockPointerDecl(FD);
5542 if (FD->getType()->isObjCQualifiedIdType() ||
5543 FD->getType()->isObjCQualifiedInterfaceType())
5544 RewriteObjCQualifiedInterfaceTypes(FD);
5545 }
5546}
5547
Steve Narofff4b992a2008-10-28 20:29:00 +00005548/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5549/// main file of the input.
5550void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5551 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffb1368882008-12-17 00:20:22 +00005552 if (FD->isOverloadedOperator())
5553 return;
Mike Stump11289f42009-09-09 15:08:12 +00005554
Steve Narofff4b992a2008-10-28 20:29:00 +00005555 // Since function prototypes don't have ParmDecl's, we check the function
5556 // prototype. This enables us to rewrite function declarations and
5557 // definitions using the same code.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005558 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005559
Sebastian Redla7b98a72009-04-26 20:35:05 +00005560 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00005561 if (CompoundStmt *Body = FD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005562 CurFunctionDef = FD;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005563 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005564 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005565 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005566 Body =
5567 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5568 FD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005569 CurrentBody = 0;
5570 if (PropParentMap) {
5571 delete PropParentMap;
5572 PropParentMap = 0;
5573 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005574 // This synthesizes and inserts the block "impl" struct, invoke function,
5575 // and any copy/dispose helper functions.
5576 InsertBlockLiteralsWithinFunction(FD);
5577 CurFunctionDef = 0;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005578 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005579 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005580 return;
5581 }
5582 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00005583 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005584 CurMethodDef = MD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005585 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005586 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005587 Body =
5588 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5589 MD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005590 CurrentBody = 0;
5591 if (PropParentMap) {
5592 delete PropParentMap;
5593 PropParentMap = 0;
5594 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005595 InsertBlockLiteralsWithinMethod(MD);
5596 CurMethodDef = 0;
5597 }
5598 }
5599 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5600 ClassImplementation.push_back(CI);
5601 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5602 CategoryImplementation.push_back(CI);
5603 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5604 RewriteForwardClassDecl(CD);
5605 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5606 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroffa5c0db82008-12-11 21:05:33 +00005607 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005608 RewriteBlockPointerDecl(VD);
Steve Naroffd8907b72008-10-29 18:15:37 +00005609 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005610 CheckFunctionPointerDecl(VD->getType(), VD);
5611 if (VD->getInit()) {
Steve Naroffc989a7b2008-11-03 23:29:32 +00005612 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005613 RewriteCastExpr(CE);
5614 }
5615 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00005616 } else if (VD->getType()->isRecordType()) {
5617 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5618 if (RD->isDefinition())
5619 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005620 }
Steve Naroffd8907b72008-10-29 18:15:37 +00005621 if (VD->getInit()) {
5622 GlobalVarDecl = VD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005623 CollectPropertySetters(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005624 CurrentBody = VD->getInit();
Steve Naroffd8907b72008-10-29 18:15:37 +00005625 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005626 CurrentBody = 0;
5627 if (PropParentMap) {
5628 delete PropParentMap;
5629 PropParentMap = 0;
5630 }
Mike Stump11289f42009-09-09 15:08:12 +00005631 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner86d7d912008-11-24 03:54:41 +00005632 VD->getNameAsCString());
Steve Naroffd8907b72008-10-29 18:15:37 +00005633 GlobalVarDecl = 0;
5634
5635 // This is needed for blocks.
Steve Naroffc989a7b2008-11-03 23:29:32 +00005636 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroffd8907b72008-10-29 18:15:37 +00005637 RewriteCastExpr(CE);
5638 }
5639 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005640 return;
5641 }
5642 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005643 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005644 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005645 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005646 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5647 return;
5648 }
5649 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroffe70a52a2009-12-05 15:55:59 +00005650 if (RD->isDefinition())
5651 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005652 return;
5653 }
5654 // Nothing yet.
5655}
5656
Chris Lattnercf169832009-03-28 04:11:33 +00005657void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005658 if (Diags.hasErrorOccurred())
5659 return;
Mike Stump11289f42009-09-09 15:08:12 +00005660
Steve Narofff4b992a2008-10-28 20:29:00 +00005661 RewriteInclude();
Mike Stump11289f42009-09-09 15:08:12 +00005662
Steve Naroffd9803712009-04-29 16:37:50 +00005663 // Here's a great place to add any extra declarations that may be needed.
5664 // Write out meta data for each @protocol(<expr>).
Mike Stump11289f42009-09-09 15:08:12 +00005665 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00005666 E = ProtocolExprDecls.end(); I != E; ++I)
5667 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5668
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005669 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005670 if (ClassImplementation.size() || CategoryImplementation.size())
5671 RewriteImplementations();
Steve Naroffd9803712009-04-29 16:37:50 +00005672
Steve Narofff4b992a2008-10-28 20:29:00 +00005673 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5674 // we are done.
Mike Stump11289f42009-09-09 15:08:12 +00005675 if (const RewriteBuffer *RewriteBuf =
Steve Narofff4b992a2008-10-28 20:29:00 +00005676 Rewrite.getRewriteBufferFor(MainFileID)) {
5677 //printf("Changed:\n");
5678 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5679 } else {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005680 llvm::errs() << "No changes\n";
Steve Narofff4b992a2008-10-28 20:29:00 +00005681 }
Steve Narofff8cfd162008-11-13 20:07:04 +00005682
Steve Naroffd9803712009-04-29 16:37:50 +00005683 if (ClassImplementation.size() || CategoryImplementation.size() ||
5684 ProtocolExprDecls.size()) {
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005685 // Rewrite Objective-c meta data*
5686 std::string ResultStr;
5687 SynthesizeMetaDataIntoBuffer(ResultStr);
5688 // Emit metadata.
5689 *OutFile << ResultStr;
5690 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005691 OutFile->flush();
5692}