blob: 578a063614a1b651ba4f8f5c61012d9e29243388 [file] [log] [blame]
Steve Naroffb29b4272008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattner77cd2a02007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner77cd2a02007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Daniel Dunbar9b414d32010-06-15 17:48:49 +000014#include "clang/Rewrite/ASTConsumers.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Steve Naroff8599e7a2008-12-08 16:43:47 +000018#include "clang/AST/ParentMap.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner07506182007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner26de4652007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +000023#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000025#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000026#include "llvm/ADT/SmallPtrSet.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000027#include "llvm/ADT/OwningPtr.h"
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +000028#include "llvm/ADT/DenseSet.h"
Fariborz Jahanian72952fc2010-03-01 23:36:21 +000029
Chris Lattner77cd2a02007-10-11 00:43:27 +000030using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000031using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000032
Chris Lattner77cd2a02007-10-11 00:43:27 +000033namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000034 class RewriteObjC : public ASTConsumer {
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000035 enum {
36 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
37 block, ... */
38 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
39 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
40 __block variable */
41 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
42 helpers */
43 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
44 support routines */
45 BLOCK_BYREF_CURRENT_MAX = 256
46 };
47
48 enum {
49 BLOCK_NEEDS_FREE = (1 << 24),
50 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
51 BLOCK_HAS_CXX_OBJ = (1 << 26),
52 BLOCK_IS_GC = (1 << 27),
53 BLOCK_IS_GLOBAL = (1 << 28),
54 BLOCK_HAS_DESCRIPTOR = (1 << 29)
55 };
56
Chris Lattner2c64b7b2007-10-16 21:07:07 +000057 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000058 Diagnostic &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000059 const LangOptions &LangOpts;
Steve Narofff69cc5d2008-01-30 19:17:43 +000060 unsigned RewriteFailedDiag;
Steve Naroff8c565152008-12-05 17:03:39 +000061 unsigned TryFinallyContainsReturnDiag;
Mike Stump1eb44332009-09-09 15:08:12 +000062
Chris Lattner01c57482007-10-17 22:35:30 +000063 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000064 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000065 TranslationUnitDecl *TUDecl;
Chris Lattner2b2453a2009-01-17 06:22:33 +000066 FileID MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000067 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000068 SourceLocation LastIncLoc;
Mike Stump1eb44332009-09-09 15:08:12 +000069
Ted Kremeneka526c5c2008-01-07 19:49:32 +000070 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
71 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
72 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +000073 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000074 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
75 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000076 llvm::SmallVector<Stmt *, 32> Stmts;
77 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroff621edce2009-04-29 16:37:50 +000078 // Remember all the @protocol(<expr>) expressions.
79 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +000080
81 llvm::DenseSet<uint64_t> CopyDestroyCache;
82
Steve Naroffd82a9ab2008-03-15 00:55:56 +000083 unsigned NumObjCStringLiterals;
Mike Stump1eb44332009-09-09 15:08:12 +000084
Steve Naroffebf2b562007-10-23 23:50:29 +000085 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000086 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000087 FunctionDecl *MsgSendStretFunctionDecl;
88 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000089 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000090 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000091 FunctionDecl *GetMetaClassFunctionDecl;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +000092 FunctionDecl *GetSuperClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000093 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000094 FunctionDecl *CFStringFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000095 FunctionDecl *SuperContructorFunctionDecl;
Mike Stump1eb44332009-09-09 15:08:12 +000096
Steve Naroffbeaf2992007-11-03 11:27:19 +000097 // ObjC string constant support.
Steve Naroff248a7532008-04-15 22:42:06 +000098 VarDecl *ConstantStringClassReference;
Steve Naroffbeaf2992007-11-03 11:27:19 +000099 RecordDecl *NSStringRecord;
Mike Stump1eb44332009-09-09 15:08:12 +0000100
Fariborz Jahanianb586cce2008-01-16 00:09:11 +0000101 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000102 int BcLabelCount;
Mike Stump1eb44332009-09-09 15:08:12 +0000103
Steve Naroff874e2322007-11-15 10:28:18 +0000104 // Needed for super.
Steve Naroff54055232008-10-27 17:20:55 +0000105 ObjCMethodDecl *CurMethodDef;
Steve Naroff874e2322007-11-15 10:28:18 +0000106 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000107 RecordDecl *ConstantStringDecl;
Mike Stump1eb44332009-09-09 15:08:12 +0000108
Steve Naroff621edce2009-04-29 16:37:50 +0000109 TypeDecl *ProtocolTypeDecl;
110 QualType getProtocolType();
Mike Stump1eb44332009-09-09 15:08:12 +0000111
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000112 // Needed for header files being rewritten
113 bool IsHeader;
Mike Stump1eb44332009-09-09 15:08:12 +0000114
Steve Naroffa7b402d2008-03-28 22:26:09 +0000115 std::string InFileName;
Eli Friedman66d6f042009-05-18 22:20:00 +0000116 llvm::raw_ostream* OutFile;
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000117
118 bool SilenceRewriteMacroWarning;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000119 bool objc_impl_method;
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000120
Steve Naroffba92b2e2008-03-27 22:29:16 +0000121 std::string Preamble;
Steve Naroff54055232008-10-27 17:20:55 +0000122
123 // Block expressions.
124 llvm::SmallVector<BlockExpr *, 32> Blocks;
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000125 llvm::SmallVector<int, 32> InnerDeclRefsCount;
126 llvm::SmallVector<BlockDeclRefExpr *, 32> InnerDeclRefs;
127
Steve Naroff54055232008-10-27 17:20:55 +0000128 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
Mike Stump1eb44332009-09-09 15:08:12 +0000129
Steve Naroff54055232008-10-27 17:20:55 +0000130 // Block related declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +0000131 llvm::SmallVector<ValueDecl *, 8> BlockByCopyDecls;
132 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
133 llvm::SmallVector<ValueDecl *, 8> BlockByRefDecls;
134 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000135 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff54055232008-10-27 17:20:55 +0000136 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000137 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
138
Steve Naroff54055232008-10-27 17:20:55 +0000139 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
140
Steve Naroffc77a6362008-12-04 16:24:46 +0000141 // This maps a property to it's assignment statement.
142 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
Steve Naroff8599e7a2008-12-08 16:43:47 +0000143 // This maps a property to it's synthesied message expression.
144 // This allows us to rewrite chained getters (e.g. o.a.b.c).
145 llvm::DenseMap<ObjCPropertyRefExpr *, Stmt *> PropGetters;
Mike Stump1eb44332009-09-09 15:08:12 +0000146
Steve Naroff4c3580e2008-12-04 23:50:32 +0000147 // This maps an original source AST to it's rewritten form. This allows
148 // us to avoid rewriting the same node twice (which is very uncommon).
149 // This is needed to support some of the exotic property rewriting.
150 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Naroff15f081d2008-12-03 00:56:33 +0000151
Steve Naroff54055232008-10-27 17:20:55 +0000152 FunctionDecl *CurFunctionDef;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000153 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000154 VarDecl *GlobalVarDecl;
Mike Stump1eb44332009-09-09 15:08:12 +0000155
Steve Naroffb619d952008-12-09 12:56:34 +0000156 bool DisableReplaceStmt;
Mike Stump1eb44332009-09-09 15:08:12 +0000157
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000158 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000159 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000160 virtual void Initialize(ASTContext &context);
161
Chris Lattnerf04da132007-10-24 17:06:59 +0000162 // Top Level Driver code.
Chris Lattner682bf922009-03-29 16:50:03 +0000163 virtual void HandleTopLevelDecl(DeclGroupRef D) {
164 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
165 HandleTopLevelSingleDecl(*I);
166 }
167 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000168 void HandleDeclInMainFile(Decl *D);
Eli Friedman66d6f042009-05-18 22:20:00 +0000169 RewriteObjC(std::string inFile, llvm::raw_ostream *OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000170 Diagnostic &D, const LangOptions &LOpts,
171 bool silenceMacroWarn);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000172
173 ~RewriteObjC() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000174
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000175 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump1eb44332009-09-09 15:08:12 +0000176
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000177 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000178 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump1eb44332009-09-09 15:08:12 +0000179
Steve Naroff4c3580e2008-12-04 23:50:32 +0000180 if (ReplacingStmt)
181 return; // We can't rewrite the same node twice.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000182
Steve Naroffb619d952008-12-09 12:56:34 +0000183 if (DisableReplaceStmt)
184 return; // Used when rewriting the assignment of a property setter.
185
Steve Naroff4c3580e2008-12-04 23:50:32 +0000186 // If replacement succeeded or warning disabled return with no warning.
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000187 if (!Rewrite.ReplaceStmt(Old, New)) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000188 ReplacedNodes[Old] = New;
189 return;
190 }
191 if (SilenceRewriteMacroWarning)
192 return;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000193 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
194 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000195 }
Steve Naroffb619d952008-12-09 12:56:34 +0000196
197 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
198 // Measaure the old text.
199 int Size = Rewrite.getRangeSize(SrcRange);
200 if (Size == -1) {
201 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
202 << Old->getSourceRange();
203 return;
204 }
205 // Get the new text.
206 std::string SStr;
207 llvm::raw_string_ostream S(SStr);
Chris Lattnere4f21422009-06-30 01:26:17 +0000208 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroffb619d952008-12-09 12:56:34 +0000209 const std::string &Str = S.str();
210
211 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000212 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroffb619d952008-12-09 12:56:34 +0000213 ReplacedNodes[Old] = New;
214 return;
215 }
216 if (SilenceRewriteMacroWarning)
217 return;
218 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
219 << Old->getSourceRange();
220 }
221
Benjamin Kramerd999b372010-02-14 14:14:16 +0000222 void InsertText(SourceLocation Loc, llvm::StringRef Str,
Steve Naroffba92b2e2008-03-27 22:29:16 +0000223 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000224 // If insertion succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000225 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000226 SilenceRewriteMacroWarning)
227 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000228
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000229 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
230 }
Mike Stump1eb44332009-09-09 15:08:12 +0000231
Chris Lattneraadaf782008-01-31 19:51:04 +0000232 void ReplaceText(SourceLocation Start, unsigned OrigLength,
Benjamin Kramerd999b372010-02-14 14:14:16 +0000233 llvm::StringRef Str) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000234 // If removal succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000235 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
Chris Lattneraadaf782008-01-31 19:51:04 +0000236 SilenceRewriteMacroWarning)
237 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000238
Chris Lattneraadaf782008-01-31 19:51:04 +0000239 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
240 }
Mike Stump1eb44332009-09-09 15:08:12 +0000241
Chris Lattnerf04da132007-10-24 17:06:59 +0000242 // Syntactic Rewriting.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000243 void RewriteInclude();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000244 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffa0876e82008-12-02 17:36:43 +0000245 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
246 ObjCImplementationDecl *IMD,
247 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000248 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000249 void RewriteImplementationDecl(Decl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000250 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000251 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
252 const FunctionType *&FPRetType);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000253 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
254 ValueDecl *VD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000255 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
256 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
257 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
258 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000259 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff09b266e2007-10-30 23:14:51 +0000260 void RewriteFunctionDecl(FunctionDecl *FD);
Daniel Dunbarfa297fb2010-06-30 19:16:53 +0000261 void RewriteBlockPointerType(std::string& Str, QualType Type);
262 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000263 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000264 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +0000265 void RewriteTypeOfDecl(VarDecl *VD);
Steve Naroff4f95b752008-07-29 18:15:38 +0000266 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000267 bool needToScanForQualifiers(QualType T);
Steve Naroff874e2322007-11-15 10:28:18 +0000268 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000269 QualType getConstantStringStructType();
Fariborz Jahanian1f906222010-05-25 15:56:08 +0000270 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
Steve Naroffbaf58c32008-05-31 14:15:04 +0000271 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump1eb44332009-09-09 15:08:12 +0000272
Chris Lattnerf04da132007-10-24 17:06:59 +0000273 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000274 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroffc77a6362008-12-04 16:24:46 +0000275 void CollectPropertySetters(Stmt *S);
Mike Stump1eb44332009-09-09 15:08:12 +0000276
Steve Naroff8599e7a2008-12-08 16:43:47 +0000277 Stmt *CurrentBody;
278 ParentMap *PropParentMap; // created lazily.
Mike Stump1eb44332009-09-09 15:08:12 +0000279
Chris Lattnere64b7772007-10-24 16:57:36 +0000280 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +0000281 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart,
282 bool &replaced);
283 Stmt *RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced);
Steve Naroffc77a6362008-12-04 16:24:46 +0000284 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Mike Stump1eb44332009-09-09 15:08:12 +0000285 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroffb619d952008-12-09 12:56:34 +0000286 SourceRange SrcRange);
Steve Naroffb42f8412007-11-05 14:50:49 +0000287 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000288 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000289 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000290 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffb85e77a2009-12-05 21:43:12 +0000291 void WarnAboutReturnGotoStmts(Stmt *S);
292 void HasReturnStmts(Stmt *S, bool &hasReturns);
293 void RewriteTryReturnStmts(Stmt *S);
294 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000295 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000296 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000297 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000298 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
299 SourceLocation OrigEnd);
Mike Stump1eb44332009-09-09 15:08:12 +0000300 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +0000301 Expr **args, unsigned nargs,
302 SourceLocation StartLoc=SourceLocation(),
303 SourceLocation EndLoc=SourceLocation());
304 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
305 SourceLocation StartLoc=SourceLocation(),
306 SourceLocation EndLoc=SourceLocation());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000307 Stmt *RewriteBreakStmt(BreakStmt *S);
308 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000309 void SynthCountByEnumWithState(std::string &buf);
Mike Stump1eb44332009-09-09 15:08:12 +0000310
Steve Naroff09b266e2007-10-30 23:14:51 +0000311 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000312 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000313 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000314 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000315 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000316 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000317 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000318 void SynthGetSuperClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000319 void SynthSelGetUidFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000320 void SynthSuperContructorFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000321
Chris Lattnerf04da132007-10-24 17:06:59 +0000322 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000323 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000324 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000325
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000326 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000327 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000328
Douglas Gregor653f1b12009-04-23 01:02:12 +0000329 template<typename MethodIterator>
330 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
331 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000332 bool IsInstanceMethod,
Daniel Dunbar4087f272010-08-17 22:39:59 +0000333 llvm::StringRef prefix,
334 llvm::StringRef ClassName,
Chris Lattner158ecb92007-10-25 17:07:24 +0000335 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000336
Steve Naroff621edce2009-04-29 16:37:50 +0000337 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
Daniel Dunbar4087f272010-08-17 22:39:59 +0000338 llvm::StringRef prefix,
339 llvm::StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +0000340 std::string &Result);
341 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Daniel Dunbar4087f272010-08-17 22:39:59 +0000342 llvm::StringRef prefix,
343 llvm::StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +0000344 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000345 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000346 std::string &Result);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000347 void SynthesizeIvarOffsetComputation(ObjCContainerDecl *IDecl,
Mike Stump1eb44332009-09-09 15:08:12 +0000348 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000349 std::string &Result);
Steve Narofface66252008-11-13 20:07:04 +0000350 void RewriteImplementations();
351 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000352
Steve Naroff54055232008-10-27 17:20:55 +0000353 // Block rewriting.
Mike Stump1eb44332009-09-09 15:08:12 +0000354 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff54055232008-10-27 17:20:55 +0000355 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump1eb44332009-09-09 15:08:12 +0000356
Steve Naroff54055232008-10-27 17:20:55 +0000357 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
358 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump1eb44332009-09-09 15:08:12 +0000359
360 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000361 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000362 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +0000363 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +0000364 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000365 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
Steve Naroff54055232008-10-27 17:20:55 +0000366 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000367
368 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Daniel Dunbar4087f272010-08-17 22:39:59 +0000369 llvm::StringRef funcName, std::string Tag);
Mike Stump1eb44332009-09-09 15:08:12 +0000370 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Daniel Dunbar4087f272010-08-17 22:39:59 +0000371 llvm::StringRef funcName, std::string Tag);
Steve Naroff01aec112009-12-06 21:14:13 +0000372 std::string SynthesizeBlockImpl(BlockExpr *CE,
373 std::string Tag, std::string Desc);
374 std::string SynthesizeBlockDescriptor(std::string DescTag,
375 std::string ImplTag,
Daniel Dunbar4087f272010-08-17 22:39:59 +0000376 int i, llvm::StringRef funcName,
Steve Naroff01aec112009-12-06 21:14:13 +0000377 unsigned hasCopy);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +0000378 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff54055232008-10-27 17:20:55 +0000379 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Daniel Dunbar4087f272010-08-17 22:39:59 +0000380 llvm::StringRef FunName);
Steve Naroff3d7e7862009-12-05 15:55:59 +0000381 void RewriteRecordBody(RecordDecl *RD);
Mike Stump1eb44332009-09-09 15:08:12 +0000382
Steve Naroff54055232008-10-27 17:20:55 +0000383 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000384 void GetBlockDeclRefExprs(Stmt *S);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000385 void GetInnerBlockDeclRefExprs(Stmt *S,
386 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +0000387 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
Mike Stump1eb44332009-09-09 15:08:12 +0000388
Steve Naroff54055232008-10-27 17:20:55 +0000389 // We avoid calling Type::isBlockPointerType(), since it operates on the
390 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000391 bool isTopLevelBlockPointerType(QualType T) {
392 return isa<BlockPointerType>(T);
393 }
Mike Stump1eb44332009-09-09 15:08:12 +0000394
Fariborz Jahanian4fc84532010-05-25 17:12:52 +0000395 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
396 /// to a function pointer type and upon success, returns true; false
397 /// otherwise.
398 bool convertBlockPointerToFunctionPointer(QualType &T) {
399 if (isTopLevelBlockPointerType(T)) {
400 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
401 T = Context->getPointerType(BPT->getPointeeType());
402 return true;
403 }
404 return false;
405 }
406
Steve Naroff54055232008-10-27 17:20:55 +0000407 // FIXME: This predicate seems like it would be useful to add to ASTContext.
408 bool isObjCType(QualType T) {
409 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
410 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000411
Steve Naroff54055232008-10-27 17:20:55 +0000412 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000413
Steve Naroff54055232008-10-27 17:20:55 +0000414 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
415 OCT == Context->getCanonicalType(Context->getObjCClassType()))
416 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000417
Ted Kremenek6217b802009-07-29 21:53:49 +0000418 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000419 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000420 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff54055232008-10-27 17:20:55 +0000421 return true;
422 }
423 return false;
424 }
425 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000426 void GetExtentOfArgList(const char *Name, const char *&LParen,
427 const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000428 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump1eb44332009-09-09 15:08:12 +0000429
Daniel Dunbar4087f272010-08-17 22:39:59 +0000430 FunctionDecl *SynthBlockInitFunctionDecl(llvm::StringRef name);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000431 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
432 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs);
Mike Stump1eb44332009-09-09 15:08:12 +0000433
Steve Naroff621edce2009-04-29 16:37:50 +0000434 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump1eb44332009-09-09 15:08:12 +0000435 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroff621edce2009-04-29 16:37:50 +0000436 if (From[i] == '"')
437 To += "\\\"";
438 else
439 To += From[i];
440 }
441 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000442 };
John McCall9d125032010-01-15 18:39:57 +0000443
444 // Helper function: create a CStyleCastExpr with trivial type source info.
445 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +0000446 CastKind Kind, Expr *E) {
John McCall9d125032010-01-15 18:39:57 +0000447 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
John McCallf871d0c2010-08-07 06:22:56 +0000448 return CStyleCastExpr::Create(*Ctx, Ty, Kind, E, 0, TInfo,
449 SourceLocation(), SourceLocation());
John McCall9d125032010-01-15 18:39:57 +0000450 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000451}
452
Mike Stump1eb44332009-09-09 15:08:12 +0000453void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
454 NamedDecl *D) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000455 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000456 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000457 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000458 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000459 // All the args are checked/rewritten. Don't call twice!
460 RewriteBlockPointerDecl(D);
461 break;
462 }
463 }
464}
465
466void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000467 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +0000468 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000469 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000470}
471
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000472static bool IsHeaderFile(const std::string &Filename) {
473 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump1eb44332009-09-09 15:08:12 +0000474
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000475 if (DotPos == std::string::npos) {
476 // no file extension
Mike Stump1eb44332009-09-09 15:08:12 +0000477 return false;
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000478 }
Mike Stump1eb44332009-09-09 15:08:12 +0000479
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000480 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
481 // C header: .h
482 // C++ header: .hh or .H;
483 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump1eb44332009-09-09 15:08:12 +0000484}
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000485
Eli Friedman66d6f042009-05-18 22:20:00 +0000486RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000487 Diagnostic &D, const LangOptions &LOpts,
488 bool silenceMacroWarn)
489 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
490 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000491 IsHeader = IsHeaderFile(inFile);
Mike Stump1eb44332009-09-09 15:08:12 +0000492 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000493 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump1eb44332009-09-09 15:08:12 +0000494 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000495 "rewriter doesn't support user-specified control flow semantics "
496 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000497}
498
Eli Friedmanbce831b2009-05-18 22:29:17 +0000499ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
500 llvm::raw_ostream* OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000501 Diagnostic &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000502 const LangOptions &LOpts,
503 bool SilenceRewriteMacroWarning) {
504 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere365c502007-11-30 22:25:36 +0000505}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000506
Steve Naroffb29b4272008-04-14 22:03:09 +0000507void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000508 Context = &context;
509 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000510 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000511 MsgSendFunctionDecl = 0;
512 MsgSendSuperFunctionDecl = 0;
513 MsgSendStretFunctionDecl = 0;
514 MsgSendSuperStretFunctionDecl = 0;
515 MsgSendFpretFunctionDecl = 0;
516 GetClassFunctionDecl = 0;
517 GetMetaClassFunctionDecl = 0;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000518 GetSuperClassFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000519 SelGetUidFunctionDecl = 0;
520 CFStringFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000521 ConstantStringClassReference = 0;
522 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000523 CurMethodDef = 0;
524 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000525 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000526 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000527 SuperStructDecl = 0;
Steve Naroff621edce2009-04-29 16:37:50 +0000528 ProtocolTypeDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000529 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000530 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000531 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000532 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000533 PropParentMap = 0;
534 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000535 DisableReplaceStmt = false;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000536 objc_impl_method = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000537
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000538 // Get the ID and start/end of the main file.
539 MainFileID = SM->getMainFileID();
540 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
541 MainFileStart = MainBuf->getBufferStart();
542 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000543
Chris Lattner2c78b872009-04-14 23:22:57 +0000544 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump1eb44332009-09-09 15:08:12 +0000545
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000546 // declaring objc_selector outside the parameter list removes a silly
547 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000548 if (IsHeader)
Steve Naroff62c26322009-02-03 20:39:18 +0000549 Preamble = "#pragma once\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000550 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff46a98a72008-12-23 20:11:22 +0000551 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000552 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000553 if (LangOpts.Microsoft) {
554 // Add a constructor for creating temporary objects.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000555 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
556 ": ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000557 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000558 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000559 Preamble += "};\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000560 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
561 Preamble += "typedef struct objc_object Protocol;\n";
562 Preamble += "#define _REWRITER_typedef_Protocol\n";
563 Preamble += "#endif\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000564 if (LangOpts.Microsoft) {
565 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
566 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
567 } else
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000568 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000569 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000570 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000571 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000572 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000573 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000574 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000575 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000576 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000577 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000578 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000579 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000580 Preamble += "(const char *);\n";
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000581 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
582 Preamble += "(struct objc_class *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000583 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000584 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000585 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
586 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
587 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
588 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
589 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000590 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000591 // @synchronized hooks.
Steve Naroff4ebd7162008-12-08 17:30:33 +0000592 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
593 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
594 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000595 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
596 Preamble += "struct __objcFastEnumerationState {\n\t";
597 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000598 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000599 Preamble += "unsigned long *mutationsPtr;\n\t";
600 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000601 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000602 Preamble += "#define __FASTENUMERATIONSTATE\n";
603 Preamble += "#endif\n";
604 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
605 Preamble += "struct __NSConstantStringImpl {\n";
606 Preamble += " int *isa;\n";
607 Preamble += " int flags;\n";
608 Preamble += " char *str;\n";
609 Preamble += " long length;\n";
610 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000611 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
612 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
613 Preamble += "#else\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000614 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000615 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000616 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
617 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000618 // Blocks preamble.
619 Preamble += "#ifndef BLOCK_IMPL\n";
620 Preamble += "#define BLOCK_IMPL\n";
621 Preamble += "struct __block_impl {\n";
622 Preamble += " void *isa;\n";
623 Preamble += " int Flags;\n";
Steve Naroff01aec112009-12-06 21:14:13 +0000624 Preamble += " int Reserved;\n";
Steve Naroff54055232008-10-27 17:20:55 +0000625 Preamble += " void *FuncPtr;\n";
626 Preamble += "};\n";
Steve Naroff5bc60d02008-12-16 15:50:30 +0000627 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroffc9c1e9c2009-12-06 01:52:22 +0000628 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000629 Preamble += "extern \"C\" __declspec(dllexport) "
630 "void _Block_object_assign(void *, const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000631 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
632 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
633 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
634 Preamble += "#else\n";
Steve Naroffcd826372010-01-05 18:09:31 +0000635 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
636 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000637 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
638 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
639 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000640 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000641 if (LangOpts.Microsoft) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000642 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
643 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Chris Lattner553e5832010-04-13 17:33:56 +0000644 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
Steve Naroffa48396e2008-10-27 18:50:14 +0000645 Preamble += "#define __attribute__(X)\n";
Chris Lattner553e5832010-04-13 17:33:56 +0000646 Preamble += "#endif\n";
Fariborz Jahanian34204192010-01-15 22:29:39 +0000647 Preamble += "#define __weak\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000648 }
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000649 else {
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000650 Preamble += "#define __block\n";
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000651 Preamble += "#define __weak\n";
652 }
Fariborz Jahaniandf496522010-03-02 01:19:04 +0000653 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
654 // as this avoids warning in any 64bit/32bit compilation model.
655 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000656}
657
658
Chris Lattnerf04da132007-10-24 17:06:59 +0000659//===----------------------------------------------------------------------===//
660// Top Level Driver Code
661//===----------------------------------------------------------------------===//
662
Chris Lattner682bf922009-03-29 16:50:03 +0000663void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremeneke50187a2010-02-05 21:28:51 +0000664 if (Diags.hasErrorOccurred())
665 return;
666
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000667 // Two cases: either the decl could be in the main file, or it could be in a
668 // #included file. If the former, rewrite it now. If the later, check to see
669 // if we rewrote the #include/#import.
670 SourceLocation Loc = D->getLocation();
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000671 Loc = SM->getInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000672
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000673 // If this is for a builtin, ignore it.
674 if (Loc.isInvalid()) return;
675
Steve Naroffebf2b562007-10-23 23:50:29 +0000676 // Look for built-in declarations that we need to refer during the rewrite.
677 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000678 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000679 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000680 // declared in <Foundation/NSString.h>
Daniel Dunbar4087f272010-08-17 22:39:59 +0000681 if (FVD->getName() == "_NSConstantStringClassReference") {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000682 ConstantStringClassReference = FVD;
683 return;
684 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000685 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000686 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000687 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000688 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000689 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000690 RewriteProtocolDecl(PD);
Mike Stump1eb44332009-09-09 15:08:12 +0000691 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000692 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000693 RewriteForwardProtocolDecl(FP);
Douglas Gregord0434102009-01-09 00:49:46 +0000694 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
695 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000696 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
697 DIEnd = LSD->decls_end();
Douglas Gregord0434102009-01-09 00:49:46 +0000698 DI != DIEnd; ++DI)
Chris Lattner682bf922009-03-29 16:50:03 +0000699 HandleTopLevelSingleDecl(*DI);
Steve Naroffebf2b562007-10-23 23:50:29 +0000700 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000701 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000702 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000703 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000704}
705
Chris Lattnerf04da132007-10-24 17:06:59 +0000706//===----------------------------------------------------------------------===//
707// Syntactic (non-AST) Rewriting Code
708//===----------------------------------------------------------------------===//
709
Steve Naroffb29b4272008-04-14 22:03:09 +0000710void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000711 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000712 llvm::StringRef MainBuf = SM->getBufferData(MainFileID);
713 const char *MainBufStart = MainBuf.begin();
714 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000715 size_t ImportLen = strlen("import");
Mike Stump1eb44332009-09-09 15:08:12 +0000716
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000717 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000718 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
719 if (*BufPtr == '#') {
720 if (++BufPtr == MainBufEnd)
721 return;
722 while (*BufPtr == ' ' || *BufPtr == '\t')
723 if (++BufPtr == MainBufEnd)
724 return;
725 if (!strncmp(BufPtr, "import", ImportLen)) {
726 // replace import with include
Mike Stump1eb44332009-09-09 15:08:12 +0000727 SourceLocation ImportLoc =
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000728 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000729 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000730 BufPtr += ImportLen;
731 }
732 }
733 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000734}
735
Steve Naroffeb0646c2008-12-02 15:48:25 +0000736static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
737 ObjCIvarDecl *OID) {
738 std::string S;
739 S = "((struct ";
740 S += ClassDecl->getIdentifier()->getName();
741 S += "_IMPL *)self)->";
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +0000742 S += OID->getName();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000743 return S;
744}
745
Steve Naroffa0876e82008-12-02 17:36:43 +0000746void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
747 ObjCImplementationDecl *IMD,
748 ObjCCategoryImplDecl *CID) {
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000749 static bool objcGetPropertyDefined = false;
750 static bool objcSetPropertyDefined = false;
Steve Naroffd40910b2008-12-01 20:33:01 +0000751 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramerd999b372010-02-14 14:14:16 +0000752 InsertText(startLoc, "// ");
Steve Naroffeb0646c2008-12-02 15:48:25 +0000753 const char *startBuf = SM->getCharacterData(startLoc);
754 assert((*startBuf == '@') && "bogus @synthesize location");
755 const char *semiBuf = strchr(startBuf, ';');
756 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000757 SourceLocation onePastSemiLoc =
758 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000759
760 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
761 return; // FIXME: is this correct?
Mike Stump1eb44332009-09-09 15:08:12 +0000762
Steve Naroffeb0646c2008-12-02 15:48:25 +0000763 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000764 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000765 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000766 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000767
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000768 if (!OID)
769 return;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000770 unsigned Attributes = PD->getPropertyAttributes();
771 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
772 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
773 ObjCPropertyDecl::OBJC_PR_copy));
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000774 std::string Getr;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000775 if (GenGetProperty && !objcGetPropertyDefined) {
776 objcGetPropertyDefined = true;
777 // FIXME. Is this attribute correct in all cases?
778 Getr = "\nextern \"C\" __declspec(dllimport) "
779 "id objc_getProperty(id, SEL, long, bool);\n";
780 }
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000781 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
782 Getr += "{ ";
783 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroff3539cdb2008-12-02 17:54:50 +0000784 // See objc-act.c:objc_synthesize_new_getter() for details.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000785 if (GenGetProperty) {
786 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
787 Getr += "typedef ";
788 const FunctionType *FPRetType = 0;
789 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
790 FPRetType);
791 Getr += " _TYPE";
792 if (FPRetType) {
793 Getr += ")"; // close the precedence "scope" for "*".
794
795 // Now, emit the argument types (if any).
Daniel Dunbarfa297fb2010-06-30 19:16:53 +0000796 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000797 Getr += "(";
798 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
799 if (i) Getr += ", ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +0000800 std::string ParamStr = FT->getArgType(i).getAsString(
801 Context->PrintingPolicy);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000802 Getr += ParamStr;
803 }
804 if (FT->isVariadic()) {
805 if (FT->getNumArgs()) Getr += ", ";
806 Getr += "...";
807 }
808 Getr += ")";
809 } else
810 Getr += "()";
811 }
812 Getr += ";\n";
813 Getr += "return (_TYPE)";
814 Getr += "objc_getProperty(self, _cmd, ";
815 SynthesizeIvarOffsetComputation(ClassDecl, OID, Getr);
816 Getr += ", 1)";
817 }
818 else
819 Getr += "return " + getIvarAccessString(ClassDecl, OID);
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000820 Getr += "; }";
Benjamin Kramerd999b372010-02-14 14:14:16 +0000821 InsertText(onePastSemiLoc, Getr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000822 if (PD->isReadOnly())
823 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000824
Steve Naroffeb0646c2008-12-02 15:48:25 +0000825 // Generate the 'setter' function.
826 std::string Setr;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000827 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
828 ObjCPropertyDecl::OBJC_PR_copy);
829 if (GenSetProperty && !objcSetPropertyDefined) {
830 objcSetPropertyDefined = true;
831 // FIXME. Is this attribute correct in all cases?
832 Setr = "\nextern \"C\" __declspec(dllimport) "
833 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
834 }
835
Steve Naroffeb0646c2008-12-02 15:48:25 +0000836 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000837 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000838 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff15f081d2008-12-03 00:56:33 +0000839 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000840 if (GenSetProperty) {
841 Setr += "objc_setProperty (self, _cmd, ";
842 SynthesizeIvarOffsetComputation(ClassDecl, OID, Setr);
843 Setr += ", (id)";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000844 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000845 Setr += ", ";
846 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
847 Setr += "0, ";
848 else
849 Setr += "1, ";
850 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
851 Setr += "1)";
852 else
853 Setr += "0)";
854 }
855 else {
856 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000857 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000858 }
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000859 Setr += "; }";
Benjamin Kramerd999b372010-02-14 14:14:16 +0000860 InsertText(onePastSemiLoc, Setr);
Steve Naroffd40910b2008-12-01 20:33:01 +0000861}
Chris Lattner8a12c272007-10-11 18:38:32 +0000862
Steve Naroffb29b4272008-04-14 22:03:09 +0000863void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000864 // Get the start location and compute the semi location.
865 SourceLocation startLoc = ClassDecl->getLocation();
866 const char *startBuf = SM->getCharacterData(startLoc);
867 const char *semiPtr = strchr(startBuf, ';');
Mike Stump1eb44332009-09-09 15:08:12 +0000868
Chris Lattnerf04da132007-10-24 17:06:59 +0000869 // Translate to typedef's that forward reference structs with the same name
870 // as the class. As a convenience, we include the original declaration
871 // as a comment.
872 std::string typedefString;
Fariborz Jahanian91fbd122010-01-11 22:48:40 +0000873 typedefString += "// @class ";
874 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
875 I != E; ++I) {
876 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
877 typedefString += ForwardDecl->getNameAsString();
878 if (I+1 != E)
879 typedefString += ", ";
880 else
881 typedefString += ";\n";
882 }
883
Chris Lattner67956052009-02-20 18:04:31 +0000884 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
885 I != E; ++I) {
Ted Kremenek321c22f2009-11-18 00:28:11 +0000886 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff32174822007-11-09 12:50:28 +0000887 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000888 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000889 typedefString += "\n";
890 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000891 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000892 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000893 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000894 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000895 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000896 }
Mike Stump1eb44332009-09-09 15:08:12 +0000897
Steve Naroff934f2762007-10-24 22:48:43 +0000898 // Replace the @class with typedefs corresponding to the classes.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000899 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
Chris Lattnerf04da132007-10-24 17:06:59 +0000900}
901
Steve Naroffb29b4272008-04-14 22:03:09 +0000902void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000903 // When method is a synthesized one, such as a getter/setter there is
904 // nothing to rewrite.
905 if (Method->isSynthesized())
906 return;
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000907 SourceLocation LocStart = Method->getLocStart();
908 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000909
Chris Lattner30fc9332009-02-04 01:06:56 +0000910 if (SM->getInstantiationLineNumber(LocEnd) >
911 SM->getInstantiationLineNumber(LocStart)) {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000912 InsertText(LocStart, "#if 0\n");
913 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000914 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000915 InsertText(LocStart, "// ");
Steve Naroff423cb562007-10-30 13:30:57 +0000916 }
917}
918
Mike Stump1eb44332009-09-09 15:08:12 +0000919void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000920 SourceLocation Loc = prop->getAtLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000921
Benjamin Kramerd999b372010-02-14 14:14:16 +0000922 ReplaceText(Loc, 0, "// ");
Steve Naroff6327e0d2009-01-11 01:06:09 +0000923 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000924}
925
Steve Naroffb29b4272008-04-14 22:03:09 +0000926void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000927 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000928
Steve Naroff423cb562007-10-30 13:30:57 +0000929 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000930 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000931
Fariborz Jahanian13751e32010-02-10 01:15:09 +0000932 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
933 E = CatDecl->prop_end(); I != E; ++I)
934 RewriteProperty(*I);
935
Mike Stump1eb44332009-09-09 15:08:12 +0000936 for (ObjCCategoryDecl::instmeth_iterator
937 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000938 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000939 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +0000940 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000941 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000942 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000943 RewriteMethodDeclaration(*I);
944
Steve Naroff423cb562007-10-30 13:30:57 +0000945 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +0000946 ReplaceText(CatDecl->getAtEndRange().getBegin(),
947 strlen("@end"), "/* @end */");
Steve Naroff423cb562007-10-30 13:30:57 +0000948}
949
Steve Naroffb29b4272008-04-14 22:03:09 +0000950void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000951 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000952
Steve Naroff752d6ef2007-10-30 16:42:30 +0000953 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000954 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000955
956 for (ObjCProtocolDecl::instmeth_iterator
957 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000958 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000959 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000960 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000961 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000962 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000963 RewriteMethodDeclaration(*I);
964
Steve Naroff752d6ef2007-10-30 16:42:30 +0000965 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +0000966 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +0000967 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroff8cc764c2007-11-14 15:03:57 +0000968
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000969 // Must comment out @optional/@required
970 const char *startBuf = SM->getCharacterData(LocStart);
971 const char *endBuf = SM->getCharacterData(LocEnd);
972 for (const char *p = startBuf; p < endBuf; p++) {
973 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Steve Naroff8cc764c2007-11-14 15:03:57 +0000974 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000975 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump1eb44332009-09-09 15:08:12 +0000976
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000977 }
978 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Steve Naroff8cc764c2007-11-14 15:03:57 +0000979 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000980 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump1eb44332009-09-09 15:08:12 +0000981
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000982 }
983 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000984}
985
Steve Naroffb29b4272008-04-14 22:03:09 +0000986void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000987 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000988 if (LocStart.isInvalid())
989 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000990 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000991 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000992}
993
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000994void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
995 const FunctionType *&FPRetType) {
996 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000997 ResultStr += "id";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000998 else if (T->isFunctionPointerType() ||
999 T->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001000 // needs special handling, since pointer-to-functions have special
1001 // syntax (where a decaration models use).
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001002 QualType retType = T;
Steve Narofff4312dc2008-12-11 19:29:16 +00001003 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001004 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001005 PointeeTy = PT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001006 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001007 PointeeTy = BPT->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001008 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001009 ResultStr += FPRetType->getResultType().getAsString(
1010 Context->PrintingPolicy);
Steve Narofff4312dc2008-12-11 19:29:16 +00001011 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +00001012 }
1013 } else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001014 ResultStr += T.getAsString(Context->PrintingPolicy);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001015}
1016
1017void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
1018 std::string &ResultStr) {
1019 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1020 const FunctionType *FPRetType = 0;
1021 ResultStr += "\nstatic ";
1022 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001023 ResultStr += " ";
Mike Stump1eb44332009-09-09 15:08:12 +00001024
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001025 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001026 std::string NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001027
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001028 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001029 NameStr += "_I_";
1030 else
1031 NameStr += "_C_";
Mike Stump1eb44332009-09-09 15:08:12 +00001032
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001033 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001034 NameStr += "_";
Mike Stump1eb44332009-09-09 15:08:12 +00001035
1036 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +00001037 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001038 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001039 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001040 }
Mike Stump1eb44332009-09-09 15:08:12 +00001041 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +00001042 {
1043 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001044 int len = selString.size();
1045 for (int i = 0; i < len; i++)
1046 if (selString[i] == ':')
1047 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001048 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001049 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001050 // Remember this name for metadata emission
1051 MethodInternalNames[OMD] = NameStr;
1052 ResultStr += NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001053
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001054 // Rewrite arguments
1055 ResultStr += "(";
Mike Stump1eb44332009-09-09 15:08:12 +00001056
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001057 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001058 if (OMD->isInstanceMethod()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001059 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001060 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +00001061 if (!LangOpts.Microsoft) {
1062 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
1063 ResultStr += "struct ";
1064 }
1065 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001066 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001067 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001068 }
1069 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001070 ResultStr += Context->getObjCClassType().getAsString(
1071 Context->PrintingPolicy);
Mike Stump1eb44332009-09-09 15:08:12 +00001072
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001073 ResultStr += " self, ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001074 ResultStr += Context->getObjCSelType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001075 ResultStr += " _cmd";
Mike Stump1eb44332009-09-09 15:08:12 +00001076
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001077 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +00001078 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1079 E = OMD->param_end(); PI != E; ++PI) {
1080 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001081 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +00001082 if (PDecl->getType()->isObjCQualifiedIdType()) {
1083 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001084 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +00001085 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001086 std::string Name = PDecl->getNameAsString();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00001087 QualType QT = PDecl->getType();
1088 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1089 if (convertBlockPointerToFunctionPointer(QT))
1090 QT.getAsStringInternal(Name, Context->PrintingPolicy);
1091 else
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001092 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroff543409e2008-04-18 21:13:19 +00001093 ResultStr += Name;
1094 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001095 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +00001096 if (OMD->isVariadic())
1097 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001098 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +00001099
Steve Naroff76e429d2008-07-16 14:40:40 +00001100 if (FPRetType) {
1101 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +00001102
Steve Naroff76e429d2008-07-16 14:40:40 +00001103 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +00001104 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001105 ResultStr += "(";
1106 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1107 if (i) ResultStr += ", ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001108 std::string ParamStr = FT->getArgType(i).getAsString(
1109 Context->PrintingPolicy);
Steve Naroff76e429d2008-07-16 14:40:40 +00001110 ResultStr += ParamStr;
1111 }
1112 if (FT->isVariadic()) {
1113 if (FT->getNumArgs()) ResultStr += ", ";
1114 ResultStr += "...";
1115 }
1116 ResultStr += ")";
1117 } else {
1118 ResultStr += "()";
1119 }
1120 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001121}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001122void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001123 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1124 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001125
Fariborz Jahaniana1352162010-02-15 21:11:41 +00001126 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001127
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001128 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001129 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1130 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001131 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001132 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001133 ObjCMethodDecl *OMD = *I;
1134 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001135 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001136 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001137
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001138 const char *startBuf = SM->getCharacterData(LocStart);
1139 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001140 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001141 }
Mike Stump1eb44332009-09-09 15:08:12 +00001142
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001143 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001144 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1145 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001146 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001147 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001148 ObjCMethodDecl *OMD = *I;
1149 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001150 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001151 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001152
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001153 const char *startBuf = SM->getCharacterData(LocStart);
1154 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001155 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001156 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001157 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001158 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001159 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001160 I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001161 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001162 }
1163
Benjamin Kramerd999b372010-02-14 14:14:16 +00001164 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001165}
1166
Steve Naroffb29b4272008-04-14 22:03:09 +00001167void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001168 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001169 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001170 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001171 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001172 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001173 ResultStr += "\n";
1174 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001175 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001176 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001177 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001178 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001179 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001180 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001181 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001182 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001183 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001184
1185 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001186 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff6327e0d2009-01-11 01:06:09 +00001187 RewriteProperty(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001188 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001189 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001190 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001191 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001192 for (ObjCInterfaceDecl::classmeth_iterator
1193 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001194 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001195 RewriteMethodDeclaration(*I);
1196
Steve Naroff2feac5e2007-10-30 03:43:13 +00001197 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001198 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1199 "/* @end */");
Steve Naroffbef11852007-10-26 20:53:56 +00001200}
1201
Steve Naroffb619d952008-12-09 12:56:34 +00001202Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1203 SourceRange SrcRange) {
Steve Naroffc77a6362008-12-04 16:24:46 +00001204 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1205 // This allows us to reuse all the fun and games in SynthMessageExpr().
1206 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1207 ObjCMessageExpr *MsgExpr;
1208 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1209 llvm::SmallVector<Expr *, 1> ExprVec;
1210 ExprVec.push_back(newStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001211
Steve Naroff8599e7a2008-12-08 16:43:47 +00001212 Stmt *Receiver = PropRefExpr->getBase();
1213 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1214 if (PRE && PropGetters[PRE]) {
1215 // This allows us to handle chain/nested property getters.
1216 Receiver = PropGetters[PRE];
1217 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001218 if (isa<ObjCSuperExpr>(Receiver))
1219 MsgExpr = ObjCMessageExpr::Create(*Context,
1220 PDecl->getType().getNonReferenceType(),
1221 /*FIXME?*/SourceLocation(),
1222 Receiver->getLocStart(),
1223 /*IsInstanceSuper=*/true,
1224 cast<Expr>(Receiver)->getType(),
1225 PDecl->getSetterName(),
1226 PDecl->getSetterMethodDecl(),
1227 &ExprVec[0], 1,
1228 /*FIXME:*/SourceLocation());
1229 else
1230 MsgExpr = ObjCMessageExpr::Create(*Context,
1231 PDecl->getType().getNonReferenceType(),
1232 /*FIXME: */SourceLocation(),
1233 cast<Expr>(Receiver),
1234 PDecl->getSetterName(),
1235 PDecl->getSetterMethodDecl(),
1236 &ExprVec[0], 1,
1237 /*FIXME:*/SourceLocation());
Steve Naroffc77a6362008-12-04 16:24:46 +00001238 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001239
Steve Naroffc77a6362008-12-04 16:24:46 +00001240 // Now do the actual rewrite.
Steve Naroffb619d952008-12-09 12:56:34 +00001241 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffe58ee0c2008-12-10 14:53:27 +00001242 //delete BinOp;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001243 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1244 // to things that stay around.
1245 Context->Deallocate(MsgExpr);
Steve Naroffc77a6362008-12-04 16:24:46 +00001246 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001247}
1248
Steve Naroffc77a6362008-12-04 16:24:46 +00001249Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Naroff15f081d2008-12-03 00:56:33 +00001250 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1251 // This allows us to reuse all the fun and games in SynthMessageExpr().
1252 ObjCMessageExpr *MsgExpr;
1253 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
Mike Stump1eb44332009-09-09 15:08:12 +00001254
Steve Naroff8599e7a2008-12-08 16:43:47 +00001255 Stmt *Receiver = PropRefExpr->getBase();
Mike Stump1eb44332009-09-09 15:08:12 +00001256
Steve Naroff8599e7a2008-12-08 16:43:47 +00001257 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1258 if (PRE && PropGetters[PRE]) {
1259 // This allows us to handle chain/nested property getters.
1260 Receiver = PropGetters[PRE];
1261 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001262
1263 if (isa<ObjCSuperExpr>(Receiver))
1264 MsgExpr = ObjCMessageExpr::Create(*Context,
1265 PDecl->getType().getNonReferenceType(),
1266 /*FIXME:*/SourceLocation(),
1267 Receiver->getLocStart(),
1268 /*IsInstanceSuper=*/true,
1269 cast<Expr>(Receiver)->getType(),
1270 PDecl->getGetterName(),
1271 PDecl->getGetterMethodDecl(),
1272 0, 0,
1273 /*FIXME:*/SourceLocation());
1274 else
1275 MsgExpr = ObjCMessageExpr::Create(*Context,
1276 PDecl->getType().getNonReferenceType(),
1277 /*FIXME:*/SourceLocation(),
1278 cast<Expr>(Receiver),
1279 PDecl->getGetterName(),
1280 PDecl->getGetterMethodDecl(),
1281 0, 0,
1282 /*FIXME:*/SourceLocation());
Steve Naroff15f081d2008-12-03 00:56:33 +00001283
Steve Naroff4c3580e2008-12-04 23:50:32 +00001284 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001285
1286 if (!PropParentMap)
1287 PropParentMap = new ParentMap(CurrentBody);
1288
1289 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1290 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1291 // We stash away the ReplacingStmt since actually doing the
1292 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1293 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek8189cde2009-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 Naroff8599e7a2008-12-08 16:43:47 +00001297 return PropRefExpr; // return the original...
1298 } else {
1299 ReplaceStmt(PropRefExpr, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001300 // delete PropRefExpr; elsewhere...
Ted Kremenek8189cde2009-02-07 01:47:29 +00001301 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1302 // to things that stay around.
1303 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001304 return ReplacingStmt;
1305 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001306}
1307
Mike Stump1eb44332009-09-09 15:08:12 +00001308Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001309 SourceLocation OrigStart,
1310 bool &replaced) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001311 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001312 const Expr *BaseExpr = IV->getBase();
Steve Naroff54055232008-10-27 17:20:55 +00001313 if (CurMethodDef) {
Fariborz Jahanian8f095432010-01-26 18:28:51 +00001314 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001315 ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001316 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianffbdead2010-01-26 20:37:44 +00001317 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Narofff0757612008-05-08 17:52:16 +00001318 // lookup which class implements the instance variable.
1319 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001320 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001321 clsDeclared);
Steve Narofff0757612008-05-08 17:52:16 +00001322 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001323
Steve Narofff0757612008-05-08 17:52:16 +00001324 // Synthesize an explicit cast to gain access to the ivar.
1325 std::string RecName = clsDeclared->getIdentifier()->getName();
1326 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001327 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001328 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001329 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +00001330 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1331 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001332 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCall2de56d12010-08-25 11:45:40 +00001333 CK_Unknown,
John McCall9d125032010-01-15 18:39:57 +00001334 IV->getBase());
Steve Narofff0757612008-05-08 17:52:16 +00001335 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001336 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1337 IV->getBase()->getLocEnd(),
1338 castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001339 replaced = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001340 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001341 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001342 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1343 IV->getLocation(),
1344 D->getType());
Steve Naroff4c3580e2008-12-04 23:50:32 +00001345 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001346 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001347 }
Fariborz Jahanian7e20ffe2010-01-28 01:41:20 +00001348 // Get the new text
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001349 // Cannot delete IV->getBase(), since PE points to it.
1350 // Replace the old base with the cast. This is important when doing
1351 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001352 IV->setBase(PE);
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001353 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001354 }
Steve Naroff84472a82008-04-18 21:55:08 +00001355 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001356 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump1eb44332009-09-09 15:08:12 +00001357
Steve Naroff9f525972008-05-06 23:20:07 +00001358 // Explicit ivar refs need to have a cast inserted.
1359 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian26337b22010-01-12 17:31:23 +00001360 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Fariborz Jahanianc374cd92010-01-11 17:50:35 +00001361 ObjCInterfaceType *iFaceDecl =
1362 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001363 // lookup which class implements the instance variable.
1364 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001365 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001366 clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001367 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001368
Steve Naroff9f525972008-05-06 23:20:07 +00001369 // Synthesize an explicit cast to gain access to the ivar.
1370 std::string RecName = clsDeclared->getIdentifier()->getName();
1371 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001372 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001373 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001374 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001375 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1376 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001377 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCall2de56d12010-08-25 11:45:40 +00001378 CK_Unknown,
John McCall9d125032010-01-15 18:39:57 +00001379 IV->getBase());
Steve Naroff9f525972008-05-06 23:20:07 +00001380 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001381 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner8d366162008-05-28 16:38:23 +00001382 IV->getBase()->getLocEnd(), castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001383 replaced = true;
Steve Naroff9f525972008-05-06 23:20:07 +00001384 // Cannot delete IV->getBase(), since PE points to it.
1385 // Replace the old base with the cast. This is important when doing
1386 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001387 IV->setBase(PE);
Steve Naroff9f525972008-05-06 23:20:07 +00001388 return IV;
1389 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001390 }
Steve Naroff84472a82008-04-18 21:55:08 +00001391 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001392}
1393
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001394Stmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) {
1395 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1396 CI != E; ++CI) {
1397 if (*CI) {
1398 Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced);
1399 if (newStmt)
1400 *CI = newStmt;
1401 }
1402 }
1403 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
1404 SourceRange OrigStmtRange = S->getSourceRange();
1405 Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(),
1406 replaced);
1407 return newStmt;
Fariborz Jahanian376338a2010-02-05 17:48:10 +00001408 }
1409 if (ObjCMessageExpr *MsgRefExpr = dyn_cast<ObjCMessageExpr>(S)) {
1410 Stmt *newStmt = SynthMessageExpr(MsgRefExpr);
1411 return newStmt;
1412 }
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001413 return S;
1414}
1415
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001416/// SynthCountByEnumWithState - To print:
1417/// ((unsigned int (*)
1418/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001419/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001420/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001421/// "countByEnumeratingWithState:objects:count:"),
1422/// &enumState,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001423/// (id *)items, (unsigned int)16)
1424///
Steve Naroffb29b4272008-04-14 22:03:09 +00001425void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001426 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1427 "id *, unsigned int))(void *)objc_msgSend)";
1428 buf += "\n\t\t";
1429 buf += "((id)l_collection,\n\t\t";
1430 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1431 buf += "\n\t\t";
1432 buf += "&enumState, "
1433 "(id *)items, (unsigned int)16)";
1434}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001435
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001436/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1437/// statement to exit to its outer synthesized loop.
1438///
Steve Naroffb29b4272008-04-14 22:03:09 +00001439Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001440 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1441 return S;
1442 // replace break with goto __break_label
1443 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001444
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001445 SourceLocation startLoc = S->getLocStart();
1446 buf = "goto __break_label_";
1447 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001448 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001449
1450 return 0;
1451}
1452
1453/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1454/// statement to continue with its inner synthesized loop.
1455///
Steve Naroffb29b4272008-04-14 22:03:09 +00001456Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001457 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1458 return S;
1459 // replace continue with goto __continue_label
1460 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001461
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001462 SourceLocation startLoc = S->getLocStart();
1463 buf = "goto __continue_label_";
1464 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001465 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001466
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001467 return 0;
1468}
1469
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001470/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001471/// It rewrites:
1472/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001473
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001474/// Into:
1475/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001476/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001477/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001478/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001479/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001480/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001481/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001482/// if (limit) {
1483/// unsigned long startMutations = *enumState.mutationsPtr;
1484/// do {
1485/// unsigned long counter = 0;
1486/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001487/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001488/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001489/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001490/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001491/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001492/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001493/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001494/// objects:items count:16]);
1495/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001496/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001497/// }
1498/// else
1499/// elem = nil;
1500/// }
1501///
Steve Naroffb29b4272008-04-14 22:03:09 +00001502Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001503 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001504 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001505 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001506 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001507 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001508 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001509
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001510 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001511 const char *startBuf = SM->getCharacterData(startLoc);
Daniel Dunbar4087f272010-08-17 22:39:59 +00001512 llvm::StringRef elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001513 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001514 std::string buf;
1515 buf = "\n{\n\t";
1516 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1517 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001518 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001519 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001520 if (ElementType->isObjCQualifiedIdType() ||
1521 ElementType->isObjCQualifiedInterfaceType())
1522 // Simply use 'id' for all qualified types.
1523 elementTypeAsString = "id";
1524 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001525 elementTypeAsString = ElementType.getAsString(Context->PrintingPolicy);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001526 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001527 buf += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00001528 elementName = D->getName();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001529 buf += elementName;
1530 buf += ";\n\t";
1531 }
Chris Lattner06767512008-04-08 05:52:18 +00001532 else {
1533 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar4087f272010-08-17 22:39:59 +00001534 elementName = DR->getDecl()->getName();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001535 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1536 if (VD->getType()->isObjCQualifiedIdType() ||
1537 VD->getType()->isObjCQualifiedInterfaceType())
1538 // Simply use 'id' for all qualified types.
1539 elementTypeAsString = "id";
1540 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001541 elementTypeAsString = VD->getType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001542 }
Mike Stump1eb44332009-09-09 15:08:12 +00001543
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001544 // struct __objcFastEnumerationState enumState = { 0 };
1545 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1546 // id items[16];
1547 buf += "id items[16];\n\t";
1548 // id l_collection = (id)
1549 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001550 // Find start location of 'collection' the hard way!
1551 const char *startCollectionBuf = startBuf;
1552 startCollectionBuf += 3; // skip 'for'
1553 startCollectionBuf = strchr(startCollectionBuf, '(');
1554 startCollectionBuf++; // skip '('
1555 // find 'in' and skip it.
1556 while (*startCollectionBuf != ' ' ||
1557 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1558 (*(startCollectionBuf+3) != ' ' &&
1559 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1560 startCollectionBuf++;
1561 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001562
1563 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001564 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001565 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001566 SourceLocation rightParenLoc = S->getRParenLoc();
1567 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1568 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001569 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001570
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001571 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1572 // objects:items count:16];
1573 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001574 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001575 // ((unsigned int (*)
1576 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001577 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001578 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001579 // "countByEnumeratingWithState:objects:count:"),
1580 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001581 // (id *)items, (unsigned int)16);
1582 buf += "unsigned long limit =\n\t\t";
1583 SynthCountByEnumWithState(buf);
1584 buf += ";\n\t";
1585 /// if (limit) {
1586 /// unsigned long startMutations = *enumState.mutationsPtr;
1587 /// do {
1588 /// unsigned long counter = 0;
1589 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001590 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001591 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001592 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001593 buf += "if (limit) {\n\t";
1594 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1595 buf += "do {\n\t\t";
1596 buf += "unsigned long counter = 0;\n\t\t";
1597 buf += "do {\n\t\t\t";
1598 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1599 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1600 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001601 buf += " = (";
1602 buf += elementTypeAsString;
1603 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001604 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001605 ReplaceText(lparenLoc, 1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001606
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001607 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001608 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001609 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001610 /// objects:items count:16]);
1611 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001612 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001613 /// }
1614 /// else
1615 /// elem = nil;
1616 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001617 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001618 buf = ";\n\t";
1619 buf += "__continue_label_";
1620 buf += utostr(ObjCBcLabelNo.back());
1621 buf += ": ;";
1622 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001623 buf += "} while (counter < limit);\n\t";
1624 buf += "} while (limit = ";
1625 SynthCountByEnumWithState(buf);
1626 buf += ");\n\t";
1627 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001628 buf += " = ((";
1629 buf += elementTypeAsString;
1630 buf += ")0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001631 buf += "__break_label_";
1632 buf += utostr(ObjCBcLabelNo.back());
1633 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001634 buf += "}\n\t";
1635 buf += "else\n\t\t";
1636 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001637 buf += " = ((";
1638 buf += elementTypeAsString;
1639 buf += ")0);\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001640 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001641
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001642 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001643 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001644 if (isa<CompoundStmt>(S->getBody())) {
1645 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001646 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001647 } else {
1648 /* Need to treat single statements specially. For example:
1649 *
1650 * for (A *a in b) if (stuff()) break;
1651 * for (A *a in b) xxxyy;
1652 *
1653 * The following code simply scans ahead to the semi to find the actual end.
1654 */
1655 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1656 const char *semiBuf = strchr(stmtBuf, ';');
1657 assert(semiBuf && "Can't find ';'");
1658 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001659 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001660 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001661 Stmts.pop_back();
1662 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001663 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001664}
1665
Mike Stump1eb44332009-09-09 15:08:12 +00001666/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001667/// This routine rewrites @synchronized(expr) stmt;
1668/// into:
1669/// objc_sync_enter(expr);
1670/// @try stmt @finally { objc_sync_exit(expr); }
1671///
Steve Naroffb29b4272008-04-14 22:03:09 +00001672Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001673 // Get the start location and compute the semi location.
1674 SourceLocation startLoc = S->getLocStart();
1675 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001676
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001677 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001678
1679 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001680 buf = "objc_sync_enter((id)";
1681 const char *lparenBuf = startBuf;
1682 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramerd999b372010-02-14 14:14:16 +00001683 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001684 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1685 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001686 // been rewritten! (which implies the SourceLocation's are invalid).
1687 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001688 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001689 while (*endBuf != ')') endBuf--;
1690 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001691 buf = ");\n";
1692 // declare a new scope with two variables, _stack and _rethrow.
1693 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1694 buf += "int buf[18/*32-bit i386*/];\n";
1695 buf += "char *pointers[4];} _stack;\n";
1696 buf += "id volatile _rethrow = 0;\n";
1697 buf += "objc_exception_try_enter(&_stack);\n";
1698 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001699 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001700 startLoc = S->getSynchBody()->getLocEnd();
1701 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001702
Steve Naroffc7089f12008-08-19 13:04:19 +00001703 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001704 SourceLocation lastCurlyLoc = startLoc;
1705 buf = "}\nelse {\n";
1706 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001707 buf += "}\n";
1708 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001709 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001710
1711 std::string syncBuf;
1712 syncBuf += " objc_sync_exit(";
John McCall9d125032010-01-15 18:39:57 +00001713 Expr *syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall2de56d12010-08-25 11:45:40 +00001714 CK_Unknown,
John McCall9d125032010-01-15 18:39:57 +00001715 S->getSynchExpr());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001716 std::string syncExprBufS;
1717 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00001718 syncExpr->printPretty(syncExprBuf, *Context, 0,
1719 PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001720 syncBuf += syncExprBuf.str();
1721 syncBuf += ");";
1722
1723 buf += syncBuf;
1724 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001725 buf += "}\n";
1726 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001727
Benjamin Kramerd999b372010-02-14 14:14:16 +00001728 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001729
1730 bool hasReturns = false;
1731 HasReturnStmts(S->getSynchBody(), hasReturns);
1732 if (hasReturns)
1733 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1734
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001735 return 0;
1736}
1737
Steve Naroffb85e77a2009-12-05 21:43:12 +00001738void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1739{
Steve Naroff8c565152008-12-05 17:03:39 +00001740 // Perform a bottom up traversal of all children.
1741 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1742 CI != E; ++CI)
1743 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001744 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001745
Steve Naroffb85e77a2009-12-05 21:43:12 +00001746 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001747 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001748 TryFinallyContainsReturnDiag);
1749 }
1750 return;
1751}
1752
Steve Naroffb85e77a2009-12-05 21:43:12 +00001753void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1754{
1755 // Perform a bottom up traversal of all children.
1756 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1757 CI != E; ++CI)
1758 if (*CI)
1759 HasReturnStmts(*CI, hasReturns);
1760
1761 if (isa<ReturnStmt>(S))
1762 hasReturns = true;
1763 return;
1764}
1765
1766void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1767 // Perform a bottom up traversal of all children.
1768 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1769 CI != E; ++CI)
1770 if (*CI) {
1771 RewriteTryReturnStmts(*CI);
1772 }
1773 if (isa<ReturnStmt>(S)) {
1774 SourceLocation startLoc = S->getLocStart();
1775 const char *startBuf = SM->getCharacterData(startLoc);
1776
1777 const char *semiBuf = strchr(startBuf, ';');
1778 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1779 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1780
1781 std::string buf;
1782 buf = "{ objc_exception_try_exit(&_stack); return";
1783
Benjamin Kramerd999b372010-02-14 14:14:16 +00001784 ReplaceText(startLoc, 6, buf);
1785 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001786 }
1787 return;
1788}
1789
1790void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1791 // Perform a bottom up traversal of all children.
1792 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1793 CI != E; ++CI)
1794 if (*CI) {
1795 RewriteSyncReturnStmts(*CI, syncExitBuf);
1796 }
1797 if (isa<ReturnStmt>(S)) {
1798 SourceLocation startLoc = S->getLocStart();
1799 const char *startBuf = SM->getCharacterData(startLoc);
1800
1801 const char *semiBuf = strchr(startBuf, ';');
1802 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1803 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1804
1805 std::string buf;
1806 buf = "{ objc_exception_try_exit(&_stack);";
1807 buf += syncExitBuf;
1808 buf += " return";
1809
Benjamin Kramerd999b372010-02-14 14:14:16 +00001810 ReplaceText(startLoc, 6, buf);
1811 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001812 }
1813 return;
1814}
1815
Steve Naroffb29b4272008-04-14 22:03:09 +00001816Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001817 // Get the start location and compute the semi location.
1818 SourceLocation startLoc = S->getLocStart();
1819 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001820
Steve Naroff75730982007-11-07 04:08:17 +00001821 assert((*startBuf == '@') && "bogus @try location");
1822
1823 std::string buf;
1824 // declare a new scope with two variables, _stack and _rethrow.
1825 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1826 buf += "int buf[18/*32-bit i386*/];\n";
1827 buf += "char *pointers[4];} _stack;\n";
1828 buf += "id volatile _rethrow = 0;\n";
1829 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001830 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001831
Benjamin Kramerd999b372010-02-14 14:14:16 +00001832 ReplaceText(startLoc, 4, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001833
Steve Naroff75730982007-11-07 04:08:17 +00001834 startLoc = S->getTryBody()->getLocEnd();
1835 startBuf = SM->getCharacterData(startLoc);
1836
1837 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001838
Steve Naroff75730982007-11-07 04:08:17 +00001839 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001840 if (S->getNumCatchStmts()) {
Steve Naroffc9ba1722008-07-16 15:31:30 +00001841 startLoc = startLoc.getFileLocWithOffset(1);
1842 buf = " /* @catch begin */ else {\n";
1843 buf += " id _caught = objc_exception_extract(&_stack);\n";
1844 buf += " objc_exception_try_enter (&_stack);\n";
1845 buf += " if (_setjmp(_stack.buf))\n";
1846 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1847 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00001848
Benjamin Kramerd999b372010-02-14 14:14:16 +00001849 InsertText(startLoc, buf);
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001850 } else { /* no catch list */
1851 buf = "}\nelse {\n";
1852 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1853 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001854 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001855 }
Steve Naroff75730982007-11-07 04:08:17 +00001856 bool sawIdTypedCatch = false;
1857 Stmt *lastCatchBody = 0;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001858 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1859 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregorc00d8e12010-04-26 16:46:50 +00001860 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00001861
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001862 if (I == 0)
Steve Naroff75730982007-11-07 04:08:17 +00001863 buf = "if ("; // we are generating code for the first catch clause
1864 else
1865 buf = "else if (";
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001866 startLoc = Catch->getLocStart();
Steve Naroff75730982007-11-07 04:08:17 +00001867 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001868
Steve Naroff75730982007-11-07 04:08:17 +00001869 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00001870
Steve Naroff75730982007-11-07 04:08:17 +00001871 const char *lParenLoc = strchr(startBuf, '(');
1872
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001873 if (Catch->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001874 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001875 lastCatchBody = Catch->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001876 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1877 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001878 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner06767512008-04-08 05:52:18 +00001879 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001880 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001881
Steve Naroffe12e6922008-02-01 20:02:07 +00001882 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00001883 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00001884 } else if (catchDecl) {
1885 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001886 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001887 buf += "1) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001888 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00001889 sawIdTypedCatch = true;
John McCall506b57e2010-05-17 21:00:27 +00001890 } else if (const ObjCObjectPointerType *Ptr =
1891 t->getAs<ObjCObjectPointerType>()) {
1892 // Should be a pointer to a class.
1893 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1894 if (IDecl) {
Steve Naroff21867b12007-11-07 18:43:40 +00001895 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall506b57e2010-05-17 21:00:27 +00001896 buf += IDecl->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001897 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001898 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00001899 }
1900 }
1901 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001902 lastCatchBody = Catch->getCatchBody();
1903 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroff75730982007-11-07 04:08:17 +00001904 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1905 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1906 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1907 assert((*rParenBuf == ')') && "bogus @catch paren location");
1908 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001909
Mike Stump1eb44332009-09-09 15:08:12 +00001910 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00001911 // declares the @catch parameter).
Benjamin Kramerd999b372010-02-14 14:14:16 +00001912 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff7ba138a2009-03-03 19:52:17 +00001913 } else {
Steve Naroff75730982007-11-07 04:08:17 +00001914 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001915 }
Steve Naroff75730982007-11-07 04:08:17 +00001916 }
1917 // Complete the catch list...
1918 if (lastCatchBody) {
1919 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001920 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1921 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001922
Steve Naroff378f47a2008-09-11 15:29:03 +00001923 // Insert the last (implicit) else clause *before* the right curly brace.
1924 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1925 buf = "} /* last catch end */\n";
1926 buf += "else {\n";
1927 buf += " _rethrow = _caught;\n";
1928 buf += " objc_exception_try_exit(&_stack);\n";
1929 buf += "} } /* @catch end */\n";
1930 if (!S->getFinallyStmt())
1931 buf += "}\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001932 InsertText(bodyLoc, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001933
Steve Naroff75730982007-11-07 04:08:17 +00001934 // Set lastCurlyLoc
1935 lastCurlyLoc = lastCatchBody->getLocEnd();
1936 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001937 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001938 startLoc = finalStmt->getLocStart();
1939 startBuf = SM->getCharacterData(startLoc);
1940 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00001941
Benjamin Kramerd999b372010-02-14 14:14:16 +00001942 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump1eb44332009-09-09 15:08:12 +00001943
Steve Naroff75730982007-11-07 04:08:17 +00001944 Stmt *body = finalStmt->getFinallyBody();
1945 SourceLocation startLoc = body->getLocStart();
1946 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001947 assert(*SM->getCharacterData(startLoc) == '{' &&
1948 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001949 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00001950 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001951
Steve Naroff75730982007-11-07 04:08:17 +00001952 startLoc = startLoc.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001953 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Steve Naroff75730982007-11-07 04:08:17 +00001954 endLoc = endLoc.getFileLocWithOffset(-1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001955 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump1eb44332009-09-09 15:08:12 +00001956
Steve Naroff75730982007-11-07 04:08:17 +00001957 // Set lastCurlyLoc
1958 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00001959
Steve Naroff8c565152008-12-05 17:03:39 +00001960 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00001961 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00001962 } else { /* no finally clause - make sure we synthesize an implicit one */
1963 buf = "{ /* implicit finally clause */\n";
1964 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1965 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1966 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001967 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001968
1969 // Now check for any return/continue/go statements within the @try.
1970 // The implicit finally clause won't called if the @try contains any
1971 // jump statements.
1972 bool hasReturns = false;
1973 HasReturnStmts(S->getTryBody(), hasReturns);
1974 if (hasReturns)
1975 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00001976 }
1977 // Now emit the final closing curly brace...
1978 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001979 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001980 return 0;
1981}
1982
Mike Stump1eb44332009-09-09 15:08:12 +00001983// This can't be done with ReplaceStmt(S, ThrowExpr), since
1984// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00001985// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001986Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001987 // Get the start location and compute the semi location.
1988 SourceLocation startLoc = S->getLocStart();
1989 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001990
Steve Naroff2bd03922007-11-07 15:32:26 +00001991 assert((*startBuf == '@') && "bogus @throw location");
1992
1993 std::string buf;
1994 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001995 if (S->getThrowExpr())
1996 buf = "objc_exception_throw(";
1997 else // add an implicit argument
1998 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00001999
Steve Naroff4ba0acb2008-07-25 15:41:30 +00002000 // handle "@ throw" correctly.
2001 const char *wBuf = strchr(startBuf, 'w');
2002 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramerd999b372010-02-14 14:14:16 +00002003 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002004
Steve Naroff2bd03922007-11-07 15:32:26 +00002005 const char *semiBuf = strchr(startBuf, ';');
2006 assert((*semiBuf == ';') && "@throw: can't find ';'");
2007 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002008 ReplaceText(semiLoc, 1, ");");
Steve Naroff2bd03922007-11-07 15:32:26 +00002009 return 0;
2010}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002011
Steve Naroffb29b4272008-04-14 22:03:09 +00002012Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00002013 // Create a new string expression.
2014 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002015 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002016 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattner2085fd62009-02-18 06:40:38 +00002017 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
2018 StrEncoding.length(), false,StrType,
2019 SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002020 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00002021
Chris Lattner07506182007-11-30 22:53:43 +00002022 // Replace this subexpr in the parent.
Steve Naroff4c3580e2008-12-04 23:50:32 +00002023 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00002024 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00002025}
2026
Steve Naroffb29b4272008-04-14 22:03:09 +00002027Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00002028 if (!SelGetUidFunctionDecl)
2029 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00002030 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2031 // Create a call to sel_registerName("selName").
2032 llvm::SmallVector<Expr*, 8> SelExprs;
2033 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002034 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002035 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00002036 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00002037 false, argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00002038 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2039 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002040 ReplaceStmt(Exp, SelExp);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002041 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00002042 return SelExp;
2043}
2044
Steve Naroffb29b4272008-04-14 22:03:09 +00002045CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002046 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2047 SourceLocation EndLoc) {
Steve Naroffebf2b562007-10-23 23:50:29 +00002048 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00002049 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002050
Steve Naroffebf2b562007-10-23 23:50:29 +00002051 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002052 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002053
Steve Naroffebf2b562007-10-23 23:50:29 +00002054 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00002055 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson88465d32010-04-23 22:18:37 +00002056 ImplicitCastExpr *ICE =
John McCall2de56d12010-08-25 11:45:40 +00002057 ImplicitCastExpr::Create(*Context, pToFunc, CK_Unknown,
John McCall5baba9d2010-08-25 10:28:54 +00002058 DRE, 0, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00002059
John McCall183700f2009-09-21 23:43:11 +00002060 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002061
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002062 CallExpr *Exp =
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002063 new (Context) CallExpr(*Context, ICE, args, nargs,
2064 FT->getCallResultType(*Context), EndLoc);
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002065 return Exp;
Steve Naroff934f2762007-10-24 22:48:43 +00002066}
2067
Steve Naroffd5255f52007-11-01 13:24:47 +00002068static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2069 const char *&startRef, const char *&endRef) {
2070 while (startBuf < endBuf) {
2071 if (*startBuf == '<')
2072 startRef = startBuf; // mark the start.
2073 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00002074 if (startRef && *startRef == '<') {
2075 endRef = startBuf; // mark the end.
2076 return true;
2077 }
2078 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002079 }
2080 startBuf++;
2081 }
2082 return false;
2083}
2084
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002085static void scanToNextArgument(const char *&argRef) {
2086 int angle = 0;
2087 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2088 if (*argRef == '<')
2089 angle++;
2090 else if (*argRef == '>')
2091 angle--;
2092 argRef++;
2093 }
2094 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2095}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002096
Steve Naroffb29b4272008-04-14 22:03:09 +00002097bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian32132a02010-02-03 21:29:28 +00002098 if (T->isObjCQualifiedIdType())
2099 return true;
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002100 if (const PointerType *PT = T->getAs<PointerType>()) {
2101 if (PT->getPointeeType()->isObjCQualifiedIdType())
2102 return true;
2103 }
2104 if (T->isObjCObjectPointerType()) {
2105 T = T->getPointeeType();
2106 return T->isObjCQualifiedInterfaceType();
2107 }
2108 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002109}
2110
Steve Naroff4f95b752008-07-29 18:15:38 +00002111void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2112 QualType Type = E->getType();
2113 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00002114 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00002115
Steve Naroffcda658e2008-11-19 21:15:47 +00002116 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2117 Loc = ECE->getLParenLoc();
2118 EndLoc = ECE->getRParenLoc();
2119 } else {
2120 Loc = E->getLocStart();
2121 EndLoc = E->getLocEnd();
2122 }
2123 // This will defend against trying to rewrite synthesized expressions.
2124 if (Loc.isInvalid() || EndLoc.isInvalid())
2125 return;
2126
Steve Naroff4f95b752008-07-29 18:15:38 +00002127 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00002128 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00002129 const char *startRef = 0, *endRef = 0;
2130 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2131 // Get the locations of the startRef, endRef.
2132 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2133 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2134 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002135 InsertText(LessLoc, "/*");
2136 InsertText(GreaterLoc, "*/");
Steve Naroff4f95b752008-07-29 18:15:38 +00002137 }
2138 }
2139}
2140
Steve Naroffb29b4272008-04-14 22:03:09 +00002141void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002142 SourceLocation Loc;
2143 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00002144 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002145 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2146 Loc = VD->getLocation();
2147 Type = VD->getType();
2148 }
2149 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2150 Loc = FD->getLocation();
2151 // Check for ObjC 'id' and class types that have been adorned with protocol
2152 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002153 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002154 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002155 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002156 if (!proto)
2157 return;
2158 Type = proto->getResultType();
2159 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002160 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2161 Loc = FD->getLocation();
2162 Type = FD->getType();
2163 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002164 else
2165 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002166
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002167 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002168 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002169
Steve Naroffd5255f52007-11-01 13:24:47 +00002170 const char *endBuf = SM->getCharacterData(Loc);
2171 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002172 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002173 startBuf--; // scan backward (from the decl location) for return type.
2174 const char *startRef = 0, *endRef = 0;
2175 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2176 // Get the locations of the startRef, endRef.
2177 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2178 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2179 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002180 InsertText(LessLoc, "/*");
2181 InsertText(GreaterLoc, "*/");
Steve Naroff9165ad32007-10-31 04:38:33 +00002182 }
2183 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002184 if (!proto)
2185 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002186 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002187 const char *startBuf = SM->getCharacterData(Loc);
2188 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00002189 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2190 if (needToScanForQualifiers(proto->getArgType(i))) {
2191 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002192
Steve Naroffd5255f52007-11-01 13:24:47 +00002193 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002194 // scan forward (from the decl location) for argument types.
2195 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00002196 const char *startRef = 0, *endRef = 0;
2197 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2198 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002199 SourceLocation LessLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002200 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002201 SourceLocation GreaterLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002202 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002203 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002204 InsertText(LessLoc, "/*");
2205 InsertText(GreaterLoc, "*/");
Steve Naroffd5255f52007-11-01 13:24:47 +00002206 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002207 startBuf = ++endBuf;
2208 }
2209 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002210 // If the function name is derived from a macro expansion, then the
2211 // argument buffer will not follow the name. Need to speak with Chris.
2212 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002213 startBuf++; // scan forward (from the decl location) for argument types.
2214 startBuf++;
2215 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002216 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002217}
2218
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002219void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2220 QualType QT = ND->getType();
2221 const Type* TypePtr = QT->getAs<Type>();
2222 if (!isa<TypeOfExprType>(TypePtr))
2223 return;
2224 while (isa<TypeOfExprType>(TypePtr)) {
2225 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2226 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2227 TypePtr = QT->getAs<Type>();
2228 }
2229 // FIXME. This will not work for multiple declarators; as in:
2230 // __typeof__(a) b,c,d;
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002231 std::string TypeAsString(QT.getAsString(Context->PrintingPolicy));
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002232 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2233 const char *startBuf = SM->getCharacterData(DeclLoc);
2234 if (ND->getInit()) {
2235 std::string Name(ND->getNameAsString());
2236 TypeAsString += " " + Name + " = ";
2237 Expr *E = ND->getInit();
2238 SourceLocation startLoc;
2239 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2240 startLoc = ECE->getLParenLoc();
2241 else
2242 startLoc = E->getLocStart();
2243 startLoc = SM->getInstantiationLoc(startLoc);
2244 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002245 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002246 }
2247 else {
2248 SourceLocation X = ND->getLocEnd();
2249 X = SM->getInstantiationLoc(X);
2250 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002251 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002252 }
2253}
2254
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002255// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002256void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002257 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2258 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002259 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002260 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002261 &ArgTys[0], ArgTys.size(),
2262 false /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002263 false, false, 0, 0,
2264 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002265 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002266 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002267 SelGetUidIdent, getFuncType, 0,
John McCalld931b082010-08-26 03:08:43 +00002268 SC_Extern,
2269 SC_None, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002270}
2271
Steve Naroffb29b4272008-04-14 22:03:09 +00002272void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002273 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002274 if (FD->getIdentifier() &&
Daniel Dunbar4087f272010-08-17 22:39:59 +00002275 FD->getName() == "sel_registerName") {
Steve Naroff09b266e2007-10-30 23:14:51 +00002276 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002277 return;
2278 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002279 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002280}
2281
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002282void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2283 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002284 const char *argPtr = TypeString.c_str();
2285 if (!strchr(argPtr, '^')) {
2286 Str += TypeString;
2287 return;
2288 }
2289 while (*argPtr) {
2290 Str += (*argPtr == '^' ? '*' : *argPtr);
2291 argPtr++;
2292 }
2293}
2294
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002295// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002296void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2297 ValueDecl *VD) {
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002298 QualType Type = VD->getType();
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002299 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002300 const char *argPtr = TypeString.c_str();
2301 int paren = 0;
2302 while (*argPtr) {
2303 switch (*argPtr) {
2304 case '(':
2305 Str += *argPtr;
2306 paren++;
2307 break;
2308 case ')':
2309 Str += *argPtr;
2310 paren--;
2311 break;
2312 case '^':
2313 Str += '*';
2314 if (paren == 1)
2315 Str += VD->getNameAsString();
2316 break;
2317 default:
2318 Str += *argPtr;
2319 break;
2320 }
2321 argPtr++;
2322 }
2323}
2324
2325
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002326void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2327 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2328 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2329 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2330 if (!proto)
2331 return;
2332 QualType Type = proto->getResultType();
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002333 std::string FdStr = Type.getAsString(Context->PrintingPolicy);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002334 FdStr += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00002335 FdStr += FD->getName();
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002336 FdStr += "(";
2337 unsigned numArgs = proto->getNumArgs();
2338 for (unsigned i = 0; i < numArgs; i++) {
2339 QualType ArgType = proto->getArgType(i);
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002340 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002341 if (i+1 < numArgs)
2342 FdStr += ", ";
2343 }
2344 FdStr += ");\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002345 InsertText(FunLocStart, FdStr);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002346 CurFunctionDeclToDeclareForBlock = 0;
2347}
2348
Steve Naroffc0a123c2008-03-11 17:37:02 +00002349// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002350void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002351 if (SuperContructorFunctionDecl)
2352 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002353 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroffc0a123c2008-03-11 17:37:02 +00002354 llvm::SmallVector<QualType, 16> ArgTys;
2355 QualType argT = Context->getObjCIdType();
2356 assert(!argT.isNull() && "Can't find 'id' type");
2357 ArgTys.push_back(argT);
2358 ArgTys.push_back(argT);
2359 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2360 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002361 false, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002362 false, false, 0, 0,
2363 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002364 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002365 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002366 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002367 SC_Extern,
2368 SC_None, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002369}
2370
Steve Naroff09b266e2007-10-30 23:14:51 +00002371// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002372void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002373 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2374 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002375 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002376 assert(!argT.isNull() && "Can't find 'id' type");
2377 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002378 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002379 assert(!argT.isNull() && "Can't find 'SEL' type");
2380 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002381 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002382 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002383 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002384 false, false, 0, 0,
2385 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002386 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002387 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002388 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002389 SC_Extern,
2390 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002391}
2392
Steve Naroff874e2322007-11-15 10:28:18 +00002393// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002394void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002395 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2396 llvm::SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002397 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002398 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002399 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002400 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2401 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2402 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002403 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002404 assert(!argT.isNull() && "Can't find 'SEL' type");
2405 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002406 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00002407 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002408 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002409 false, false, 0, 0,
2410 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002411 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002412 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002413 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002414 SC_Extern,
2415 SC_None, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002416}
2417
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002418// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002419void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002420 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2421 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002422 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002423 assert(!argT.isNull() && "Can't find 'id' type");
2424 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002425 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002426 assert(!argT.isNull() && "Can't find 'SEL' type");
2427 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002428 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002429 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002430 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002431 false, false, 0, 0,
2432 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002433 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002434 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002435 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002436 SC_Extern,
2437 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002438}
2439
Mike Stump1eb44332009-09-09 15:08:12 +00002440// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002441// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002442void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002443 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002444 &Context->Idents.get("objc_msgSendSuper_stret");
2445 llvm::SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002446 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002447 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002448 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002449 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2450 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2451 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002452 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002453 assert(!argT.isNull() && "Can't find 'SEL' type");
2454 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002455 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002456 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002457 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002458 false, false, 0, 0,
2459 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002460 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002461 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002462 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002463 SC_Extern,
2464 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002465}
2466
Steve Naroff1284db82008-05-08 22:02:18 +00002467// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002468void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002469 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2470 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002471 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002472 assert(!argT.isNull() && "Can't find 'id' type");
2473 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002474 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002475 assert(!argT.isNull() && "Can't find 'SEL' type");
2476 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00002477 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002478 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002479 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002480 false, false, 0, 0,
2481 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002482 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002483 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002484 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002485 SC_Extern,
2486 SC_None, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002487}
2488
Steve Naroff09b266e2007-10-30 23:14:51 +00002489// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002490void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002491 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2492 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002493 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002494 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002495 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002496 false /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002497 false, false, 0, 0,
2498 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002499 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002500 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002501 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002502 SC_Extern,
2503 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002504}
2505
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002506// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2507void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2508 IdentifierInfo *getSuperClassIdent =
2509 &Context->Idents.get("class_getSuperclass");
2510 llvm::SmallVector<QualType, 16> ArgTys;
2511 ArgTys.push_back(Context->getObjCClassType());
2512 QualType getClassType = Context->getFunctionType(Context->getObjCClassType(),
2513 &ArgTys[0], ArgTys.size(),
2514 false /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002515 false, false, 0, 0,
2516 FunctionType::ExtInfo());
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002517 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002518 SourceLocation(),
2519 getSuperClassIdent,
2520 getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002521 SC_Extern,
2522 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002523 false);
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002524}
2525
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002526// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002527void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002528 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2529 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002530 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002531 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002532 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002533 false /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002534 false, false, 0, 0,
2535 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002536 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002537 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002538 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002539 SC_Extern,
2540 SC_None, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002541}
2542
Steve Naroffb29b4272008-04-14 22:03:09 +00002543Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002544 QualType strType = getConstantStringStructType();
2545
2546 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002547
2548 std::string tmpName = InFileName;
2549 unsigned i;
2550 for (i=0; i < tmpName.length(); i++) {
2551 char c = tmpName.at(i);
2552 // replace any non alphanumeric characters with '_'.
2553 if (!isalpha(c) && (c < '0' || c > '9'))
2554 tmpName[i] = '_';
2555 }
2556 S += tmpName;
2557 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002558 S += utostr(NumObjCStringLiterals++);
2559
Steve Naroffba92b2e2008-03-27 22:29:16 +00002560 Preamble += "static __NSConstantStringImpl " + S;
2561 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2562 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002563 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002564 std::string prettyBufS;
2565 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00002566 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2567 PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002568 Preamble += prettyBuf.str();
2569 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002570 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002571
2572 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Benjamin Kramerd999b372010-02-14 14:14:16 +00002573 &Context->Idents.get(S), strType, 0,
John McCalld931b082010-08-26 03:08:43 +00002574 SC_Static, SC_None);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002575 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00002576 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002577 Context->getPointerType(DRE->getType()),
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002578 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002579 // cast to NSConstantString *
John McCall9d125032010-01-15 18:39:57 +00002580 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCall2de56d12010-08-25 11:45:40 +00002581 CK_Unknown, Unop);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002582 ReplaceStmt(Exp, cast);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002583 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002584 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002585}
2586
Steve Naroff874e2322007-11-15 10:28:18 +00002587// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002588QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002589 if (!SuperStructDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002590 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002591 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002592 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002593 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002594
Steve Naroff874e2322007-11-15 10:28:18 +00002595 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002596 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002597 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002598 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002599
Steve Naroff874e2322007-11-15 10:28:18 +00002600 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002601 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002602 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2603 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002604 FieldTypes[i], 0,
2605 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002606 /*Mutable=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002607 }
Mike Stump1eb44332009-09-09 15:08:12 +00002608
Douglas Gregor838db382010-02-11 01:19:42 +00002609 SuperStructDecl->completeDefinition();
Steve Naroff874e2322007-11-15 10:28:18 +00002610 }
2611 return Context->getTagDeclType(SuperStructDecl);
2612}
2613
Steve Naroffb29b4272008-04-14 22:03:09 +00002614QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002615 if (!ConstantStringDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002616 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002617 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002618 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002619 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002620
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002621 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002622 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002623 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002624 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002625 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002626 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002627 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002628 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002629
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002630 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002631 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002632 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2633 ConstantStringDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002634 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002635 FieldTypes[i], 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00002636 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002637 /*Mutable=*/true));
Douglas Gregor44b43212008-12-11 16:49:14 +00002638 }
2639
Douglas Gregor838db382010-02-11 01:19:42 +00002640 ConstantStringDecl->completeDefinition();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002641 }
2642 return Context->getTagDeclType(ConstantStringDecl);
2643}
2644
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002645Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2646 SourceLocation StartLoc,
2647 SourceLocation EndLoc) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002648 if (!SelGetUidFunctionDecl)
2649 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002650 if (!MsgSendFunctionDecl)
2651 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002652 if (!MsgSendSuperFunctionDecl)
2653 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002654 if (!MsgSendStretFunctionDecl)
2655 SynthMsgSendStretFunctionDecl();
2656 if (!MsgSendSuperStretFunctionDecl)
2657 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002658 if (!MsgSendFpretFunctionDecl)
2659 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002660 if (!GetClassFunctionDecl)
2661 SynthGetClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002662 if (!GetSuperClassFunctionDecl)
2663 SynthGetSuperClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002664 if (!GetMetaClassFunctionDecl)
2665 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002666
Steve Naroff874e2322007-11-15 10:28:18 +00002667 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002668 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2669 // May need to use objc_msgSend_stret() as well.
2670 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002671 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2672 QualType resultType = mDecl->getResultType();
Douglas Gregorfb87b892010-04-26 21:31:17 +00002673 if (resultType->isRecordType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002674 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002675 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002676 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002677 }
Mike Stump1eb44332009-09-09 15:08:12 +00002678
Steve Naroff934f2762007-10-24 22:48:43 +00002679 // Synthesize a call to objc_msgSend().
2680 llvm::SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002681 switch (Exp->getReceiverKind()) {
2682 case ObjCMessageExpr::SuperClass: {
2683 MsgSendFlavor = MsgSendSuperFunctionDecl;
2684 if (MsgSendStretFlavor)
2685 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2686 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002687
Douglas Gregor04badcf2010-04-21 00:45:42 +00002688 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00002689
Douglas Gregor04badcf2010-04-21 00:45:42 +00002690 llvm::SmallVector<Expr*, 4> InitExprs;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002691
Douglas Gregor04badcf2010-04-21 00:45:42 +00002692 // set the receiver to self, the first argument to all methods.
2693 InitExprs.push_back(
2694 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall2de56d12010-08-25 11:45:40 +00002695 CK_Unknown,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002696 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2697 Context->getObjCIdType(),
2698 SourceLocation()))
2699 ); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002700
Douglas Gregor04badcf2010-04-21 00:45:42 +00002701 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2702 llvm::SmallVector<Expr*, 8> ClsExprs;
2703 QualType argType = Context->getPointerType(Context->CharTy);
2704 ClsExprs.push_back(StringLiteral::Create(*Context,
2705 ClassDecl->getIdentifier()->getNameStart(),
2706 ClassDecl->getIdentifier()->getLength(),
2707 false, argType, SourceLocation()));
2708 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2709 &ClsExprs[0],
2710 ClsExprs.size(),
2711 StartLoc,
2712 EndLoc);
2713 // (Class)objc_getClass("CurrentClass")
2714 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2715 Context->getObjCClassType(),
John McCall2de56d12010-08-25 11:45:40 +00002716 CK_Unknown, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002717 ClsExprs.clear();
2718 ClsExprs.push_back(ArgExpr);
2719 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2720 &ClsExprs[0], ClsExprs.size(),
2721 StartLoc, EndLoc);
2722
2723 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2724 // To turn off a warning, type-cast to 'id'
2725 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2726 NoTypeInfoCStyleCastExpr(Context,
2727 Context->getObjCIdType(),
John McCall2de56d12010-08-25 11:45:40 +00002728 CK_Unknown, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002729 // struct objc_super
2730 QualType superType = getSuperStructType();
2731 Expr *SuperRep;
Steve Naroff621edce2009-04-29 16:37:50 +00002732
Douglas Gregor04badcf2010-04-21 00:45:42 +00002733 if (LangOpts.Microsoft) {
2734 SynthSuperContructorFunctionDecl();
2735 // Simulate a contructor call...
2736 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
2737 superType, SourceLocation());
2738 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2739 InitExprs.size(),
2740 superType, SourceLocation());
2741 // The code for super is a little tricky to prevent collision with
2742 // the structure definition in the header. The rewriter has it's own
2743 // internal definition (__rw_objc_super) that is uses. This is why
2744 // we need the cast below. For example:
2745 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2746 //
John McCall2de56d12010-08-25 11:45:40 +00002747 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002748 Context->getPointerType(SuperRep->getType()),
2749 SourceLocation());
2750 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2751 Context->getPointerType(superType),
John McCall2de56d12010-08-25 11:45:40 +00002752 CK_Unknown, SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002753 } else {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002754 // (struct objc_super) { <exprs from above> }
2755 InitListExpr *ILE =
2756 new (Context) InitListExpr(*Context, SourceLocation(),
2757 &InitExprs[0], InitExprs.size(),
2758 SourceLocation());
2759 TypeSourceInfo *superTInfo
2760 = Context->getTrivialTypeSourceInfo(superType);
2761 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2762 superType, ILE, false);
2763 // struct objc_super *
John McCall2de56d12010-08-25 11:45:40 +00002764 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002765 Context->getPointerType(SuperRep->getType()),
2766 SourceLocation());
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002767 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002768 MsgExprs.push_back(SuperRep);
2769 break;
Steve Naroff6568d4d2007-11-14 23:54:14 +00002770 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002771
2772 case ObjCMessageExpr::Class: {
2773 llvm::SmallVector<Expr*, 8> ClsExprs;
2774 QualType argType = Context->getPointerType(Context->CharTy);
2775 ObjCInterfaceDecl *Class
John McCall506b57e2010-05-17 21:00:27 +00002776 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00002777 IdentifierInfo *clsName = Class->getIdentifier();
2778 ClsExprs.push_back(StringLiteral::Create(*Context,
2779 clsName->getNameStart(),
2780 clsName->getLength(),
2781 false, argType,
2782 SourceLocation()));
2783 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2784 &ClsExprs[0],
2785 ClsExprs.size(),
2786 StartLoc, EndLoc);
2787 MsgExprs.push_back(Cls);
2788 break;
2789 }
2790
2791 case ObjCMessageExpr::SuperInstance:{
2792 MsgSendFlavor = MsgSendSuperFunctionDecl;
2793 if (MsgSendStretFlavor)
2794 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2795 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2796 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2797 llvm::SmallVector<Expr*, 4> InitExprs;
2798
2799 InitExprs.push_back(
2800 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall2de56d12010-08-25 11:45:40 +00002801 CK_Unknown,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002802 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2803 Context->getObjCIdType(),
2804 SourceLocation()))
2805 ); // set the 'receiver'.
2806
2807 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2808 llvm::SmallVector<Expr*, 8> ClsExprs;
2809 QualType argType = Context->getPointerType(Context->CharTy);
2810 ClsExprs.push_back(StringLiteral::Create(*Context,
2811 ClassDecl->getIdentifier()->getNameStart(),
2812 ClassDecl->getIdentifier()->getLength(),
2813 false, argType, SourceLocation()));
2814 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2815 &ClsExprs[0],
2816 ClsExprs.size(),
2817 StartLoc, EndLoc);
2818 // (Class)objc_getClass("CurrentClass")
2819 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2820 Context->getObjCClassType(),
John McCall2de56d12010-08-25 11:45:40 +00002821 CK_Unknown, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002822 ClsExprs.clear();
2823 ClsExprs.push_back(ArgExpr);
2824 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2825 &ClsExprs[0], ClsExprs.size(),
2826 StartLoc, EndLoc);
2827
2828 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2829 // To turn off a warning, type-cast to 'id'
2830 InitExprs.push_back(
2831 // set 'super class', using class_getSuperclass().
2832 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall2de56d12010-08-25 11:45:40 +00002833 CK_Unknown, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002834 // struct objc_super
2835 QualType superType = getSuperStructType();
2836 Expr *SuperRep;
2837
2838 if (LangOpts.Microsoft) {
2839 SynthSuperContructorFunctionDecl();
2840 // Simulate a contructor call...
2841 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
2842 superType, SourceLocation());
2843 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2844 InitExprs.size(),
2845 superType, SourceLocation());
2846 // The code for super is a little tricky to prevent collision with
2847 // the structure definition in the header. The rewriter has it's own
2848 // internal definition (__rw_objc_super) that is uses. This is why
2849 // we need the cast below. For example:
2850 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2851 //
John McCall2de56d12010-08-25 11:45:40 +00002852 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002853 Context->getPointerType(SuperRep->getType()),
2854 SourceLocation());
2855 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2856 Context->getPointerType(superType),
John McCall2de56d12010-08-25 11:45:40 +00002857 CK_Unknown, SuperRep);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002858 } else {
2859 // (struct objc_super) { <exprs from above> }
2860 InitListExpr *ILE =
2861 new (Context) InitListExpr(*Context, SourceLocation(),
2862 &InitExprs[0], InitExprs.size(),
2863 SourceLocation());
2864 TypeSourceInfo *superTInfo
2865 = Context->getTrivialTypeSourceInfo(superType);
2866 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2867 superType, ILE, false);
2868 }
2869 MsgExprs.push_back(SuperRep);
2870 break;
2871 }
2872
2873 case ObjCMessageExpr::Instance: {
2874 // Remove all type-casts because it may contain objc-style types; e.g.
2875 // Foo<Proto> *.
2876 Expr *recExpr = Exp->getInstanceReceiver();
2877 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2878 recExpr = CE->getSubExpr();
2879 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall2de56d12010-08-25 11:45:40 +00002880 CK_Unknown, recExpr);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002881 MsgExprs.push_back(recExpr);
2882 break;
2883 }
2884 }
2885
Steve Naroffbeaf2992007-11-03 11:27:19 +00002886 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002887 llvm::SmallVector<Expr*, 8> SelExprs;
2888 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002889 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002890 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00002891 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00002892 false, argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00002893 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002894 &SelExprs[0], SelExprs.size(),
2895 StartLoc,
2896 EndLoc);
Steve Naroff934f2762007-10-24 22:48:43 +00002897 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002898
Steve Naroff934f2762007-10-24 22:48:43 +00002899 // Now push any user supplied arguments.
2900 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002901 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002902 // Make all implicit casts explicit...ICE comes in handy:-)
2903 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2904 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002905 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002906 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002907 : ICE->getType();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00002908 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00002909 (void)convertBlockPointerToFunctionPointer(type);
John McCall2de56d12010-08-25 11:45:40 +00002910 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK_Unknown,
John McCall9d125032010-01-15 18:39:57 +00002911 userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002912 }
2913 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002914 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002915 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002916 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002917 userExpr = CE->getSubExpr();
John McCall9d125032010-01-15 18:39:57 +00002918 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall2de56d12010-08-25 11:45:40 +00002919 CK_Unknown, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002920 }
Mike Stump1eb44332009-09-09 15:08:12 +00002921 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002922 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00002923 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2924 // out the argument in the original expression (since we aren't deleting
2925 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2926 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00002927 }
Steve Naroffab972d32007-11-04 22:37:50 +00002928 // Generate the funky cast.
2929 CastExpr *cast;
2930 llvm::SmallVector<QualType, 8> ArgTypes;
2931 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00002932
Steve Naroffab972d32007-11-04 22:37:50 +00002933 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002934 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2935 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2936 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002937 ArgTypes.push_back(Context->getObjCIdType());
2938 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00002939 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002940 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00002941 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2942 E = OMD->param_end(); PI != E; ++PI) {
2943 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00002944 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00002945 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002946 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00002947 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff352336b2007-11-05 14:36:37 +00002948 ArgTypes.push_back(t);
2949 }
Chris Lattner89951a82009-02-20 18:43:26 +00002950 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2951 ? Context->getObjCIdType() : OMD->getResultType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00002952 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Naroffab972d32007-11-04 22:37:50 +00002953 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002954 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002955 }
2956 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002957 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002958
Steve Naroffab972d32007-11-04 22:37:50 +00002959 // Create a reference to the objc_msgSend() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002960 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002961 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002962
Mike Stump1eb44332009-09-09 15:08:12 +00002963 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00002964 // If we don't do this cast, we get the following bizarre warning/note:
2965 // xx.m:13: warning: function called through a non-compatible type
2966 // xx.m:13: note: if this code is reached, the program will abort
John McCall9d125032010-01-15 18:39:57 +00002967 cast = NoTypeInfoCStyleCastExpr(Context,
2968 Context->getPointerType(Context->VoidTy),
John McCall2de56d12010-08-25 11:45:40 +00002969 CK_Unknown, DRE);
Mike Stump1eb44332009-09-09 15:08:12 +00002970
Steve Naroffab972d32007-11-04 22:37:50 +00002971 // Now do the "normal" pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00002972 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002973 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002974 // If we don't have a method decl, force a variadic cast.
Douglas Gregorce056bc2010-02-21 22:15:06 +00002975 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002976 false, false, 0, 0,
2977 FunctionType::ExtInfo());
Steve Naroffab972d32007-11-04 22:37:50 +00002978 castType = Context->getPointerType(castType);
John McCall2de56d12010-08-25 11:45:40 +00002979 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_Unknown,
John McCall9d125032010-01-15 18:39:57 +00002980 cast);
Steve Naroffab972d32007-11-04 22:37:50 +00002981
2982 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002983 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump1eb44332009-09-09 15:08:12 +00002984
John McCall183700f2009-09-21 23:43:11 +00002985 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00002986 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002987 MsgExprs.size(),
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002988 FT->getResultType(), EndLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002989 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002990 if (MsgSendStretFlavor) {
2991 // We have the method which returns a struct/union. Must also generate
2992 // call to objc_msgSend_stret and hang both varieties on a conditional
2993 // expression which dictate which one to envoke depending on size of
2994 // method's return type.
Mike Stump1eb44332009-09-09 15:08:12 +00002995
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002996 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002997 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002998 SourceLocation());
2999 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall9d125032010-01-15 18:39:57 +00003000 cast = NoTypeInfoCStyleCastExpr(Context,
3001 Context->getPointerType(Context->VoidTy),
John McCall2de56d12010-08-25 11:45:40 +00003002 CK_Unknown, STDRE);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003003 // Now do the "normal" pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00003004 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00003005 &ArgTypes[0], ArgTypes.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00003006 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00003007 false, false, 0, 0,
3008 FunctionType::ExtInfo());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003009 castType = Context->getPointerType(castType);
John McCall2de56d12010-08-25 11:45:40 +00003010 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_Unknown,
John McCall9d125032010-01-15 18:39:57 +00003011 cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003012
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003013 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003014 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003015
John McCall183700f2009-09-21 23:43:11 +00003016 FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003017 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003018 MsgExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00003019 FT->getResultType(), SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00003020
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003021 // Build sizeof(returnType)
Mike Stump1eb44332009-09-09 15:08:12 +00003022 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCalla93c9342009-12-07 02:54:59 +00003023 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl05189992008-11-11 17:56:53 +00003024 Context->getSizeType(),
3025 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003026 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3027 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3028 // For X86 it is more complicated and some kind of target specific routine
3029 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00003030 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00003031 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00003032 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3033 llvm::APInt(IntSize, 8),
3034 Context->IntTy,
3035 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00003036 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
John McCall2de56d12010-08-25 11:45:40 +00003037 BO_LE,
Mike Stump1eb44332009-09-09 15:08:12 +00003038 Context->IntTy,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003039 SourceLocation());
3040 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00003041 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003042 new (Context) ConditionalOperator(lessThanExpr,
3043 SourceLocation(), CE,
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003044 SourceLocation(), STCE, (Expr*)0,
3045 returnType);
3046 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3047 CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003048 }
Mike Stump1eb44332009-09-09 15:08:12 +00003049 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003050 return ReplacingStmt;
3051}
3052
Steve Naroffb29b4272008-04-14 22:03:09 +00003053Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003054 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3055 Exp->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00003056
Steve Naroff934f2762007-10-24 22:48:43 +00003057 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00003058 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00003059
3060 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003061 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00003062}
3063
Steve Naroff621edce2009-04-29 16:37:50 +00003064// typedef struct objc_object Protocol;
3065QualType RewriteObjC::getProtocolType() {
3066 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00003067 TypeSourceInfo *TInfo
3068 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00003069 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00003070 SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00003071 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00003072 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00003073 }
3074 return Context->getTypeDeclType(ProtocolTypeDecl);
3075}
3076
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003077/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00003078/// a synthesized/forward data reference (to the protocol's metadata).
3079/// The forward references (and metadata) are generated in
3080/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00003081Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00003082 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3083 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00003084 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00003085 ID, getProtocolType(), 0,
John McCalld931b082010-08-26 03:08:43 +00003086 SC_Extern, SC_None);
Steve Naroff621edce2009-04-29 16:37:50 +00003087 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00003088 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroff621edce2009-04-29 16:37:50 +00003089 Context->getPointerType(DRE->getType()),
3090 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00003091 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCall2de56d12010-08-25 11:45:40 +00003092 CK_Unknown,
John McCall9d125032010-01-15 18:39:57 +00003093 DerefExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003094 ReplaceStmt(Exp, castExpr);
3095 ProtocolExprDecls.insert(Exp->getProtocol());
Mike Stump1eb44332009-09-09 15:08:12 +00003096 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003097 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003098
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003099}
3100
Mike Stump1eb44332009-09-09 15:08:12 +00003101bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00003102 const char *endBuf) {
3103 while (startBuf < endBuf) {
3104 if (*startBuf == '#') {
3105 // Skip whitespace.
3106 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3107 ;
3108 if (!strncmp(startBuf, "if", strlen("if")) ||
3109 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3110 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3111 !strncmp(startBuf, "define", strlen("define")) ||
3112 !strncmp(startBuf, "undef", strlen("undef")) ||
3113 !strncmp(startBuf, "else", strlen("else")) ||
3114 !strncmp(startBuf, "elif", strlen("elif")) ||
3115 !strncmp(startBuf, "endif", strlen("endif")) ||
3116 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3117 !strncmp(startBuf, "include", strlen("include")) ||
3118 !strncmp(startBuf, "import", strlen("import")) ||
3119 !strncmp(startBuf, "include_next", strlen("include_next")))
3120 return true;
3121 }
3122 startBuf++;
3123 }
3124 return false;
3125}
3126
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003127/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003128/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00003129void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003130 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003131 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar4087f272010-08-17 22:39:59 +00003132 assert(CDecl->getName() != "" &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003133 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003134 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003135 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003136 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003137 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003138 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00003139 SourceLocation LocStart = CDecl->getLocStart();
3140 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00003141
Steve Narofffea763e82007-11-14 19:25:57 +00003142 const char *startBuf = SM->getCharacterData(LocStart);
3143 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00003144
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003145 // If no ivars and no root or if its root, directly or indirectly,
3146 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003147 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
3148 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00003149 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003150 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003151 return;
3152 }
Mike Stump1eb44332009-09-09 15:08:12 +00003153
3154 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003155 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003156 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003157 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00003158 if (LangOpts.Microsoft)
3159 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00003160
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003161 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00003162 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00003163 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003164 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00003165 // If the buffer contains preprocessor directives, we do more fine-grained
3166 // rewrites. This is intended to fix code that looks like (which occurs in
3167 // NSURL.h, for example):
3168 //
3169 // #ifdef XYZ
3170 // @interface Foo : NSObject
3171 // #else
3172 // @interface FooBar : NSObject
3173 // #endif
3174 // {
3175 // int i;
3176 // }
3177 // @end
3178 //
3179 // This clause is segregated to avoid breaking the common case.
3180 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003181 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffbaf58c32008-05-31 14:15:04 +00003182 CDecl->getClassLoc();
3183 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00003184 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003185
Chris Lattnercafeb352009-02-20 18:18:36 +00003186 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00003187 // advance to the end of the referenced protocols.
3188 while (endHeader < cursor && *endHeader != '>') endHeader++;
3189 endHeader++;
3190 }
3191 // rewrite the original header
Benjamin Kramerd999b372010-02-14 14:14:16 +00003192 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003193 } else {
3194 // rewrite the original header *without* disturbing the '{'
Benjamin Kramerd999b372010-02-14 14:14:16 +00003195 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003196 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003197 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00003198 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003199 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003200 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003201 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003202 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003203
Steve Narofffea763e82007-11-14 19:25:57 +00003204 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00003205 SourceLocation OnePastCurly =
3206 LocStart.getFileLocWithOffset(cursor-startBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003207 InsertText(OnePastCurly, Result);
Steve Narofffea763e82007-11-14 19:25:57 +00003208 }
3209 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00003210
Steve Narofffea763e82007-11-14 19:25:57 +00003211 // Now comment out any visibility specifiers.
3212 while (cursor < endBuf) {
3213 if (*cursor == '@') {
3214 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00003215 // Skip whitespace.
3216 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3217 /*scan*/;
3218
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003219 // FIXME: presence of @public, etc. inside comment results in
3220 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00003221 if (!strncmp(cursor, "public", strlen("public")) ||
3222 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00003223 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00003224 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramerd999b372010-02-14 14:14:16 +00003225 InsertText(atLoc, "// ");
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003226 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00003227 // FIXME: If there are cases where '<' is used in ivar declaration part
3228 // of user code, then scan the ivar list and use needToScanForQualifiers
3229 // for type checking.
3230 else if (*cursor == '<') {
3231 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003232 InsertText(atLoc, "/* ");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003233 cursor = strchr(cursor, '>');
3234 cursor++;
3235 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003236 InsertText(atLoc, " */");
Steve Naroffced80a82008-10-30 12:09:33 +00003237 } else if (*cursor == '^') { // rewrite block specifier.
3238 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003239 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003240 }
Steve Narofffea763e82007-11-14 19:25:57 +00003241 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003242 }
Steve Narofffea763e82007-11-14 19:25:57 +00003243 // Don't forget to add a ';'!!
Benjamin Kramerd999b372010-02-14 14:14:16 +00003244 InsertText(LocEnd.getFileLocWithOffset(1), ";");
Steve Narofffea763e82007-11-14 19:25:57 +00003245 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00003246 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00003247 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003248 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003249 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003250 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003251 Result += "_IVARS;\n};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00003252 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003253 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003254 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003255 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00003256 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003257}
3258
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003259// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003260/// class methods.
Douglas Gregor653f1b12009-04-23 01:02:12 +00003261template<typename MethodIterator>
3262void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3263 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00003264 bool IsInstanceMethod,
Daniel Dunbar4087f272010-08-17 22:39:59 +00003265 llvm::StringRef prefix,
3266 llvm::StringRef ClassName,
Chris Lattner158ecb92007-10-25 17:07:24 +00003267 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003268 if (MethodBegin == MethodEnd) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003269
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003270 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003271 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003272 SEL _cmd;
3273 char *method_types;
3274 void *_imp;
3275 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003276 */
Chris Lattner158ecb92007-10-25 17:07:24 +00003277 Result += "\nstruct _objc_method {\n";
3278 Result += "\tSEL _cmd;\n";
3279 Result += "\tchar *method_types;\n";
3280 Result += "\tvoid *_imp;\n";
3281 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003282
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003283 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00003284 }
Mike Stump1eb44332009-09-09 15:08:12 +00003285
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003286 // Build _objc_method_list for class's methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003287
Steve Naroff946a6932008-03-11 00:12:29 +00003288 /* struct {
3289 struct _objc_method_list *next_method;
3290 int method_count;
3291 struct _objc_method method_list[];
3292 }
3293 */
Douglas Gregor653f1b12009-04-23 01:02:12 +00003294 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroff946a6932008-03-11 00:12:29 +00003295 Result += "\nstatic struct {\n";
3296 Result += "\tstruct _objc_method_list *next_method;\n";
3297 Result += "\tint method_count;\n";
3298 Result += "\tstruct _objc_method method_list[";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003299 Result += utostr(NumMethods);
Steve Naroff946a6932008-03-11 00:12:29 +00003300 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003301 Result += prefix;
3302 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3303 Result += "_METHODS_";
3304 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003305 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003306 Result += IsInstanceMethod ? "inst" : "cls";
3307 Result += "_meth\")))= ";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003308 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003309
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003310 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003311 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003312 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003313 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003314 Result += "\", \"";
3315 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003316 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003317 Result += MethodInternalNames[*MethodBegin];
3318 Result += "}\n";
3319 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3320 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003321 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003322 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003323 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003324 Result += "\", \"";
3325 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003326 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003327 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00003328 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003329 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003330 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003331}
3332
Steve Naroff621edce2009-04-29 16:37:50 +00003333/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00003334void RewriteObjC::
Daniel Dunbar4087f272010-08-17 22:39:59 +00003335RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, llvm::StringRef prefix,
3336 llvm::StringRef ClassName, std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003337 static bool objc_protocol_methods = false;
Steve Naroff621edce2009-04-29 16:37:50 +00003338
3339 // Output struct protocol_methods holder of method selector and type.
3340 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3341 /* struct protocol_methods {
3342 SEL _cmd;
3343 char *method_types;
3344 }
3345 */
3346 Result += "\nstruct _protocol_methods {\n";
3347 Result += "\tstruct objc_selector *_cmd;\n";
3348 Result += "\tchar *method_types;\n";
3349 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003350
Steve Naroff621edce2009-04-29 16:37:50 +00003351 objc_protocol_methods = true;
3352 }
3353 // Do not synthesize the protocol more than once.
3354 if (ObjCSynthesizedProtocols.count(PDecl))
3355 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003356
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003357 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3358 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3359 PDecl->instmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003360 /* struct _objc_protocol_method_list {
3361 int protocol_method_count;
3362 struct protocol_methods protocols[];
3363 }
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003364 */
Steve Naroff621edce2009-04-29 16:37:50 +00003365 Result += "\nstatic struct {\n";
3366 Result += "\tint protocol_method_count;\n";
3367 Result += "\tstruct _protocol_methods protocol_methods[";
3368 Result += utostr(NumMethods);
3369 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3370 Result += PDecl->getNameAsString();
3371 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3372 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003373
Steve Naroff621edce2009-04-29 16:37:50 +00003374 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003375 for (ObjCProtocolDecl::instmeth_iterator
3376 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003377 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003378 if (I == PDecl->instmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003379 Result += "\t ,{{(struct objc_selector *)\"";
3380 else
3381 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar4087f272010-08-17 22:39:59 +00003382 Result += (*I)->getSelector().getAsString();
Steve Naroff621edce2009-04-29 16:37:50 +00003383 std::string MethodTypeString;
3384 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3385 Result += "\", \"";
3386 Result += MethodTypeString;
3387 Result += "\"}\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003388 }
Steve Naroff621edce2009-04-29 16:37:50 +00003389 Result += "\t }\n};\n";
3390 }
Mike Stump1eb44332009-09-09 15:08:12 +00003391
Steve Naroff621edce2009-04-29 16:37:50 +00003392 // Output class methods declared in this protocol.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003393 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3394 PDecl->classmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003395 if (NumMethods > 0) {
3396 /* struct _objc_protocol_method_list {
3397 int protocol_method_count;
3398 struct protocol_methods protocols[];
3399 }
3400 */
3401 Result += "\nstatic struct {\n";
3402 Result += "\tint protocol_method_count;\n";
3403 Result += "\tstruct _protocol_methods protocol_methods[";
3404 Result += utostr(NumMethods);
3405 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3406 Result += PDecl->getNameAsString();
3407 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3408 "{\n\t";
3409 Result += utostr(NumMethods);
3410 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003411
Steve Naroff621edce2009-04-29 16:37:50 +00003412 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003413 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003414 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003415 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003416 if (I == PDecl->classmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003417 Result += "\t ,{{(struct objc_selector *)\"";
3418 else
3419 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar4087f272010-08-17 22:39:59 +00003420 Result += (*I)->getSelector().getAsString();
Steve Naroff621edce2009-04-29 16:37:50 +00003421 std::string MethodTypeString;
3422 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3423 Result += "\", \"";
3424 Result += MethodTypeString;
3425 Result += "\"}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003426 }
Steve Naroff621edce2009-04-29 16:37:50 +00003427 Result += "\t }\n};\n";
3428 }
3429
3430 // Output:
3431 /* struct _objc_protocol {
3432 // Objective-C 1.0 extensions
3433 struct _objc_protocol_extension *isa;
3434 char *protocol_name;
3435 struct _objc_protocol **protocol_list;
3436 struct _objc_protocol_method_list *instance_methods;
3437 struct _objc_protocol_method_list *class_methods;
Mike Stump1eb44332009-09-09 15:08:12 +00003438 };
Steve Naroff621edce2009-04-29 16:37:50 +00003439 */
3440 static bool objc_protocol = false;
3441 if (!objc_protocol) {
3442 Result += "\nstruct _objc_protocol {\n";
3443 Result += "\tstruct _objc_protocol_extension *isa;\n";
3444 Result += "\tchar *protocol_name;\n";
3445 Result += "\tstruct _objc_protocol **protocol_list;\n";
3446 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3447 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003448 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003449
Steve Naroff621edce2009-04-29 16:37:50 +00003450 objc_protocol = true;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003451 }
Mike Stump1eb44332009-09-09 15:08:12 +00003452
Steve Naroff621edce2009-04-29 16:37:50 +00003453 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3454 Result += PDecl->getNameAsString();
3455 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3456 "{\n\t0, \"";
3457 Result += PDecl->getNameAsString();
3458 Result += "\", 0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003459 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003460 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3461 Result += PDecl->getNameAsString();
3462 Result += ", ";
3463 }
3464 else
3465 Result += "0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003466 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003467 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3468 Result += PDecl->getNameAsString();
3469 Result += "\n";
3470 }
3471 else
3472 Result += "0\n";
3473 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003474
Steve Naroff621edce2009-04-29 16:37:50 +00003475 // Mark this protocol as having been generated.
3476 if (!ObjCSynthesizedProtocols.insert(PDecl))
3477 assert(false && "protocol already synthesized");
3478
3479}
3480
3481void RewriteObjC::
3482RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
Daniel Dunbar4087f272010-08-17 22:39:59 +00003483 llvm::StringRef prefix, llvm::StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +00003484 std::string &Result) {
3485 if (Protocols.empty()) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003486
Steve Naroff621edce2009-04-29 16:37:50 +00003487 for (unsigned i = 0; i != Protocols.size(); i++)
3488 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3489
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003490 // Output the top lovel protocol meta-data for the class.
3491 /* struct _objc_protocol_list {
3492 struct _objc_protocol_list *next;
3493 int protocol_count;
3494 struct _objc_protocol *class_protocols[];
3495 }
3496 */
3497 Result += "\nstatic struct {\n";
3498 Result += "\tstruct _objc_protocol_list *next;\n";
3499 Result += "\tint protocol_count;\n";
3500 Result += "\tstruct _objc_protocol *class_protocols[";
3501 Result += utostr(Protocols.size());
3502 Result += "];\n} _OBJC_";
3503 Result += prefix;
3504 Result += "_PROTOCOLS_";
3505 Result += ClassName;
3506 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3507 "{\n\t0, ";
3508 Result += utostr(Protocols.size());
3509 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003510
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003511 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003512 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003513 Result += " \n";
Mike Stump1eb44332009-09-09 15:08:12 +00003514
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003515 for (unsigned i = 1; i != Protocols.size(); i++) {
3516 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003517 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003518 Result += "\n";
3519 }
3520 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003521}
3522
Steve Naroff621edce2009-04-29 16:37:50 +00003523
Mike Stump1eb44332009-09-09 15:08:12 +00003524/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003525/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003526void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003527 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003528 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003529 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003530 ObjCCategoryDecl *CDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00003531 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003532 CDecl = CDecl->getNextClassCategory())
3533 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3534 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003535
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003536 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003537 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003538 FullCategoryName += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003539
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003540 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003541 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003542 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003543
3544 // If any of our property implementations have associated getters or
3545 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003546 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3547 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003548 Prop != PropEnd; ++Prop) {
3549 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3550 continue;
3551 if (!(*Prop)->getPropertyIvarDecl())
3552 continue;
3553 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3554 if (!PD)
3555 continue;
3556 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3557 InstanceMethods.push_back(Getter);
3558 if (PD->isReadOnly())
3559 continue;
3560 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3561 InstanceMethods.push_back(Setter);
3562 }
3563 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003564 true, "CATEGORY_", FullCategoryName.c_str(),
3565 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003566
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003567 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003568 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003569 false, "CATEGORY_", FullCategoryName.c_str(),
3570 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003571
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003572 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003573 // Null CDecl is case of a category implementation with no category interface
3574 if (CDecl)
Steve Naroff621edce2009-04-29 16:37:50 +00003575 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Daniel Dunbar4087f272010-08-17 22:39:59 +00003576 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003577 /* struct _objc_category {
3578 char *category_name;
3579 char *class_name;
3580 struct _objc_method_list *instance_methods;
3581 struct _objc_method_list *class_methods;
3582 struct _objc_protocol_list *protocols;
3583 // Objective-C 1.0 extensions
3584 uint32_t size; // sizeof (struct _objc_category)
Mike Stump1eb44332009-09-09 15:08:12 +00003585 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003586 // @property decl.
Mike Stump1eb44332009-09-09 15:08:12 +00003587 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003588 */
Mike Stump1eb44332009-09-09 15:08:12 +00003589
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003590 static bool objc_category = false;
3591 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003592 Result += "\nstruct _objc_category {\n";
3593 Result += "\tchar *category_name;\n";
3594 Result += "\tchar *class_name;\n";
3595 Result += "\tstruct _objc_method_list *instance_methods;\n";
3596 Result += "\tstruct _objc_method_list *class_methods;\n";
3597 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003598 Result += "\tunsigned int size;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003599 Result += "\tstruct _objc_property_list *instance_properties;\n";
3600 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003601 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003602 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003603 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3604 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003605 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003606 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003607 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003608 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003609 Result += "\"\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003610
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003611 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003612 Result += "\t, (struct _objc_method_list *)"
3613 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3614 Result += FullCategoryName;
3615 Result += "\n";
3616 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003617 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003618 Result += "\t, 0\n";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003619 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003620 Result += "\t, (struct _objc_method_list *)"
3621 "&_OBJC_CATEGORY_CLASS_METHODS_";
3622 Result += FullCategoryName;
3623 Result += "\n";
3624 }
3625 else
3626 Result += "\t, 0\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003627
Chris Lattnercafeb352009-02-20 18:18:36 +00003628 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003629 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003630 Result += FullCategoryName;
3631 Result += "\n";
3632 }
3633 else
3634 Result += "\t, 0\n";
3635 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003636}
3637
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003638/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3639/// ivar offset.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00003640void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCContainerDecl *IDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00003641 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003642 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003643 if (ivar->isBitField()) {
3644 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3645 // place all bitfields at offset 0.
3646 Result += "0";
3647 } else {
3648 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003649 Result += IDecl->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003650 if (LangOpts.Microsoft)
3651 Result += "_IMPL";
3652 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003653 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003654 Result += ")";
3655 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003656}
3657
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003658//===----------------------------------------------------------------------===//
3659// Meta Data Emission
3660//===----------------------------------------------------------------------===//
3661
Steve Naroffb29b4272008-04-14 22:03:09 +00003662void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003663 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003664 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00003665
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003666 // Explictly declared @interface's are already synthesized.
Steve Naroff33feeb02009-04-20 20:09:33 +00003667 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003668 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003669 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003670 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003671 }
Mike Stump1eb44332009-09-09 15:08:12 +00003672
Chris Lattnerbe6df082007-12-12 07:56:42 +00003673 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003674 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump1eb44332009-09-09 15:08:12 +00003675 ? IDecl->ivar_size()
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003676 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003677 if (NumIvars > 0) {
3678 static bool objc_ivar = false;
3679 if (!objc_ivar) {
3680 /* struct _objc_ivar {
3681 char *ivar_name;
3682 char *ivar_type;
3683 int ivar_offset;
Mike Stump1eb44332009-09-09 15:08:12 +00003684 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003685 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003686 Result += "\nstruct _objc_ivar {\n";
3687 Result += "\tchar *ivar_name;\n";
3688 Result += "\tchar *ivar_type;\n";
3689 Result += "\tint ivar_offset;\n";
3690 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003691
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003692 objc_ivar = true;
3693 }
3694
Steve Naroff946a6932008-03-11 00:12:29 +00003695 /* struct {
3696 int ivar_count;
3697 struct _objc_ivar ivar_list[nIvars];
Mike Stump1eb44332009-09-09 15:08:12 +00003698 };
Steve Naroff946a6932008-03-11 00:12:29 +00003699 */
Mike Stump1eb44332009-09-09 15:08:12 +00003700 Result += "\nstatic struct {\n";
Steve Naroff946a6932008-03-11 00:12:29 +00003701 Result += "\tint ivar_count;\n";
3702 Result += "\tstruct _objc_ivar ivar_list[";
3703 Result += utostr(NumIvars);
3704 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003705 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003706 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003707 "{\n\t";
3708 Result += utostr(NumIvars);
3709 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003710
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003711 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003712 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003713 if (!IDecl->ivar_empty()) {
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003714 for (ObjCInterfaceDecl::ivar_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003715 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003716 IV != IVEnd; ++IV)
3717 IVars.push_back(*IV);
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003718 IVI = IDecl->ivar_begin();
3719 IVE = IDecl->ivar_end();
Chris Lattnerbe6df082007-12-12 07:56:42 +00003720 } else {
3721 IVI = CDecl->ivar_begin();
3722 IVE = CDecl->ivar_end();
3723 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003724 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003725 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003726 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003727 std::string TmpString, StrEncoding;
3728 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3729 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003730 Result += StrEncoding;
3731 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003732 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003733 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003734 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003735 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003736 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003737 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003738 std::string TmpString, StrEncoding;
3739 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3740 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003741 Result += StrEncoding;
3742 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003743 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003744 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003745 }
Mike Stump1eb44332009-09-09 15:08:12 +00003746
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003747 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003748 }
Mike Stump1eb44332009-09-09 15:08:12 +00003749
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003750 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003751 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003752 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003753
3754 // If any of our property implementations have associated getters or
3755 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003756 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3757 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003758 Prop != PropEnd; ++Prop) {
3759 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3760 continue;
3761 if (!(*Prop)->getPropertyIvarDecl())
3762 continue;
3763 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3764 if (!PD)
3765 continue;
3766 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3767 InstanceMethods.push_back(Getter);
3768 if (PD->isReadOnly())
3769 continue;
3770 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3771 InstanceMethods.push_back(Setter);
3772 }
3773 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003774 true, "", IDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003775
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003776 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003777 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003778 false, "", IDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003779
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003780 // Protocols referenced in class declaration?
Steve Naroff621edce2009-04-29 16:37:50 +00003781 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003782 "CLASS", CDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003783
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003784 // Declaration of class/meta-class metadata
3785 /* struct _objc_class {
3786 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003787 const char *super_class_name;
3788 char *name;
3789 long version;
3790 long info;
3791 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003792 struct _objc_ivar_list *ivars;
3793 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003794 struct objc_cache *cache;
3795 struct objc_protocol_list *protocols;
3796 const char *ivar_layout;
3797 struct _objc_class_ext *ext;
Mike Stump1eb44332009-09-09 15:08:12 +00003798 };
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003799 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003800 static bool objc_class = false;
3801 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003802 Result += "\nstruct _objc_class {\n";
3803 Result += "\tstruct _objc_class *isa;\n";
3804 Result += "\tconst char *super_class_name;\n";
3805 Result += "\tchar *name;\n";
3806 Result += "\tlong version;\n";
3807 Result += "\tlong info;\n";
3808 Result += "\tlong instance_size;\n";
3809 Result += "\tstruct _objc_ivar_list *ivars;\n";
3810 Result += "\tstruct _objc_method_list *methods;\n";
3811 Result += "\tstruct objc_cache *cache;\n";
3812 Result += "\tstruct _objc_protocol_list *protocols;\n";
3813 Result += "\tconst char *ivar_layout;\n";
3814 Result += "\tstruct _objc_class_ext *ext;\n";
3815 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003816 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003817 }
Mike Stump1eb44332009-09-09 15:08:12 +00003818
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003819 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003820 ObjCInterfaceDecl *RootClass = 0;
3821 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003822 while (SuperClass) {
3823 RootClass = SuperClass;
3824 SuperClass = SuperClass->getSuperClass();
3825 }
3826 SuperClass = CDecl->getSuperClass();
Mike Stump1eb44332009-09-09 15:08:12 +00003827
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003828 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003829 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003830 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003831 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003832 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003833 Result += "\"";
3834
3835 if (SuperClass) {
3836 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003837 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003838 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003839 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003840 Result += "\"";
3841 }
3842 else {
3843 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003844 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003845 Result += "\"";
3846 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003847 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003848 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003849 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003850 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff23f41272008-03-11 18:14:26 +00003851 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003852 Result += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003853 Result += "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003854 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003855 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003856 Result += ", 0\n";
Chris Lattnercafeb352009-02-20 18:18:36 +00003857 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003858 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003859 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003860 Result += ",0,0\n";
3861 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003862 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003863 Result += "\t,0,0,0,0\n";
3864 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003865
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003866 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003867 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003868 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003869 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003870 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003871 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003872 if (SuperClass) {
3873 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003874 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003875 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003876 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003877 Result += "\"";
3878 }
3879 else {
3880 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003881 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003882 Result += "\"";
3883 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003884 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003885 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003886 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003887 Result += ",0";
3888 else {
3889 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003890 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003891 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003892 if (LangOpts.Microsoft)
3893 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003894 Result += ")";
3895 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003896 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003897 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003898 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003899 Result += "\n\t";
3900 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003901 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003902 Result += ",0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003903 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroff946a6932008-03-11 00:12:29 +00003904 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003905 Result += CDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003906 Result += ", 0\n\t";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003907 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003908 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003909 Result += ",0,0";
Chris Lattnercafeb352009-02-20 18:18:36 +00003910 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003911 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003912 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003913 Result += ", 0,0\n";
3914 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003915 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003916 Result += ",0,0,0\n";
3917 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003918}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003919
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003920/// RewriteImplementations - This routine rewrites all method implementations
3921/// and emits meta-data.
3922
Steve Narofface66252008-11-13 20:07:04 +00003923void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003924 int ClsDefCount = ClassImplementation.size();
3925 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00003926
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003927 // Rewrite implemented methods
3928 for (int i = 0; i < ClsDefCount; i++)
3929 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00003930
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003931 for (int i = 0; i < CatDefCount; i++)
3932 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003933}
Mike Stump1eb44332009-09-09 15:08:12 +00003934
Steve Narofface66252008-11-13 20:07:04 +00003935void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3936 int ClsDefCount = ClassImplementation.size();
3937 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00003938
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003939 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003940 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003941 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003942
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003943 // For each implemented category, write out all its meta data.
3944 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003945 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroff621edce2009-04-29 16:37:50 +00003946
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003947 // Write objc_symtab metadata
3948 /*
3949 struct _objc_symtab
3950 {
3951 long sel_ref_cnt;
3952 SEL *refs;
3953 short cls_def_cnt;
3954 short cat_def_cnt;
3955 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump1eb44332009-09-09 15:08:12 +00003956 };
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003957 */
Mike Stump1eb44332009-09-09 15:08:12 +00003958
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003959 Result += "\nstruct _objc_symtab {\n";
3960 Result += "\tlong sel_ref_cnt;\n";
3961 Result += "\tSEL *refs;\n";
3962 Result += "\tshort cls_def_cnt;\n";
3963 Result += "\tshort cat_def_cnt;\n";
3964 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3965 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003966
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003967 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003968 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003969 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003970 + ", " + utostr(CatDefCount) + "\n";
3971 for (int i = 0; i < ClsDefCount; i++) {
3972 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003973 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003974 Result += "\n";
3975 }
Mike Stump1eb44332009-09-09 15:08:12 +00003976
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003977 for (int i = 0; i < CatDefCount; i++) {
3978 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003979 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003980 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003981 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003982 Result += "\n";
3983 }
Mike Stump1eb44332009-09-09 15:08:12 +00003984
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003985 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003986
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003987 // Write objc_module metadata
Mike Stump1eb44332009-09-09 15:08:12 +00003988
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003989 /*
3990 struct _objc_module {
3991 long version;
3992 long size;
3993 const char *name;
3994 struct _objc_symtab *symtab;
3995 }
3996 */
Mike Stump1eb44332009-09-09 15:08:12 +00003997
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003998 Result += "\nstruct _objc_module {\n";
3999 Result += "\tlong version;\n";
4000 Result += "\tlong size;\n";
4001 Result += "\tconst char *name;\n";
4002 Result += "\tstruct _objc_symtab *symtab;\n";
4003 Result += "};\n\n";
4004 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00004005 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004006 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00004007 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004008 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004009
4010 if (LangOpts.Microsoft) {
Steve Naroff621edce2009-04-29 16:37:50 +00004011 if (ProtocolExprDecls.size()) {
4012 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
4013 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004014 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00004015 E = ProtocolExprDecls.end(); I != E; ++I) {
4016 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
4017 Result += (*I)->getNameAsString();
4018 Result += " = &_OBJC_PROTOCOL_";
4019 Result += (*I)->getNameAsString();
4020 Result += ";\n";
4021 }
4022 Result += "#pragma data_seg(pop)\n\n";
4023 }
Steve Naroff4f943c22008-03-10 20:43:59 +00004024 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00004025 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004026 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
4027 Result += "&_OBJC_MODULES;\n";
4028 Result += "#pragma data_seg(pop)\n\n";
4029 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004030}
Chris Lattner311ff022007-10-16 22:36:42 +00004031
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004032void RewriteObjC::RewriteByRefString(std::string &ResultStr,
4033 const std::string &Name,
4034 ValueDecl *VD) {
4035 assert(BlockByRefDeclNo.count(VD) &&
4036 "RewriteByRefString: ByRef decl missing");
4037 ResultStr += "struct __Block_byref_" + Name +
4038 "_" + utostr(BlockByRefDeclNo[VD]) ;
4039}
4040
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004041static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4042 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4043 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4044 return false;
4045}
4046
Steve Naroff54055232008-10-27 17:20:55 +00004047std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Daniel Dunbar4087f272010-08-17 22:39:59 +00004048 llvm::StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00004049 std::string Tag) {
4050 const FunctionType *AFT = CE->getFunctionType();
4051 QualType RT = AFT->getResultType();
4052 std::string StructRef = "struct " + Tag;
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00004053 std::string S = "static " + RT.getAsString(Context->PrintingPolicy) + " __" +
Daniel Dunbar4087f272010-08-17 22:39:59 +00004054 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00004055
Steve Naroff54055232008-10-27 17:20:55 +00004056 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00004057
Douglas Gregor72564e72009-02-26 23:50:07 +00004058 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004059 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00004060 // block (to reference imported block decl refs).
4061 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00004062 } else if (BD->param_empty()) {
4063 S += "(" + StructRef + " *__cself)";
4064 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00004065 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00004066 assert(FT && "SynthesizeBlockFunc: No function proto");
4067 S += '(';
4068 // first add the implicit argument.
4069 S += StructRef + " *__cself, ";
4070 std::string ParamStr;
4071 for (BlockDecl::param_iterator AI = BD->param_begin(),
4072 E = BD->param_end(); AI != E; ++AI) {
4073 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004074 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004075 QualType QT = (*AI)->getType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004076 if (convertBlockPointerToFunctionPointer(QT))
4077 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004078 else
4079 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff54055232008-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 Stump1eb44332009-09-09 15:08:12 +00004089
Steve Naroff54055232008-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 Jahanianbab71682010-02-11 23:35:57 +00004092 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004093 E = BlockByRefDecls.end(); I != E; ++I) {
4094 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004095 std::string Name = (*I)->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004096 std::string TypeString;
4097 RewriteByRefString(TypeString, Name, (*I));
4098 TypeString += " *";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004099 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004100 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004101 }
Steve Naroff54055232008-10-27 17:20:55 +00004102 // Next, emit a declaration for all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004103 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004104 E = BlockByCopyDecls.end(); I != E; ++I) {
4105 S += " ";
Steve Naroff54055232008-10-27 17:20:55 +00004106 // Handle nested closure invocation. For example:
4107 //
4108 // void (^myImportedClosure)(void);
4109 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004110 //
Steve Naroff54055232008-10-27 17:20:55 +00004111 // void (^anotherClosure)(void);
4112 // anotherClosure = ^(void) {
4113 // myImportedClosure(); // import and invoke the closure
4114 // };
4115 //
Fariborz Jahaniane8c28df2010-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 Jahanian210c2482010-02-16 17:26:03 +00004124 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian6cb6eb42010-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 Jahaniane8c28df2010-02-16 16:21:26 +00004129 S += Name + " = __cself->" +
4130 (*I)->getNameAsString() + "; // bound by copy\n";
4131 }
Steve Naroff54055232008-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 Kyrtzidis39ba4ae2008-06-09 23:19:58 +00004140
Steve Naroff54055232008-10-27 17:20:55 +00004141std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Daniel Dunbar4087f272010-08-17 22:39:59 +00004142 llvm::StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00004143 std::string Tag) {
4144 std::string StructRef = "struct " + Tag;
4145 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00004146
Steve Naroff54055232008-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 Stump1eb44332009-09-09 15:08:12 +00004152 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004153 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00004154 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004155 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00004156 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004157 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004158 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004159 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004160 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004161 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004162 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004163 S += "}\n";
4164
Steve Naroff54055232008-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 Stump1eb44332009-09-09 15:08:12 +00004170 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004171 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00004172 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004173 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004174 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004175 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004176 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004177 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004178 }
Mike Stump1eb44332009-09-09 15:08:12 +00004179 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00004180 return S;
4181}
4182
Steve Naroff01aec112009-12-06 21:14:13 +00004183std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4184 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00004185 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00004186 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00004187
Steve Naroff54055232008-10-27 17:20:55 +00004188 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004189 S += " struct " + Desc;
4190 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004191
Steve Naroff01aec112009-12-06 21:14:13 +00004192 Constructor += "(void *fp, "; // Invoke function pointer.
4193 Constructor += "struct " + Desc; // Descriptor pointer.
4194 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00004195
Steve Naroff54055232008-10-27 17:20:55 +00004196 if (BlockDeclRefs.size()) {
4197 // Output all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004198 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004199 E = BlockByCopyDecls.end(); I != E; ++I) {
4200 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004201 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-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 Stump1eb44332009-09-09 15:08:12 +00004207 //
Steve Naroff54055232008-10-27 17:20:55 +00004208 // void (^anotherBlock)(void);
4209 // anotherBlock = ^(void) {
4210 // myImportedBlock(); // import and invoke the closure
4211 // };
4212 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004213 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00004214 S += "struct __block_impl *";
4215 Constructor += ", void *" + ArgName;
4216 } else {
Fariborz Jahanian6cb6eb42010-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 Naroff54055232008-10-27 17:20:55 +00004222 Constructor += ", " + ArgName;
4223 }
4224 S += FieldName + ";\n";
4225 }
4226 // Output all "by ref" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004227 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004228 E = BlockByRefDecls.end(); I != E; ++I) {
4229 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004230 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-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 Stump1eb44332009-09-09 15:08:12 +00004236 //
Steve Naroff54055232008-10-27 17:20:55 +00004237 // void (^anotherBlock)(void);
4238 // anotherBlock = ^(void) {
4239 // myImportedBlock(); // import and invoke the closure
4240 // };
4241 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004242 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00004243 S += "struct __block_impl *";
4244 Constructor += ", void *" + ArgName;
4245 } else {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004246 std::string TypeString;
4247 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004248 TypeString += " *";
4249 FieldName = TypeString + FieldName;
4250 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00004251 Constructor += ", " + ArgName;
4252 }
4253 S += FieldName + "; // by ref\n";
4254 }
4255 // Finish writing the constructor.
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004256 Constructor += ", int flags=0)";
4257 // Initialize all "by copy" arguments.
4258 bool firsTime = true;
4259 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4260 E = BlockByCopyDecls.end(); I != E; ++I) {
4261 std::string Name = (*I)->getNameAsString();
4262 if (firsTime) {
4263 Constructor += " : ";
4264 firsTime = false;
4265 }
4266 else
4267 Constructor += ", ";
4268 if (isTopLevelBlockPointerType((*I)->getType()))
4269 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4270 else
4271 Constructor += Name + "(_" + Name + ")";
4272 }
4273 // Initialize all "by ref" arguments.
4274 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4275 E = BlockByRefDecls.end(); I != E; ++I) {
4276 std::string Name = (*I)->getNameAsString();
4277 if (firsTime) {
4278 Constructor += " : ";
4279 firsTime = false;
4280 }
4281 else
4282 Constructor += ", ";
4283 if (isTopLevelBlockPointerType((*I)->getType()))
4284 Constructor += Name + "((struct __block_impl *)_"
4285 + Name + "->__forwarding)";
4286 else
4287 Constructor += Name + "(_" + Name + "->__forwarding)";
4288 }
4289
4290 Constructor += " {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004291 if (GlobalVarDecl)
4292 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4293 else
4294 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004295 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004296
Steve Naroff01aec112009-12-06 21:14:13 +00004297 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004298 } else {
4299 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00004300 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004301 if (GlobalVarDecl)
4302 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4303 else
4304 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004305 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4306 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004307 }
4308 Constructor += " ";
4309 Constructor += "}\n";
4310 S += Constructor;
4311 S += "};\n";
4312 return S;
4313}
4314
Steve Naroff01aec112009-12-06 21:14:13 +00004315std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4316 std::string ImplTag, int i,
Daniel Dunbar4087f272010-08-17 22:39:59 +00004317 llvm::StringRef FunName,
Steve Naroff01aec112009-12-06 21:14:13 +00004318 unsigned hasCopy) {
4319 std::string S = "\nstatic struct " + DescTag;
4320
4321 S += " {\n unsigned long reserved;\n";
4322 S += " unsigned long Block_size;\n";
4323 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004324 S += " void (*copy)(struct ";
4325 S += ImplTag; S += "*, struct ";
4326 S += ImplTag; S += "*);\n";
4327
4328 S += " void (*dispose)(struct ";
4329 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004330 }
4331 S += "} ";
4332
4333 S += DescTag + "_DATA = { 0, sizeof(struct ";
4334 S += ImplTag + ")";
4335 if (hasCopy) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00004336 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4337 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff01aec112009-12-06 21:14:13 +00004338 }
4339 S += "};\n";
4340 return S;
4341}
4342
Steve Naroff54055232008-10-27 17:20:55 +00004343void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Daniel Dunbar4087f272010-08-17 22:39:59 +00004344 llvm::StringRef FunName) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004345 // Insert declaration for the function in which block literal is used.
Fariborz Jahanianbf070122010-01-15 18:14:52 +00004346 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004347 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004348 bool RewriteSC = (GlobalVarDecl &&
4349 !Blocks.empty() &&
John McCalld931b082010-08-26 03:08:43 +00004350 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004351 GlobalVarDecl->getType().getCVRQualifiers());
4352 if (RewriteSC) {
4353 std::string SC(" void __");
4354 SC += GlobalVarDecl->getNameAsString();
4355 SC += "() {}";
4356 InsertText(FunLocStart, SC);
4357 }
4358
Steve Naroff54055232008-10-27 17:20:55 +00004359 // Insert closures that were part of the function.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004360 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4361 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004362 // Need to copy-in the inner copied-in variables not actually used in this
4363 // block.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004364 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4365 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
4366 ValueDecl *VD = Exp->getDecl();
4367 BlockDeclRefs.push_back(Exp);
4368 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
4369 BlockByCopyDeclsPtrSet.insert(VD);
4370 BlockByCopyDecls.push_back(VD);
4371 }
4372 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4373 BlockByRefDeclsPtrSet.insert(VD);
4374 BlockByRefDecls.push_back(VD);
4375 }
4376 }
Steve Naroff54055232008-10-27 17:20:55 +00004377
Daniel Dunbar4087f272010-08-17 22:39:59 +00004378 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4379 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00004380
Steve Naroff01aec112009-12-06 21:14:13 +00004381 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00004382
Benjamin Kramerd999b372010-02-14 14:14:16 +00004383 InsertText(FunLocStart, CI);
Steve Naroff54055232008-10-27 17:20:55 +00004384
Steve Naroff01aec112009-12-06 21:14:13 +00004385 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00004386
Benjamin Kramerd999b372010-02-14 14:14:16 +00004387 InsertText(FunLocStart, CF);
Steve Naroff54055232008-10-27 17:20:55 +00004388
4389 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00004390 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004391 InsertText(FunLocStart, HF);
Steve Naroff54055232008-10-27 17:20:55 +00004392 }
Steve Naroff01aec112009-12-06 21:14:13 +00004393 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4394 ImportedBlockDecls.size() > 0);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004395 InsertText(FunLocStart, BD);
Mike Stump1eb44332009-09-09 15:08:12 +00004396
Steve Naroff54055232008-10-27 17:20:55 +00004397 BlockDeclRefs.clear();
4398 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004399 BlockByRefDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004400 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004401 BlockByCopyDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004402 ImportedBlockDecls.clear();
4403 }
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004404 if (RewriteSC) {
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004405 // Must insert any 'const/volatile/static here. Since it has been
4406 // removed as result of rewriting of block literals.
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004407 std::string SC;
John McCalld931b082010-08-26 03:08:43 +00004408 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004409 SC = "static ";
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004410 if (GlobalVarDecl->getType().isConstQualified())
4411 SC += "const ";
4412 if (GlobalVarDecl->getType().isVolatileQualified())
4413 SC += "volatile ";
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004414 if (GlobalVarDecl->getType().isRestrictQualified())
4415 SC += "restrict ";
4416 InsertText(FunLocStart, SC);
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004417 }
4418
Steve Naroff54055232008-10-27 17:20:55 +00004419 Blocks.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004420 InnerDeclRefsCount.clear();
4421 InnerDeclRefs.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004422 RewrittenBlockExprs.clear();
4423}
4424
4425void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4426 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Daniel Dunbar4087f272010-08-17 22:39:59 +00004427 llvm::StringRef FuncName = FD->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00004428
Steve Naroff54055232008-10-27 17:20:55 +00004429 SynthesizeBlockLiterals(FunLocStart, FuncName);
4430}
4431
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004432static void BuildUniqueMethodName(std::string &Name,
4433 ObjCMethodDecl *MD) {
4434 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar4087f272010-08-17 22:39:59 +00004435 Name = IFace->getName();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004436 Name += "__" + MD->getSelector().getAsString();
4437 // Convert colons to underscores.
4438 std::string::size_type loc = 0;
4439 while ((loc = Name.find(":", loc)) != std::string::npos)
4440 Name.replace(loc, 1, "_");
4441}
4442
Steve Naroff54055232008-10-27 17:20:55 +00004443void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00004444 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4445 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanian0e1c99a2010-01-29 01:55:49 +00004446 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004447 std::string FuncName;
4448 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar4087f272010-08-17 22:39:59 +00004449 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff54055232008-10-27 17:20:55 +00004450}
4451
4452void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4453 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4454 CI != E; ++CI)
4455 if (*CI) {
4456 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4457 GetBlockDeclRefExprs(CBE->getBody());
4458 else
4459 GetBlockDeclRefExprs(*CI);
4460 }
4461 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004462 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Steve Naroff54055232008-10-27 17:20:55 +00004463 // FIXME: Handle enums.
4464 if (!isa<FunctionDecl>(CDRE->getDecl()))
4465 BlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004466 }
4467 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4468 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
4469 BlockDeclRefExpr *BDRE =
4470 new (Context)BlockDeclRefExpr(DRE->getDecl(), DRE->getType(),
4471 DRE->getLocation(), false);
4472 BlockDeclRefs.push_back(BDRE);
4473 }
4474
Steve Naroff54055232008-10-27 17:20:55 +00004475 return;
4476}
4477
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004478void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4479 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004480 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004481 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4482 CI != E; ++CI)
4483 if (*CI) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004484 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4485 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004486 GetInnerBlockDeclRefExprs(CBE->getBody(),
4487 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004488 InnerContexts);
4489 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004490 else
4491 GetInnerBlockDeclRefExprs(*CI,
4492 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004493 InnerContexts);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004494
4495 }
4496 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004497 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004498 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004499 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004500 InnerBlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004501 }
4502 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4503 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4504 if (Var->isFunctionOrMethodVarDecl())
4505 ImportedLocalExternalDecls.insert(Var);
4506 }
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004507
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004508 return;
4509}
4510
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004511/// convertFunctionTypeOfBlocks - This routine converts a function type
4512/// whose result type may be a block pointer or whose argument type(s)
4513/// might be block pointers to an equivalent funtion type replacing
4514/// all block pointers to function pointers.
4515QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4516 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4517 // FTP will be null for closures that don't take arguments.
4518 // Generate a funky cast.
4519 llvm::SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004520 QualType Res = FT->getResultType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004521 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004522
4523 if (FTP) {
4524 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4525 E = FTP->arg_type_end(); I && (I != E); ++I) {
4526 QualType t = *I;
4527 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004528 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004529 HasBlockType = true;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004530 ArgTypes.push_back(t);
4531 }
4532 }
4533 QualType FuncType;
4534 // FIXME. Does this work if block takes no argument but has a return type
4535 // which is of block type?
4536 if (HasBlockType)
4537 FuncType = Context->getFunctionType(Res,
4538 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0,
4539 false, false, 0, 0, FunctionType::ExtInfo());
4540 else FuncType = QualType(FT, 0);
4541 return FuncType;
4542}
4543
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004544Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00004545 // Navigate to relevant type information.
Steve Naroff54055232008-10-27 17:20:55 +00004546 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004547
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004548 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004549 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004550 } else if (const BlockDeclRefExpr *CDRE =
4551 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004552 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004553 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004554 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004555 }
4556 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4557 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4558 }
4559 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4560 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4561 else if (const ConditionalOperator *CEXPR =
4562 dyn_cast<ConditionalOperator>(BlockExp)) {
4563 Expr *LHSExp = CEXPR->getLHS();
4564 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4565 Expr *RHSExp = CEXPR->getRHS();
4566 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4567 Expr *CONDExp = CEXPR->getCond();
4568 ConditionalOperator *CondExpr =
4569 new (Context) ConditionalOperator(CONDExp,
4570 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00004571 SourceLocation(), cast<Expr>(RHSStmt),
4572 (Expr*)0,
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004573 Exp->getType());
4574 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00004575 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4576 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004577 } else {
4578 assert(1 && "RewriteBlockClass: Bad type");
4579 }
4580 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00004581 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00004582 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00004583 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00004584 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004585
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004586 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004587 SourceLocation(),
4588 &Context->Idents.get("__block_impl"));
4589 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00004590
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004591 // Generate a funky cast.
4592 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004593
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004594 // Push the block argument type.
4595 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00004596 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004597 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004598 E = FTP->arg_type_end(); I && (I != E); ++I) {
4599 QualType t = *I;
4600 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004601 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004602 ArgTypes.push_back(t);
4603 }
Steve Naroff54055232008-10-27 17:20:55 +00004604 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004605 // Now do the pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00004606 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00004607 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0,
4608 false, false, 0, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00004609 FunctionType::ExtInfo());
Mike Stump1eb44332009-09-09 15:08:12 +00004610
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004611 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00004612
John McCall9d125032010-01-15 18:39:57 +00004613 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCall2de56d12010-08-25 11:45:40 +00004614 CK_Unknown,
John McCall9d125032010-01-15 18:39:57 +00004615 const_cast<Expr*>(BlockExp));
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004616 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004617 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4618 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004619 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00004620
Douglas Gregor44b43212008-12-11 16:49:14 +00004621 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00004622 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004623 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004624 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4625 FD->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00004626
John McCall9d125032010-01-15 18:39:57 +00004627 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
John McCall2de56d12010-08-25 11:45:40 +00004628 CK_Unknown, ME);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004629 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00004630
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004631 llvm::SmallVector<Expr*, 8> BlkExprs;
4632 // Add the implicit argument.
4633 BlkExprs.push_back(BlkCast);
4634 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004635 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004636 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004637 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00004638 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004639 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4640 BlkExprs.size(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00004641 Exp->getType(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004642 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00004643}
4644
Steve Naroff621edce2009-04-29 16:37:50 +00004645// We need to return the rewritten expression to handle cases where the
4646// BlockDeclRefExpr is embedded in another expression being rewritten.
4647// For example:
4648//
4649// int main() {
4650// __block Foo *f;
4651// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00004652//
Steve Naroff621edce2009-04-29 16:37:50 +00004653// void (^myblock)() = ^() {
4654// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4655// i = 77;
4656// };
4657//}
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004658Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00004659 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004660 // for each DeclRefExp where BYREFVAR is name of the variable.
4661 ValueDecl *VD;
4662 bool isArrow = true;
4663 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4664 VD = BDRE->getDecl();
4665 else {
4666 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4667 isArrow = false;
4668 }
4669
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004670 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4671 &Context->Idents.get("__forwarding"),
4672 Context->VoidPtrTy, 0,
4673 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004674 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4675 FD, SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004676 FD->getType());
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004677
Daniel Dunbar4087f272010-08-17 22:39:59 +00004678 llvm::StringRef Name = VD->getName();
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004679 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4680 &Context->Idents.get(Name),
4681 Context->VoidPtrTy, 0,
4682 /*BitWidth=*/0, /*Mutable=*/true);
4683 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004684 DeclRefExp->getType());
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004685
4686
4687
Steve Naroffdf8570d2009-02-02 17:19:26 +00004688 // Need parens to enforce precedence.
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004689 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4690 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004691 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00004692 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00004693}
4694
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004695// Rewrites the imported local variable V with external storage
4696// (static, extern, etc.) as *V
4697//
4698Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4699 ValueDecl *VD = DRE->getDecl();
4700 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4701 if (!ImportedLocalExternalDecls.count(Var))
4702 return DRE;
John McCall2de56d12010-08-25 11:45:40 +00004703 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref,
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004704 DRE->getType(), DRE->getLocation());
4705 // Need parens to enforce precedence.
4706 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4707 Exp);
4708 ReplaceStmt(DRE, PE);
4709 return PE;
4710}
4711
Steve Naroffb2f9e512008-11-03 23:29:32 +00004712void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4713 SourceLocation LocStart = CE->getLParenLoc();
4714 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00004715
4716 // Need to avoid trying to rewrite synthesized casts.
4717 if (LocStart.isInvalid())
4718 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00004719 // Need to avoid trying to rewrite casts contained in macros.
4720 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4721 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004722
Steve Naroff54055232008-10-27 17:20:55 +00004723 const char *startBuf = SM->getCharacterData(LocStart);
4724 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004725 QualType QT = CE->getType();
4726 const Type* TypePtr = QT->getAs<Type>();
4727 if (isa<TypeOfExprType>(TypePtr)) {
4728 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4729 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4730 std::string TypeAsString = "(";
Fariborz Jahanianafad76f2010-02-18 01:20:22 +00004731 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004732 TypeAsString += ")";
Benjamin Kramerd999b372010-02-14 14:14:16 +00004733 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004734 return;
4735 }
Steve Naroff54055232008-10-27 17:20:55 +00004736 // advance the location to startArgList.
4737 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00004738
Steve Naroff54055232008-10-27 17:20:55 +00004739 while (*argPtr++ && (argPtr < endBuf)) {
4740 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004741 case '^':
4742 // Replace the '^' with '*'.
4743 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004744 ReplaceText(LocStart, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004745 break;
Steve Naroff54055232008-10-27 17:20:55 +00004746 }
4747 }
4748 return;
4749}
4750
4751void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4752 SourceLocation DeclLoc = FD->getLocation();
4753 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004754
Steve Naroff54055232008-10-27 17:20:55 +00004755 // We have 1 or more arguments that have closure pointers.
4756 const char *startBuf = SM->getCharacterData(DeclLoc);
4757 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00004758
Steve Naroff54055232008-10-27 17:20:55 +00004759 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004760
Steve Naroff54055232008-10-27 17:20:55 +00004761 parenCount++;
4762 // advance the location to startArgList.
4763 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4764 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00004765
Steve Naroff54055232008-10-27 17:20:55 +00004766 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00004767
Steve Naroff54055232008-10-27 17:20:55 +00004768 while (*argPtr++ && parenCount) {
4769 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004770 case '^':
4771 // Replace the '^' with '*'.
4772 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004773 ReplaceText(DeclLoc, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004774 break;
4775 case '(':
4776 parenCount++;
4777 break;
4778 case ')':
4779 parenCount--;
4780 break;
Steve Naroff54055232008-10-27 17:20:55 +00004781 }
4782 }
4783 return;
4784}
4785
4786bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004787 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004788 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004789 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004790 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004791 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004792 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004793 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004794 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004795 }
4796 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004797 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004798 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004799 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004800 return true;
4801 }
4802 return false;
4803}
4804
Ted Kremenek8189cde2009-02-07 01:47:29 +00004805void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4806 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00004807 const char *argPtr = strchr(Name, '(');
4808 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004809
Steve Naroff54055232008-10-27 17:20:55 +00004810 LParen = argPtr; // output the start.
4811 argPtr++; // skip past the left paren.
4812 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004813
Steve Naroff54055232008-10-27 17:20:55 +00004814 while (*argPtr && parenCount) {
4815 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004816 case '(': parenCount++; break;
4817 case ')': parenCount--; break;
4818 default: break;
Steve Naroff54055232008-10-27 17:20:55 +00004819 }
4820 if (parenCount) argPtr++;
4821 }
4822 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4823 RParen = argPtr; // output the end
4824}
4825
4826void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4827 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4828 RewriteBlockPointerFunctionArgs(FD);
4829 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004830 }
Steve Naroff54055232008-10-27 17:20:55 +00004831 // Handle Variables and Typedefs.
4832 SourceLocation DeclLoc = ND->getLocation();
4833 QualType DeclT;
4834 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4835 DeclT = VD->getType();
4836 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4837 DeclT = TDD->getUnderlyingType();
4838 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4839 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004840 else
Steve Naroff54055232008-10-27 17:20:55 +00004841 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00004842
Steve Naroff54055232008-10-27 17:20:55 +00004843 const char *startBuf = SM->getCharacterData(DeclLoc);
4844 const char *endBuf = startBuf;
4845 // scan backward (from the decl location) for the end of the previous decl.
4846 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4847 startBuf--;
Mike Stump1eb44332009-09-09 15:08:12 +00004848
Steve Naroff54055232008-10-27 17:20:55 +00004849 // *startBuf != '^' if we are dealing with a pointer to function that
4850 // may take block argument types (which will be handled below).
4851 if (*startBuf == '^') {
4852 // Replace the '^' with '*', computing a negative offset.
4853 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004854 ReplaceText(DeclLoc, 1, "*");
Steve Naroff54055232008-10-27 17:20:55 +00004855 }
4856 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4857 // Replace the '^' with '*' for arguments.
4858 DeclLoc = ND->getLocation();
4859 startBuf = SM->getCharacterData(DeclLoc);
4860 const char *argListBegin, *argListEnd;
4861 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4862 while (argListBegin < argListEnd) {
4863 if (*argListBegin == '^') {
4864 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004865 ReplaceText(CaretLoc, 1, "*");
Steve Naroff54055232008-10-27 17:20:55 +00004866 }
4867 argListBegin++;
4868 }
4869 }
4870 return;
4871}
4872
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004873
4874/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4875/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4876/// struct Block_byref_id_object *src) {
4877/// _Block_object_assign (&_dest->object, _src->object,
4878/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4879/// [|BLOCK_FIELD_IS_WEAK]) // object
4880/// _Block_object_assign(&_dest->object, _src->object,
4881/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4882/// [|BLOCK_FIELD_IS_WEAK]) // block
4883/// }
4884/// And:
4885/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4886/// _Block_object_dispose(_src->object,
4887/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4888/// [|BLOCK_FIELD_IS_WEAK]) // object
4889/// _Block_object_dispose(_src->object,
4890/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4891/// [|BLOCK_FIELD_IS_WEAK]) // block
4892/// }
4893
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004894std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4895 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004896 std::string S;
Benjamin Kramer1211a712010-01-10 19:57:50 +00004897 if (CopyDestroyCache.count(flag))
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004898 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004899 CopyDestroyCache.insert(flag);
4900 S = "static void __Block_byref_id_object_copy_";
4901 S += utostr(flag);
4902 S += "(void *dst, void *src) {\n";
4903
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004904 // offset into the object pointer is computed as:
4905 // void * + void* + int + int + void* + void *
4906 unsigned IntSize =
4907 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4908 unsigned VoidPtrSize =
4909 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4910
4911 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
4912 S += " _Block_object_assign((char*)dst + ";
4913 S += utostr(offset);
4914 S += ", *(void * *) ((char*)src + ";
4915 S += utostr(offset);
4916 S += "), ";
4917 S += utostr(flag);
4918 S += ");\n}\n";
4919
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004920 S += "static void __Block_byref_id_object_dispose_";
4921 S += utostr(flag);
4922 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004923 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4924 S += utostr(offset);
4925 S += "), ";
4926 S += utostr(flag);
4927 S += ");\n}\n";
4928 return S;
4929}
4930
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004931/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4932/// the declaration into:
4933/// struct __Block_byref_ND {
4934/// void *__isa; // NULL for everything except __weak pointers
4935/// struct __Block_byref_ND *__forwarding;
4936/// int32_t __flags;
4937/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004938/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4939/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004940/// typex ND;
4941/// };
4942///
4943/// It then replaces declaration of ND variable with:
4944/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4945/// __size=sizeof(struct __Block_byref_ND),
4946/// ND=initializer-if-any};
4947///
4948///
4949void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004950 // Insert declaration for the function in which block literal is
4951 // used.
4952 if (CurFunctionDeclToDeclareForBlock)
4953 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004954 int flag = 0;
4955 int isa = 0;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004956 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahaniand64a4f42010-02-26 22:49:11 +00004957 if (DeclLoc.isInvalid())
4958 // If type location is missing, it is because of missing type (a warning).
4959 // Use variable's location which is good for this case.
4960 DeclLoc = ND->getLocation();
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004961 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00004962 SourceLocation X = ND->getLocEnd();
4963 X = SM->getInstantiationLoc(X);
4964 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004965 std::string Name(ND->getNameAsString());
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004966 std::string ByrefType;
4967 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004968 ByrefType += " {\n";
4969 ByrefType += " void *__isa;\n";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004970 RewriteByRefString(ByrefType, Name, ND);
4971 ByrefType += " *__forwarding;\n";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004972 ByrefType += " int __flags;\n";
4973 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004974 // Add void *__Block_byref_id_object_copy;
4975 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004976 QualType Ty = ND->getType();
4977 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4978 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004979 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4980 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004981 }
4982
4983 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004984 ByrefType += " " + Name + ";\n";
4985 ByrefType += "};\n";
4986 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004987 SourceLocation FunLocStart;
4988 if (CurFunctionDef)
4989 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4990 else {
4991 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4992 FunLocStart = CurMethodDef->getLocStart();
4993 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00004994 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004995 if (Ty.isObjCGCWeak()) {
4996 flag |= BLOCK_FIELD_IS_WEAK;
4997 isa = 1;
4998 }
4999
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005000 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005001 flag = BLOCK_BYREF_CALLER;
5002 QualType Ty = ND->getType();
5003 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5004 if (Ty->isBlockPointerType())
5005 flag |= BLOCK_FIELD_IS_BLOCK;
5006 else
5007 flag |= BLOCK_FIELD_IS_OBJECT;
5008 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005009 if (!HF.empty())
Benjamin Kramerd999b372010-02-14 14:14:16 +00005010 InsertText(FunLocStart, HF);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005011 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005012
5013 // struct __Block_byref_ND ND =
5014 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5015 // initializer-if-any};
5016 bool hasInit = (ND->getInit() != 0);
Fariborz Jahaniane1f84f82010-01-05 18:15:57 +00005017 unsigned flags = 0;
5018 if (HasCopyAndDispose)
5019 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005020 Name = ND->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005021 ByrefType.clear();
5022 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005023 std::string ForwardingCastType("(");
5024 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005025 if (!hasInit) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005026 ByrefType += " " + Name + " = {(void*)";
5027 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005028 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005029 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005030 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005031 ByrefType += "sizeof(";
5032 RewriteByRefString(ByrefType, Name, ND);
5033 ByrefType += ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005034 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005035 ByrefType += ", __Block_byref_id_object_copy_";
5036 ByrefType += utostr(flag);
5037 ByrefType += ", __Block_byref_id_object_dispose_";
5038 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005039 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005040 ByrefType += "};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00005041 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(), ByrefType);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005042 }
5043 else {
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005044 SourceLocation startLoc;
5045 Expr *E = ND->getInit();
5046 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5047 startLoc = ECE->getLParenLoc();
5048 else
5049 startLoc = E->getLocStart();
Fariborz Jahanian791b10d2010-01-05 23:06:29 +00005050 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005051 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005052 ByrefType += " " + Name;
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005053 ByrefType += " = {(void*)";
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005054 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005055 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005056 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005057 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005058 ByrefType += "sizeof(";
5059 RewriteByRefString(ByrefType, Name, ND);
5060 ByrefType += "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005061 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005062 ByrefType += "__Block_byref_id_object_copy_";
5063 ByrefType += utostr(flag);
5064 ByrefType += ", __Block_byref_id_object_dispose_";
5065 ByrefType += utostr(flag);
5066 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005067 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00005068 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroffc5143c52009-12-23 17:24:33 +00005069
5070 // Complete the newly synthesized compound expression by inserting a right
5071 // curly brace before the end of the declaration.
5072 // FIXME: This approach avoids rewriting the initializer expression. It
5073 // also assumes there is only one declarator. For example, the following
5074 // isn't currently supported by this routine (in general):
5075 //
5076 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
5077 //
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00005078 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5079 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroffc5143c52009-12-23 17:24:33 +00005080 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
5081 SourceLocation semiLoc =
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00005082 startLoc.getFileLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroffc5143c52009-12-23 17:24:33 +00005083
Benjamin Kramerd999b372010-02-14 14:14:16 +00005084 InsertText(semiLoc, "}");
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005085 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00005086 return;
5087}
5088
Mike Stump1eb44332009-09-09 15:08:12 +00005089void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00005090 // Add initializers for any closure decl refs.
5091 GetBlockDeclRefExprs(Exp->getBody());
5092 if (BlockDeclRefs.size()) {
5093 // Unique all "by copy" declarations.
5094 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005095 if (!BlockDeclRefs[i]->isByRef()) {
5096 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5097 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5098 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5099 }
5100 }
Steve Naroff54055232008-10-27 17:20:55 +00005101 // Unique all "by ref" declarations.
5102 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5103 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005104 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5105 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5106 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5107 }
Steve Naroff54055232008-10-27 17:20:55 +00005108 }
5109 // Find any imported blocks...they will need special attention.
5110 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00005111 if (BlockDeclRefs[i]->isByRef() ||
5112 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian5b011b02010-02-26 21:46:27 +00005113 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff54055232008-10-27 17:20:55 +00005114 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff54055232008-10-27 17:20:55 +00005115 }
5116}
5117
Daniel Dunbar4087f272010-08-17 22:39:59 +00005118FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(llvm::StringRef name) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005119 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00005120 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump1eb44332009-09-09 15:08:12 +00005121 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
John McCalld931b082010-08-26 03:08:43 +00005122 ID, FType, 0, SC_Extern,
5123 SC_None, false, false);
Steve Narofffa15fd92008-10-28 20:29:00 +00005124}
5125
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005126Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
5127 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005128 Blocks.push_back(Exp);
5129
5130 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005131
5132 // Add inner imported variables now used in current block.
5133 int countOfInnerDecls = 0;
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005134 if (!InnerBlockDeclRefs.empty()) {
5135 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5136 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
5137 ValueDecl *VD = Exp->getDecl();
5138 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005139 // We need to save the copied-in variables in nested
5140 // blocks because it is needed at the end for some of the API generations.
5141 // See SynthesizeBlockLiterals routine.
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005142 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5143 BlockDeclRefs.push_back(Exp);
5144 BlockByCopyDeclsPtrSet.insert(VD);
5145 BlockByCopyDecls.push_back(VD);
5146 }
5147 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
5148 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5149 BlockDeclRefs.push_back(Exp);
5150 BlockByRefDeclsPtrSet.insert(VD);
5151 BlockByRefDecls.push_back(VD);
5152 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005153 }
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005154 // Find any imported blocks...they will need special attention.
5155 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5156 if (InnerBlockDeclRefs[i]->isByRef() ||
5157 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5158 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5159 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005160 }
5161 InnerDeclRefsCount.push_back(countOfInnerDecls);
5162
Steve Narofffa15fd92008-10-28 20:29:00 +00005163 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00005164
Steve Narofffa15fd92008-10-28 20:29:00 +00005165 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00005166 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00005167 else if (CurMethodDef)
5168 BuildUniqueMethodName(FuncName, CurMethodDef);
5169 else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005170 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00005171
Steve Narofffa15fd92008-10-28 20:29:00 +00005172 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00005173
Steve Narofffa15fd92008-10-28 20:29:00 +00005174 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
5175 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00005176
Steve Narofffa15fd92008-10-28 20:29:00 +00005177 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian1f906222010-05-25 15:56:08 +00005178 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5179 QualType FType = Context->getPointerType(BFT);
Steve Narofffa15fd92008-10-28 20:29:00 +00005180
5181 FunctionDecl *FD;
5182 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00005183
Steve Narofffa15fd92008-10-28 20:29:00 +00005184 // Simulate a contructor call...
Daniel Dunbar4087f272010-08-17 22:39:59 +00005185 FD = SynthBlockInitFunctionDecl(Tag);
Ted Kremenek8189cde2009-02-07 01:47:29 +00005186 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00005187
Steve Narofffa15fd92008-10-28 20:29:00 +00005188 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00005189
Steve Narofffdc03722008-10-29 21:23:59 +00005190 // Initialize the block function.
Daniel Dunbar4087f272010-08-17 22:39:59 +00005191 FD = SynthBlockInitFunctionDecl(Func);
Ted Kremenek8189cde2009-02-07 01:47:29 +00005192 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
5193 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005194 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCall2de56d12010-08-25 11:45:40 +00005195 CK_Unknown, Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00005196 InitExprs.push_back(castExpr);
5197
Steve Naroff01aec112009-12-06 21:14:13 +00005198 // Initialize the block descriptor.
5199 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00005200
Steve Naroff01aec112009-12-06 21:14:13 +00005201 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
5202 &Context->Idents.get(DescData.c_str()),
5203 Context->VoidPtrTy, 0,
John McCalld931b082010-08-26 03:08:43 +00005204 SC_Static, SC_None);
Steve Naroff01aec112009-12-06 21:14:13 +00005205 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
5206 new (Context) DeclRefExpr(NewVD,
5207 Context->VoidPtrTy, SourceLocation()),
John McCall2de56d12010-08-25 11:45:40 +00005208 UO_AddrOf,
Steve Naroff01aec112009-12-06 21:14:13 +00005209 Context->getPointerType(Context->VoidPtrTy),
5210 SourceLocation());
5211 InitExprs.push_back(DescRefExpr);
5212
Steve Narofffa15fd92008-10-28 20:29:00 +00005213 // Add initializers for any closure decl refs.
5214 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00005215 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00005216 // Output all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005217 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005218 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005219 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00005220 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar4087f272010-08-17 22:39:59 +00005221 FD = SynthBlockInitFunctionDecl((*I)->getName());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005222 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00005223 if (HasLocalVariableExternalStorage(*I)) {
5224 QualType QT = (*I)->getType();
5225 QT = Context->getPointerType(QT);
John McCall2de56d12010-08-25 11:45:40 +00005226 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT,
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00005227 SourceLocation());
5228 }
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005229 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00005230 FD = SynthBlockInitFunctionDecl((*I)->getName());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005231 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005232 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCall2de56d12010-08-25 11:45:40 +00005233 CK_Unknown, Arg);
Steve Narofffa15fd92008-10-28 20:29:00 +00005234 } else {
Daniel Dunbar4087f272010-08-17 22:39:59 +00005235 FD = SynthBlockInitFunctionDecl((*I)->getName());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005236 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005237 if (HasLocalVariableExternalStorage(*I)) {
5238 QualType QT = (*I)->getType();
5239 QT = Context->getPointerType(QT);
John McCall2de56d12010-08-25 11:45:40 +00005240 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT,
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005241 SourceLocation());
5242 }
5243
Steve Narofffa15fd92008-10-28 20:29:00 +00005244 }
Mike Stump1eb44332009-09-09 15:08:12 +00005245 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005246 }
5247 // Output all "by ref" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005248 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005249 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005250 ValueDecl *ND = (*I);
5251 std::string Name(ND->getNameAsString());
5252 std::string RecName;
5253 RewriteByRefString(RecName, Name, ND);
5254 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5255 + sizeof("struct"));
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005256 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005257 SourceLocation(), II);
5258 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5259 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5260
Daniel Dunbar4087f272010-08-17 22:39:59 +00005261 FD = SynthBlockInitFunctionDecl((*I)->getName());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005262 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00005263 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00005264 Context->getPointerType(Exp->getType()),
Steve Narofffdc03722008-10-29 21:23:59 +00005265 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00005266 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_Unknown, Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00005267 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005268 }
5269 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00005270 if (ImportedBlockDecls.size()) {
5271 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5272 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00005273 unsigned IntSize =
5274 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005275 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5276 Context->IntTy, SourceLocation());
Fariborz Jahanianff127882009-12-23 21:52:32 +00005277 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00005278 }
Ted Kremenek668bf912009-02-09 20:51:47 +00005279 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
5280 FType, SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00005281 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00005282 Context->getPointerType(NewRep->getType()),
Steve Narofffa15fd92008-10-28 20:29:00 +00005283 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00005284 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_Unknown,
John McCall9d125032010-01-15 18:39:57 +00005285 NewRep);
Steve Narofffa15fd92008-10-28 20:29:00 +00005286 BlockDeclRefs.clear();
5287 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005288 BlockByRefDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005289 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005290 BlockByCopyDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005291 ImportedBlockDecls.clear();
5292 return NewRep;
5293}
5294
5295//===----------------------------------------------------------------------===//
5296// Function Body / Expression rewriting
5297//===----------------------------------------------------------------------===//
5298
Steve Naroffc77a6362008-12-04 16:24:46 +00005299// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
5300// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
5301// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
5302// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
5303// Since the rewriter isn't capable of rewriting rewritten code, it's important
5304// we get this right.
5305void RewriteObjC::CollectPropertySetters(Stmt *S) {
5306 // Perform a bottom up traversal of all children.
5307 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5308 CI != E; ++CI)
5309 if (*CI)
5310 CollectPropertySetters(*CI);
5311
5312 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
5313 if (BinOp->isAssignmentOp()) {
5314 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
5315 PropSetters[PRE] = BinOp;
5316 }
5317 }
5318}
5319
Steve Narofffa15fd92008-10-28 20:29:00 +00005320Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00005321 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005322 isa<DoStmt>(S) || isa<ForStmt>(S))
5323 Stmts.push_back(S);
5324 else if (isa<ObjCForCollectionStmt>(S)) {
5325 Stmts.push_back(S);
Chris Lattner4824fcd2010-01-09 21:45:57 +00005326 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00005327 }
Mike Stump1eb44332009-09-09 15:08:12 +00005328
Steve Narofffa15fd92008-10-28 20:29:00 +00005329 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005330
Steve Narofffa15fd92008-10-28 20:29:00 +00005331 // Perform a bottom up rewrite of all children.
5332 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5333 CI != E; ++CI)
5334 if (*CI) {
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005335 Stmt *newStmt;
5336 Stmt *S = (*CI);
5337 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5338 Expr *OldBase = IvarRefExpr->getBase();
5339 bool replaced = false;
5340 newStmt = RewriteObjCNestedIvarRefExpr(S, replaced);
5341 if (replaced) {
5342 if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
5343 ReplaceStmt(OldBase, IRE->getBase());
5344 else
5345 ReplaceStmt(S, newStmt);
5346 }
5347 }
5348 else
5349 newStmt = RewriteFunctionBodyOrGlobalInitializer(S);
Mike Stump1eb44332009-09-09 15:08:12 +00005350 if (newStmt)
Steve Narofffa15fd92008-10-28 20:29:00 +00005351 *CI = newStmt;
5352 }
Mike Stump1eb44332009-09-09 15:08:12 +00005353
Steve Narofffa15fd92008-10-28 20:29:00 +00005354 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005355 llvm::SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005356 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5357 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005358 ImportedLocalExternalDecls.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005359 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005360 InnerBlockDeclRefs, InnerContexts);
Steve Narofffa15fd92008-10-28 20:29:00 +00005361 // Rewrite the block body in place.
5362 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005363 ImportedLocalExternalDecls.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005364 // Now we snarf the rewritten text and stash it away for later use.
Ted Kremenek6a12a142010-01-07 18:00:35 +00005365 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005366 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00005367
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005368 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5369
Steve Narofffa15fd92008-10-28 20:29:00 +00005370 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005371 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00005372 return blockTranscribed;
5373 }
5374 // Handle specific things.
5375 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5376 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00005377
Steve Naroffc77a6362008-12-04 16:24:46 +00005378 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
5379 BinaryOperator *BinOp = PropSetters[PropRefExpr];
5380 if (BinOp) {
5381 // Because the rewriter doesn't allow us to rewrite rewritten code,
5382 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffb619d952008-12-09 12:56:34 +00005383 DisableReplaceStmt = true;
5384 // Save the source range. Even if we disable the replacement, the
5385 // rewritten node will have been inserted into the tree. If the synthesized
5386 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump1eb44332009-09-09 15:08:12 +00005387 // self.errorHandler = handler ? handler :
Steve Naroffb619d952008-12-09 12:56:34 +00005388 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
5389 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroffc77a6362008-12-04 16:24:46 +00005390 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroffb619d952008-12-09 12:56:34 +00005391 DisableReplaceStmt = false;
Steve Naroff4c3580e2008-12-04 23:50:32 +00005392 //
5393 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
5394 // we changed the RHS of BinOp, the rewriter would fail (since it needs
5395 // to see the original expression). Consider this example:
5396 //
5397 // Foo *obj1, *obj2;
5398 //
5399 // obj1.i = [obj2 rrrr];
5400 //
5401 // 'BinOp' for the previous expression looks like:
5402 //
5403 // (BinaryOperator 0x231ccf0 'int' '='
5404 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
5405 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
5406 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
5407 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
5408 //
5409 // 'newStmt' represents the rewritten message expression. For example:
5410 //
5411 // (CallExpr 0x231d300 'id':'struct objc_object *'
5412 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
5413 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
5414 // (CStyleCastExpr 0x231d220 'void *'
5415 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
5416 //
5417 // Note that 'newStmt' is passed to RewritePropertySetter so that it
5418 // can be used as the setter argument. ReplaceStmt() will still 'see'
5419 // the original RHS (since we haven't altered BinOp).
5420 //
Mike Stump1eb44332009-09-09 15:08:12 +00005421 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff4c3580e2008-12-04 23:50:32 +00005422 // node. As a result, we now leak the original AST nodes.
5423 //
Steve Naroffb619d952008-12-09 12:56:34 +00005424 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroffc77a6362008-12-04 16:24:46 +00005425 } else {
5426 return RewritePropertyGetter(PropRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00005427 }
5428 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005429 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5430 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00005431
Steve Narofffa15fd92008-10-28 20:29:00 +00005432 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5433 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00005434
Steve Narofffa15fd92008-10-28 20:29:00 +00005435 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00005436#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00005437 // Before we rewrite it, put the original message expression in a comment.
5438 SourceLocation startLoc = MessExpr->getLocStart();
5439 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00005440
Steve Narofffa15fd92008-10-28 20:29:00 +00005441 const char *startBuf = SM->getCharacterData(startLoc);
5442 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00005443
Steve Narofffa15fd92008-10-28 20:29:00 +00005444 std::string messString;
5445 messString += "// ";
5446 messString.append(startBuf, endBuf-startBuf+1);
5447 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00005448
5449 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00005450 // InsertText(clang::SourceLocation, char const*, unsigned int).
5451 // InsertText(startLoc, messString.c_str(), messString.size());
5452 // Tried this, but it didn't work either...
5453 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00005454#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00005455 return RewriteMessageExpr(MessExpr);
5456 }
Mike Stump1eb44332009-09-09 15:08:12 +00005457
Steve Narofffa15fd92008-10-28 20:29:00 +00005458 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5459 return RewriteObjCTryStmt(StmtTry);
5460
5461 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5462 return RewriteObjCSynchronizedStmt(StmtTry);
5463
5464 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5465 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00005466
Steve Narofffa15fd92008-10-28 20:29:00 +00005467 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5468 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00005469
5470 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00005471 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00005472 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00005473 OrigStmtRange.getEnd());
5474 if (BreakStmt *StmtBreakStmt =
5475 dyn_cast<BreakStmt>(S))
5476 return RewriteBreakStmt(StmtBreakStmt);
5477 if (ContinueStmt *StmtContinueStmt =
5478 dyn_cast<ContinueStmt>(S))
5479 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00005480
5481 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00005482 // and cast exprs.
5483 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5484 // FIXME: What we're doing here is modifying the type-specifier that
5485 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00005486 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00005487 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5488 // the context of an ObjCForCollectionStmt. For example:
5489 // NSArray *someArray;
5490 // for (id <FooProtocol> index in someArray) ;
5491 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5492 // and it depends on the original text locations/positions.
Benjamin Kramerb2041de2009-12-05 22:16:51 +00005493 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroff3d7e7862009-12-05 15:55:59 +00005494 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00005495
Steve Narofffa15fd92008-10-28 20:29:00 +00005496 // Blocks rewrite rules.
5497 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5498 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00005499 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00005500 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005501 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005502 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00005503 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005504 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005505 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005506 if (VD->hasAttr<BlocksAttr>()) {
5507 static unsigned uniqueByrefDeclCount = 0;
5508 assert(!BlockByRefDeclNo.count(ND) &&
5509 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5510 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005511 RewriteByRefVar(VD);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005512 }
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005513 else
5514 RewriteTypeOfDecl(VD);
5515 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005516 }
5517 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005518 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005519 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005520 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005521 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5522 }
5523 }
5524 }
Mike Stump1eb44332009-09-09 15:08:12 +00005525
Steve Narofffa15fd92008-10-28 20:29:00 +00005526 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5527 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00005528
5529 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005530 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5531 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00005532 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5533 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005534 && "Statement stack mismatch");
5535 Stmts.pop_back();
5536 }
5537 // Handle blocks rewriting.
5538 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5539 if (BDRE->isByRef())
Steve Naroff621edce2009-04-29 16:37:50 +00005540 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofffa15fd92008-10-28 20:29:00 +00005541 }
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005542 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5543 ValueDecl *VD = DRE->getDecl();
5544 if (VD->hasAttr<BlocksAttr>())
5545 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005546 if (HasLocalVariableExternalStorage(VD))
5547 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005548 }
5549
Steve Narofffa15fd92008-10-28 20:29:00 +00005550 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005551 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00005552 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005553 ReplaceStmt(S, BlockCall);
5554 return BlockCall;
5555 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005556 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00005557 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005558 RewriteCastExpr(CE);
5559 }
5560#if 0
5561 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redl906082e2010-07-20 04:20:21 +00005562 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5563 ICE->getSubExpr(),
5564 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00005565 // Get the new text.
5566 std::string SStr;
5567 llvm::raw_string_ostream Buf(SStr);
Eli Friedman3a9eb442009-05-30 05:19:26 +00005568 Replacement->printPretty(Buf, *Context);
Steve Narofffa15fd92008-10-28 20:29:00 +00005569 const std::string &Str = Buf.str();
5570
5571 printf("CAST = %s\n", &Str[0]);
5572 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5573 delete S;
5574 return Replacement;
5575 }
5576#endif
5577 // Return this stmt unmodified.
5578 return S;
5579}
5580
Steve Naroff3d7e7862009-12-05 15:55:59 +00005581void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5582 for (RecordDecl::field_iterator i = RD->field_begin(),
5583 e = RD->field_end(); i != e; ++i) {
5584 FieldDecl *FD = *i;
5585 if (isTopLevelBlockPointerType(FD->getType()))
5586 RewriteBlockPointerDecl(FD);
5587 if (FD->getType()->isObjCQualifiedIdType() ||
5588 FD->getType()->isObjCQualifiedInterfaceType())
5589 RewriteObjCQualifiedInterfaceTypes(FD);
5590 }
5591}
5592
Steve Narofffa15fd92008-10-28 20:29:00 +00005593/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5594/// main file of the input.
5595void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5596 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffcb735302008-12-17 00:20:22 +00005597 if (FD->isOverloadedOperator())
5598 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005599
Steve Narofffa15fd92008-10-28 20:29:00 +00005600 // Since function prototypes don't have ParmDecl's, we check the function
5601 // prototype. This enables us to rewrite function declarations and
5602 // definitions using the same code.
Douglas Gregor72564e72009-02-26 23:50:07 +00005603 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005604
Sebastian Redld3a413d2009-04-26 20:35:05 +00005605 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidis5f1bfc12010-07-07 11:31:34 +00005606 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005607 CurFunctionDef = FD;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005608 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005609 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005610 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005611 Body =
5612 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5613 FD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005614 CurrentBody = 0;
5615 if (PropParentMap) {
5616 delete PropParentMap;
5617 PropParentMap = 0;
5618 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005619 // This synthesizes and inserts the block "impl" struct, invoke function,
5620 // and any copy/dispose helper functions.
5621 InsertBlockLiteralsWithinFunction(FD);
5622 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005623 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00005624 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005625 return;
5626 }
5627 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005628 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005629 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005630 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005631 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005632 Body =
5633 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5634 MD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005635 CurrentBody = 0;
5636 if (PropParentMap) {
5637 delete PropParentMap;
5638 PropParentMap = 0;
5639 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005640 InsertBlockLiteralsWithinMethod(MD);
5641 CurMethodDef = 0;
5642 }
5643 }
5644 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5645 ClassImplementation.push_back(CI);
5646 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5647 CategoryImplementation.push_back(CI);
5648 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5649 RewriteForwardClassDecl(CD);
5650 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5651 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005652 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005653 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005654 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005655 CheckFunctionPointerDecl(VD->getType(), VD);
5656 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00005657 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005658 RewriteCastExpr(CE);
5659 }
5660 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00005661 } else if (VD->getType()->isRecordType()) {
5662 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5663 if (RD->isDefinition())
5664 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005665 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005666 if (VD->getInit()) {
5667 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005668 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005669 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005670 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005671 CurrentBody = 0;
5672 if (PropParentMap) {
5673 delete PropParentMap;
5674 PropParentMap = 0;
5675 }
Mike Stump1eb44332009-09-09 15:08:12 +00005676 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00005677 VD->getName());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005678 GlobalVarDecl = 0;
5679
5680 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00005681 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005682 RewriteCastExpr(CE);
5683 }
5684 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005685 return;
5686 }
5687 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005688 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005689 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005690 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005691 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5692 return;
5693 }
5694 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroff3d7e7862009-12-05 15:55:59 +00005695 if (RD->isDefinition())
5696 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005697 return;
5698 }
5699 // Nothing yet.
5700}
5701
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00005702void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005703 if (Diags.hasErrorOccurred())
5704 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005705
Steve Narofffa15fd92008-10-28 20:29:00 +00005706 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00005707
Steve Naroff621edce2009-04-29 16:37:50 +00005708 // Here's a great place to add any extra declarations that may be needed.
5709 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00005710 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00005711 E = ProtocolExprDecls.end(); I != E; ++I)
5712 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5713
Benjamin Kramerd999b372010-02-14 14:14:16 +00005714 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff0aab7962008-11-14 14:10:01 +00005715 if (ClassImplementation.size() || CategoryImplementation.size())
5716 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00005717
Steve Narofffa15fd92008-10-28 20:29:00 +00005718 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5719 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00005720 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00005721 Rewrite.getRewriteBufferFor(MainFileID)) {
5722 //printf("Changed:\n");
5723 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5724 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +00005725 llvm::errs() << "No changes\n";
Steve Narofffa15fd92008-10-28 20:29:00 +00005726 }
Steve Narofface66252008-11-13 20:07:04 +00005727
Steve Naroff621edce2009-04-29 16:37:50 +00005728 if (ClassImplementation.size() || CategoryImplementation.size() ||
5729 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00005730 // Rewrite Objective-c meta data*
5731 std::string ResultStr;
5732 SynthesizeMetaDataIntoBuffer(ResultStr);
5733 // Emit metadata.
5734 *OutFile << ResultStr;
5735 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005736 OutFile->flush();
5737}